(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define("babylonjs", [], factory); else if(typeof exports === 'object') exports["babylonjs"] = factory(); else root["BABYLON"] = factory(); })((typeof self !== "undefined" ? self : typeof global !== "undefined" ? global : this), function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./Legacy/legacy.ts"); /******/ }) /************************************************************************/ /******/ ({ /***/ "../node_modules/tslib/tslib.es6.js": /*!******************************************!*\ !*** ../node_modules/tslib/tslib.es6.js ***! \******************************************/ /*! exports provided: __extends, __assign, __rest, __decorate, __param, __metadata, __awaiter, __generator, __exportStar, __values, __read, __spread, __await, __asyncGenerator, __asyncDelegator, __asyncValues, __makeTemplateObject, __importStar, __importDefault */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__extends", function() { return __extends; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__assign", function() { return __assign; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__rest", function() { return __rest; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__decorate", function() { return __decorate; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__param", function() { return __param; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__metadata", function() { return __metadata; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__awaiter", function() { return __awaiter; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__generator", function() { return __generator; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__exportStar", function() { return __exportStar; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__values", function() { return __values; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__read", function() { return __read; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spread", function() { return __spread; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__await", function() { return __await; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncGenerator", function() { return __asyncGenerator; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncDelegator", function() { return __asyncDelegator; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncValues", function() { return __asyncValues; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__makeTemplateObject", function() { return __makeTemplateObject; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importStar", function() { return __importStar; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importDefault", function() { return __importDefault; }); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign(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; } return __assign.apply(this, arguments); } 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) 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) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, 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]); }; } 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 }; } } function __exportStar(m, exports) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } function __values(o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; if (m) return m.call(o); return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; } 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: 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 __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); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } 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; } } 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); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } } 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 (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result.default = mod; return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } /***/ }), /***/ "../node_modules/webpack/buildin/global.js": /*!*************************************************!*\ !*** ../node_modules/webpack/buildin/global.js ***! \*************************************************/ /*! no static exports found */ /***/ (function(module, exports) { var g; // This works in non-strict mode g = (function() { return this; })(); try { // This works if eval is allowed (see CSP) g = g || new Function("return this")(); } catch (e) { // This works if the window reference is available if (typeof window === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /***/ "./Actions/abstractActionManager.ts": /*!******************************************!*\ !*** ./Actions/abstractActionManager.ts ***! \******************************************/ /*! exports provided: AbstractActionManager */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AbstractActionManager", function() { return AbstractActionManager; }); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); /** * Abstract class used to decouple action Manager from scene and meshes. * Do not instantiate. * @see http://doc.babylonjs.com/how_to/how_to_use_actions */ var AbstractActionManager = /** @class */ (function () { function AbstractActionManager() { /** Gets the cursor to use when hovering items */ this.hoverCursor = ''; /** Gets the list of actions */ this.actions = new Array(); /** * Gets or sets a boolean indicating that the manager is recursive meaning that it can trigger action from children */ this.isRecursive = false; } Object.defineProperty(AbstractActionManager, "HasTriggers", { /** * Does exist one action manager with at least one trigger **/ get: function () { for (var t in AbstractActionManager.Triggers) { if (AbstractActionManager.Triggers.hasOwnProperty(t)) { return true; } } return false; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractActionManager, "HasPickTriggers", { /** * Does exist one action manager with at least one pick trigger **/ get: function () { for (var t in AbstractActionManager.Triggers) { if (AbstractActionManager.Triggers.hasOwnProperty(t)) { var t_int = parseInt(t); if (t_int >= _Engines_constants__WEBPACK_IMPORTED_MODULE_0__["Constants"].ACTION_OnPickTrigger && t_int <= _Engines_constants__WEBPACK_IMPORTED_MODULE_0__["Constants"].ACTION_OnPickUpTrigger) { return true; } } } return false; }, enumerable: true, configurable: true }); /** * Does exist one action manager that handles actions of a given trigger * @param trigger defines the trigger to be tested * @return a boolean indicating whether the trigger is handeled by at least one action manager **/ AbstractActionManager.HasSpecificTrigger = function (trigger) { for (var t in AbstractActionManager.Triggers) { if (AbstractActionManager.Triggers.hasOwnProperty(t)) { var t_int = parseInt(t); if (t_int === trigger) { return true; } } } return false; }; /** Gets the list of active triggers */ AbstractActionManager.Triggers = {}; return AbstractActionManager; }()); /***/ }), /***/ "./Actions/action.ts": /*!***************************!*\ !*** ./Actions/action.ts ***! \***************************/ /*! exports provided: Action */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Action", function() { return Action; }); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); /** * The action to be carried out following a trigger * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions */ var Action = /** @class */ (function () { /** * Creates a new Action * @param triggerOptions the trigger, with or without parameters, for the action * @param condition an optional determinant of action */ function Action( /** the trigger, with or without parameters, for the action */ triggerOptions, condition) { this.triggerOptions = triggerOptions; /** * An event triggered prior to action being executed. */ this.onBeforeExecuteObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); if (triggerOptions.parameter) { this.trigger = triggerOptions.trigger; this._triggerParameter = triggerOptions.parameter; } else if (triggerOptions.trigger) { this.trigger = triggerOptions.trigger; } else { this.trigger = triggerOptions; } this._nextActiveAction = this; this._condition = condition; } /** * Internal only * @hidden */ Action.prototype._prepare = function () { }; /** * Gets the trigger parameters * @returns the trigger parameters */ Action.prototype.getTriggerParameter = function () { return this._triggerParameter; }; /** * Internal only - executes current action event * @hidden */ Action.prototype._executeCurrent = function (evt) { if (this._nextActiveAction._condition) { var condition = this._nextActiveAction._condition; var currentRenderId = this._actionManager.getScene().getRenderId(); // We cache the current evaluation for the current frame if (condition._evaluationId === currentRenderId) { if (!condition._currentResult) { return; } } else { condition._evaluationId = currentRenderId; if (!condition.isValid()) { condition._currentResult = false; return; } condition._currentResult = true; } } this.onBeforeExecuteObservable.notifyObservers(this); this._nextActiveAction.execute(evt); this.skipToNextActiveAction(); }; /** * Execute placeholder for child classes * @param evt optional action event */ Action.prototype.execute = function (evt) { }; /** * Skips to next active action */ Action.prototype.skipToNextActiveAction = function () { if (this._nextActiveAction._child) { if (!this._nextActiveAction._child._actionManager) { this._nextActiveAction._child._actionManager = this._actionManager; } this._nextActiveAction = this._nextActiveAction._child; } else { this._nextActiveAction = this; } }; /** * Adds action to chain of actions, may be a DoNothingAction * @param action defines the next action to execute * @returns The action passed in * @see https://www.babylonjs-playground.com/#1T30HR#0 */ Action.prototype.then = function (action) { this._child = action; action._actionManager = this._actionManager; action._prepare(); return action; }; /** * Internal only * @hidden */ Action.prototype._getProperty = function (propertyPath) { return this._actionManager._getProperty(propertyPath); }; /** * Internal only * @hidden */ Action.prototype._getEffectiveTarget = function (target, propertyPath) { return this._actionManager._getEffectiveTarget(target, propertyPath); }; /** * Serialize placeholder for child classes * @param parent of child * @returns the serialized object */ Action.prototype.serialize = function (parent) { }; /** * Internal only called by serialize * @hidden */ Action.prototype._serialize = function (serializedAction, parent) { var serializationObject = { type: 1, children: [], name: serializedAction.name, properties: serializedAction.properties || [] }; // Serialize child if (this._child) { this._child.serialize(serializationObject); } // Check if "this" has a condition if (this._condition) { var serializedCondition = this._condition.serialize(); serializedCondition.children.push(serializationObject); if (parent) { parent.children.push(serializedCondition); } return serializedCondition; } if (parent) { parent.children.push(serializationObject); } return serializationObject; }; /** * Internal only * @hidden */ Action._SerializeValueAsString = function (value) { if (typeof value === "number") { return value.toString(); } if (typeof value === "boolean") { return value ? "true" : "false"; } if (value instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector2"]) { return value.x + ", " + value.y; } if (value instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"]) { return value.x + ", " + value.y + ", " + value.z; } if (value instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color3"]) { return value.r + ", " + value.g + ", " + value.b; } if (value instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color4"]) { return value.r + ", " + value.g + ", " + value.b + ", " + value.a; } return value; // string }; /** * Internal only * @hidden */ Action._GetTargetProperty = function (target) { return { name: "target", targetType: target._isMesh ? "MeshProperties" : target._isLight ? "LightProperties" : target._isCamera ? "CameraProperties" : "SceneProperties", value: target._isScene ? "Scene" : target.name }; }; return Action; }()); _Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__["_TypeStore"].RegisteredTypes["BABYLON.Action"] = Action; /***/ }), /***/ "./Actions/actionEvent.ts": /*!********************************!*\ !*** ./Actions/actionEvent.ts ***! \********************************/ /*! exports provided: ActionEvent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActionEvent", function() { return ActionEvent; }); /** * ActionEvent is the event being sent when an action is triggered. */ var ActionEvent = /** @class */ (function () { /** * 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 */ function ActionEvent( /** The mesh or sprite that triggered the action */ source, /** The X mouse cursor position at the time of the event */ pointerX, /** The Y mouse cursor position at the time of the event */ pointerY, /** The mesh that is currently pointed at (can be null) */ meshUnderPointer, /** the original (browser) event that triggered the ActionEvent */ sourceEvent, /** additional data for the event */ additionalData) { this.source = source; this.pointerX = pointerX; this.pointerY = pointerY; this.meshUnderPointer = meshUnderPointer; this.sourceEvent = sourceEvent; this.additionalData = additionalData; } /** * Helper function to auto-create an ActionEvent from a source mesh. * @param source The source mesh that triggered the event * @param evt The original (browser) event * @param additionalData additional data for the event * @returns the new ActionEvent */ ActionEvent.CreateNew = function (source, evt, additionalData) { var 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 */ ActionEvent.CreateNewFromSprite = function (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 */ ActionEvent.CreateNewFromScene = function (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 */ ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) { return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData); }; return ActionEvent; }()); /***/ }), /***/ "./Actions/actionManager.ts": /*!**********************************!*\ !*** ./Actions/actionManager.ts ***! \**********************************/ /*! exports provided: ActionManager */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActionManager", function() { return ActionManager; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _condition__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./condition */ "./Actions/condition.ts"); /* harmony import */ var _action__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./action */ "./Actions/action.ts"); /* harmony import */ var _directActions__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./directActions */ "./Actions/directActions.ts"); /* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Misc_deepCopier__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Misc/deepCopier */ "./Misc/deepCopier.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); /* harmony import */ var _abstractActionManager__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./abstractActionManager */ "./Actions/abstractActionManager.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); /** * Action Manager manages all events to be triggered on a given mesh or the global scene. * A single scene can have many Action Managers to handle predefined actions on specific meshes. * @see http://doc.babylonjs.com/how_to/how_to_use_actions */ var ActionManager = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ActionManager, _super); /** * Creates a new action manager * @param scene defines the hosting scene */ function ActionManager(scene) { var _this = _super.call(this) || this; _this._scene = scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; scene.actionManagers.push(_this); return _this; } // Methods /** * Releases all associated resources */ ActionManager.prototype.dispose = function () { var index = this._scene.actionManagers.indexOf(this); for (var i = 0; i < this.actions.length; i++) { var action = this.actions[i]; ActionManager.Triggers[action.trigger]--; if (ActionManager.Triggers[action.trigger] === 0) { delete ActionManager.Triggers[action.trigger]; } } if (index > -1) { this._scene.actionManagers.splice(index, 1); } }; /** * Gets hosting scene * @returns the hosting scene */ ActionManager.prototype.getScene = function () { return this._scene; }; /** * Does this action manager handles actions of any of the given triggers * @param triggers defines the triggers to be tested * @return a boolean indicating whether one (or more) of the triggers is handled */ ActionManager.prototype.hasSpecificTriggers = function (triggers) { for (var index = 0; index < this.actions.length; index++) { var action = this.actions[index]; if (triggers.indexOf(action.trigger) > -1) { return true; } } return false; }; /** * Does this action manager handles actions of any of the given triggers. This function takes two arguments for * speed. * @param triggerA defines the trigger to be tested * @param triggerB defines the trigger to be tested * @return a boolean indicating whether one (or more) of the triggers is handled */ ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) { for (var index = 0; index < this.actions.length; index++) { var action = this.actions[index]; if (triggerA == action.trigger || triggerB == action.trigger) { return true; } } return false; }; /** * Does this action manager handles actions of a given trigger * @param trigger defines the trigger to be tested * @param parameterPredicate defines an optional predicate to filter triggers by parameter * @return whether the trigger is handled */ ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) { for (var index = 0; index < this.actions.length; index++) { var action = this.actions[index]; if (action.trigger === trigger) { if (parameterPredicate) { if (parameterPredicate(action.getTriggerParameter())) { return true; } } else { return true; } } } return false; }; Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", { /** * Does this action manager has pointer triggers */ get: function () { for (var index = 0; index < this.actions.length; index++) { var action = this.actions[index]; if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) { return true; } } return false; }, enumerable: true, configurable: true }); Object.defineProperty(ActionManager.prototype, "hasPickTriggers", { /** * Does this action manager has pick triggers */ get: function () { for (var index = 0; index < this.actions.length; index++) { var action = this.actions[index]; if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) { return true; } } return false; }, enumerable: true, configurable: true }); /** * Registers an action to this action manager * @param action defines the action to be registered * @return the action amended (prepared) after registration */ ActionManager.prototype.registerAction = function (action) { if (action.trigger === ActionManager.OnEveryFrameTrigger) { if (this.getScene().actionManager !== this) { _Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Warn("OnEveryFrameTrigger can only be used with scene.actionManager"); return null; } } this.actions.push(action); if (ActionManager.Triggers[action.trigger]) { ActionManager.Triggers[action.trigger]++; } else { ActionManager.Triggers[action.trigger] = 1; } action._actionManager = this; action._prepare(); return action; }; /** * Unregisters an action to this action manager * @param action defines the action to be unregistered * @return a boolean indicating whether the action has been unregistered */ ActionManager.prototype.unregisterAction = function (action) { var index = this.actions.indexOf(action); if (index !== -1) { this.actions.splice(index, 1); ActionManager.Triggers[action.trigger] -= 1; if (ActionManager.Triggers[action.trigger] === 0) { delete ActionManager.Triggers[action.trigger]; } delete action._actionManager; return true; } return false; }; /** * Process a specific trigger * @param trigger defines the trigger to process * @param evt defines the event details to be processed */ ActionManager.prototype.processTrigger = function (trigger, evt) { for (var index = 0; index < this.actions.length; index++) { var action = this.actions[index]; if (action.trigger === trigger) { if (evt) { if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) { var parameter = action.getTriggerParameter(); if (parameter && parameter !== evt.sourceEvent.keyCode) { if (!parameter.toLowerCase) { continue; } var lowerCase = parameter.toLowerCase(); if (lowerCase !== evt.sourceEvent.key) { var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode; var actualkey = String.fromCharCode(unicode).toLowerCase(); if (actualkey !== lowerCase) { continue; } } } } } action._executeCurrent(evt); } } }; /** @hidden */ ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) { var properties = propertyPath.split("."); for (var index = 0; index < properties.length - 1; index++) { target = target[properties[index]]; } return target; }; /** @hidden */ ActionManager.prototype._getProperty = function (propertyPath) { var properties = propertyPath.split("."); return properties[properties.length - 1]; }; /** * Serialize this manager to a JSON object * @param name defines the property name to store this manager * @returns a JSON representation of this manager */ ActionManager.prototype.serialize = function (name) { var root = { children: new Array(), name: name, type: 3, properties: new Array() // Empty for root but required }; for (var i = 0; i < this.actions.length; i++) { var triggerObject = { type: 0, children: new Array(), name: ActionManager.GetTriggerName(this.actions[i].trigger), properties: new Array() }; var triggerOptions = this.actions[i].triggerOptions; if (triggerOptions && typeof triggerOptions !== "number") { if (triggerOptions.parameter instanceof Node) { triggerObject.properties.push(_action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(triggerOptions.parameter)); } else { var parameter = {}; _Misc_deepCopier__WEBPACK_IMPORTED_MODULE_7__["DeepCopier"].DeepCopy(triggerOptions.parameter, parameter, ["mesh"]); if (triggerOptions.parameter && triggerOptions.parameter.mesh) { parameter._meshId = triggerOptions.parameter.mesh.id; } triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter }); } } // Serialize child action, recursively this.actions[i].serialize(triggerObject); // Add serialized trigger root.children.push(triggerObject); } return root; }; /** * Creates a new ActionManager from a JSON data * @param parsedActions defines the JSON data to read from * @param object defines the hosting mesh * @param scene defines the hosting scene */ ActionManager.Parse = function (parsedActions, object, scene) { var actionManager = new ActionManager(scene); if (object === null) { scene.actionManager = actionManager; } else { object.actionManager = actionManager; } // instanciate a new object var instanciate = function (name, params) { var internalClassType = _Misc_typeStore__WEBPACK_IMPORTED_MODULE_8__["_TypeStore"].GetClass("BABYLON." + name); if (internalClassType) { var newInstance = Object.create(internalClassType.prototype); newInstance.constructor.apply(newInstance, params); return newInstance; } }; var parseParameter = function (name, value, target, propertyPath) { if (propertyPath === null) { // String, boolean or float var floatValue = parseFloat(value); if (value === "true" || value === "false") { return value === "true"; } else { return isNaN(floatValue) ? value : floatValue; } } var effectiveTarget = propertyPath.split("."); var values = value.split(","); // Get effective Target for (var i = 0; i < effectiveTarget.length; i++) { target = target[effectiveTarget[i]]; } // Return appropriate value with its type if (typeof (target) === "boolean") { return values[0] === "true"; } if (typeof (target) === "string") { return values[0]; } // Parameters with multiple values such as Vector3 etc. var split = new Array(); for (var i = 0; i < values.length; i++) { split.push(parseFloat(values[i])); } if (target instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"]) { return _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].FromArray(split); } if (target instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector4"]) { return _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector4"].FromArray(split); } if (target instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color3"]) { return _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color3"].FromArray(split); } if (target instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color4"]) { return _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color4"].FromArray(split); } return parseFloat(values[0]); }; // traverse graph per trigger var traverse = function (parsedAction, trigger, condition, action, combineArray) { if (combineArray === void 0) { combineArray = null; } if (parsedAction.detached) { return; } var parameters = new Array(); var target = null; var propertyPath = null; var combine = parsedAction.combine && parsedAction.combine.length > 0; // Parameters if (parsedAction.type === 2) { parameters.push(actionManager); } else { parameters.push(trigger); } if (combine) { var actions = new Array(); for (var j = 0; j < parsedAction.combine.length; j++) { traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions); } parameters.push(actions); } else { for (var i = 0; i < parsedAction.properties.length; i++) { var value = parsedAction.properties[i].value; var name = parsedAction.properties[i].name; var targetType = parsedAction.properties[i].targetType; if (name === "target") { if (targetType !== null && targetType === "SceneProperties") { value = target = scene; } else { value = target = scene.getNodeByName(value); } } else if (name === "parent") { value = scene.getNodeByName(value); } else if (name === "sound") { // Can not externalize to component, so only checks for the presence off the API. if (scene.getSoundByName) { value = scene.getSoundByName(value); } } else if (name !== "propertyPath") { if (parsedAction.type === 2 && name === "operator") { value = _condition__WEBPACK_IMPORTED_MODULE_2__["ValueCondition"][value]; } else { value = parseParameter(name, value, target, name === "value" ? propertyPath : null); } } else { propertyPath = value; } parameters.push(value); } } if (combineArray === null) { parameters.push(condition); } else { parameters.push(null); } // If interpolate value action if (parsedAction.name === "InterpolateValueAction") { var param = parameters[parameters.length - 2]; parameters[parameters.length - 1] = param; parameters[parameters.length - 2] = condition; } // Action or condition(s) and not CombineAction var newAction = instanciate(parsedAction.name, parameters); if (newAction instanceof _condition__WEBPACK_IMPORTED_MODULE_2__["Condition"] && condition !== null) { var nothing = new _directActions__WEBPACK_IMPORTED_MODULE_4__["DoNothingAction"](trigger, condition); if (action) { action.then(nothing); } else { actionManager.registerAction(nothing); } action = nothing; } if (combineArray === null) { if (newAction instanceof _condition__WEBPACK_IMPORTED_MODULE_2__["Condition"]) { condition = newAction; newAction = action; } else { condition = null; if (action) { action.then(newAction); } else { actionManager.registerAction(newAction); } } } else { combineArray.push(newAction); } for (var i = 0; i < parsedAction.children.length; i++) { traverse(parsedAction.children[i], trigger, condition, newAction, null); } }; // triggers for (var i = 0; i < parsedActions.children.length; i++) { var triggerParams; var trigger = parsedActions.children[i]; if (trigger.properties.length > 0) { var param = trigger.properties[0].value; var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param); if (value._meshId) { value.mesh = scene.getMeshByID(value._meshId); } triggerParams = { trigger: ActionManager[trigger.name], parameter: value }; } else { triggerParams = ActionManager[trigger.name]; } for (var j = 0; j < trigger.children.length; j++) { if (!trigger.detached) { traverse(trigger.children[j], triggerParams, null, null); } } } }; /** * Get a trigger name by index * @param trigger defines the trigger index * @returns a trigger name */ ActionManager.GetTriggerName = function (trigger) { switch (trigger) { case 0: return "NothingTrigger"; case 1: return "OnPickTrigger"; case 2: return "OnLeftPickTrigger"; case 3: return "OnRightPickTrigger"; case 4: return "OnCenterPickTrigger"; case 5: return "OnPickDownTrigger"; case 6: return "OnPickUpTrigger"; case 7: return "OnLongPressTrigger"; case 8: return "OnPointerOverTrigger"; case 9: return "OnPointerOutTrigger"; case 10: return "OnEveryFrameTrigger"; case 11: return "OnIntersectionEnterTrigger"; case 12: return "OnIntersectionExitTrigger"; case 13: return "OnKeyDownTrigger"; case 14: return "OnKeyUpTrigger"; case 15: return "OnPickOutTrigger"; default: return ""; } }; /** * Nothing * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.NothingTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_NothingTrigger; /** * On pick * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnPickTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnPickTrigger; /** * On left pick * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnLeftPickTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnLeftPickTrigger; /** * On right pick * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnRightPickTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnRightPickTrigger; /** * On center pick * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnCenterPickTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnCenterPickTrigger; /** * On pick down * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnPickDownTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnPickDownTrigger; /** * On double pick * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnDoublePickTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnDoublePickTrigger; /** * On pick up * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnPickUpTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnPickUpTrigger; /** * On pick out. * This trigger will only be raised if you also declared a OnPickDown * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnPickOutTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnPickOutTrigger; /** * On long press * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnLongPressTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnLongPressTrigger; /** * On pointer over * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnPointerOverTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnPointerOverTrigger; /** * On pointer out * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnPointerOutTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnPointerOutTrigger; /** * On every frame * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnEveryFrameTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnEveryFrameTrigger; /** * On intersection enter * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnIntersectionEnterTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnIntersectionEnterTrigger; /** * On intersection exit * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnIntersectionExitTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnIntersectionExitTrigger; /** * On key down * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnKeyDownTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ACTION_OnKeyDownTrigger; /** * On key up * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnKeyUpTrigger = 15; return ActionManager; }(_abstractActionManager__WEBPACK_IMPORTED_MODULE_9__["AbstractActionManager"])); /***/ }), /***/ "./Actions/condition.ts": /*!******************************!*\ !*** ./Actions/condition.ts ***! \******************************/ /*! exports provided: Condition, ValueCondition, PredicateCondition, StateCondition */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Condition", function() { return Condition; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ValueCondition", function() { return ValueCondition; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PredicateCondition", function() { return PredicateCondition; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StateCondition", function() { return StateCondition; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _action__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./action */ "./Actions/action.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); /** * A Condition applied to an Action */ var Condition = /** @class */ (function () { /** * Creates a new Condition * @param actionManager the manager of the action the condition is applied to */ function Condition(actionManager) { this._actionManager = actionManager; } /** * Check if the current condition is valid * @returns a boolean */ Condition.prototype.isValid = function () { return true; }; /** * Internal only * @hidden */ Condition.prototype._getProperty = function (propertyPath) { return this._actionManager._getProperty(propertyPath); }; /** * Internal only * @hidden */ Condition.prototype._getEffectiveTarget = function (target, propertyPath) { return this._actionManager._getEffectiveTarget(target, propertyPath); }; /** * Serialize placeholder for child classes * @returns the serialized object */ Condition.prototype.serialize = function () { }; /** * Internal only * @hidden */ Condition.prototype._serialize = function (serializedCondition) { return { type: 2, children: [], name: serializedCondition.name, properties: serializedCondition.properties }; }; return Condition; }()); /** * Defines specific conditional operators as extensions of Condition */ var ValueCondition = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ValueCondition, _super); /** * Creates a new ValueCondition * @param actionManager manager for the action the condition applies to * @param target for the action * @param propertyPath path to specify the property of the target the conditional operator uses * @param value the value compared by the conditional operator against the current value of the property * @param operator the conditional operator, default ValueCondition.IsEqual */ function ValueCondition(actionManager, target, /** path to specify the property of the target the conditional operator uses */ propertyPath, /** the value compared by the conditional operator against the current value of the property */ value, /** the conditional operator, default ValueCondition.IsEqual */ operator) { if (operator === void 0) { operator = ValueCondition.IsEqual; } var _this = _super.call(this, actionManager) || this; _this.propertyPath = propertyPath; _this.value = value; _this.operator = operator; _this._target = target; _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath); _this._property = _this._getProperty(_this.propertyPath); return _this; } Object.defineProperty(ValueCondition, "IsEqual", { /** * returns the number for IsEqual */ get: function () { return ValueCondition._IsEqual; }, enumerable: true, configurable: true }); Object.defineProperty(ValueCondition, "IsDifferent", { /** * Returns the number for IsDifferent */ get: function () { return ValueCondition._IsDifferent; }, enumerable: true, configurable: true }); Object.defineProperty(ValueCondition, "IsGreater", { /** * Returns the number for IsGreater */ get: function () { return ValueCondition._IsGreater; }, enumerable: true, configurable: true }); Object.defineProperty(ValueCondition, "IsLesser", { /** * Returns the number for IsLesser */ get: function () { return ValueCondition._IsLesser; }, enumerable: true, configurable: true }); /** * Compares the given value with the property value for the specified conditional operator * @returns the result of the comparison */ ValueCondition.prototype.isValid = function () { switch (this.operator) { case ValueCondition.IsGreater: return this._effectiveTarget[this._property] > this.value; case ValueCondition.IsLesser: return this._effectiveTarget[this._property] < this.value; case ValueCondition.IsEqual: case ValueCondition.IsDifferent: var check; if (this.value.equals) { check = this.value.equals(this._effectiveTarget[this._property]); } else { check = this.value === this._effectiveTarget[this._property]; } return this.operator === ValueCondition.IsEqual ? check : !check; } return false; }; /** * Serialize the ValueCondition into a JSON compatible object * @returns serialization object */ ValueCondition.prototype.serialize = function () { return this._serialize({ name: "ValueCondition", properties: [ _action__WEBPACK_IMPORTED_MODULE_1__["Action"]._GetTargetProperty(this._target), { name: "propertyPath", value: this.propertyPath }, { name: "value", value: _action__WEBPACK_IMPORTED_MODULE_1__["Action"]._SerializeValueAsString(this.value) }, { name: "operator", value: ValueCondition.GetOperatorName(this.operator) } ] }); }; /** * Gets the name of the conditional operator for the ValueCondition * @param operator the conditional operator * @returns the name */ ValueCondition.GetOperatorName = function (operator) { switch (operator) { case ValueCondition._IsEqual: return "IsEqual"; case ValueCondition._IsDifferent: return "IsDifferent"; case ValueCondition._IsGreater: return "IsGreater"; case ValueCondition._IsLesser: return "IsLesser"; default: return ""; } }; /** * Internal only * @hidden */ ValueCondition._IsEqual = 0; /** * Internal only * @hidden */ ValueCondition._IsDifferent = 1; /** * Internal only * @hidden */ ValueCondition._IsGreater = 2; /** * Internal only * @hidden */ ValueCondition._IsLesser = 3; return ValueCondition; }(Condition)); /** * Defines a predicate condition as an extension of Condition */ var PredicateCondition = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PredicateCondition, _super); /** * Creates a new PredicateCondition * @param actionManager manager for the action the condition applies to * @param predicate defines the predicate function used to validate the condition */ function PredicateCondition(actionManager, /** defines the predicate function used to validate the condition */ predicate) { var _this = _super.call(this, actionManager) || this; _this.predicate = predicate; return _this; } /** * @returns the validity of the predicate condition */ PredicateCondition.prototype.isValid = function () { return this.predicate(); }; return PredicateCondition; }(Condition)); /** * Defines a state condition as an extension of Condition */ var StateCondition = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](StateCondition, _super); /** * Creates a new StateCondition * @param actionManager manager for the action the condition applies to * @param target of the condition * @param value to compare with target state */ function StateCondition(actionManager, target, /** Value to compare with target state */ value) { var _this = _super.call(this, actionManager) || this; _this.value = value; _this._target = target; return _this; } /** * Gets a boolean indicating if the current condition is met * @returns the validity of the state */ StateCondition.prototype.isValid = function () { return this._target.state === this.value; }; /** * Serialize the StateCondition into a JSON compatible object * @returns serialization object */ StateCondition.prototype.serialize = function () { return this._serialize({ name: "StateCondition", properties: [ _action__WEBPACK_IMPORTED_MODULE_1__["Action"]._GetTargetProperty(this._target), { name: "value", value: this.value } ] }); }; return StateCondition; }(Condition)); _Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__["_TypeStore"].RegisteredTypes["BABYLON.ValueCondition"] = ValueCondition; _Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__["_TypeStore"].RegisteredTypes["BABYLON.PredicateCondition"] = PredicateCondition; _Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__["_TypeStore"].RegisteredTypes["BABYLON.StateCondition"] = StateCondition; /***/ }), /***/ "./Actions/directActions.ts": /*!**********************************!*\ !*** ./Actions/directActions.ts ***! \**********************************/ /*! exports provided: SwitchBooleanAction, SetStateAction, SetValueAction, IncrementValueAction, PlayAnimationAction, StopAnimationAction, DoNothingAction, CombineAction, ExecuteCodeAction, SetParentAction */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SwitchBooleanAction", function() { return SwitchBooleanAction; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SetStateAction", function() { return SetStateAction; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SetValueAction", function() { return SetValueAction; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IncrementValueAction", function() { return IncrementValueAction; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlayAnimationAction", function() { return PlayAnimationAction; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StopAnimationAction", function() { return StopAnimationAction; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DoNothingAction", function() { return DoNothingAction; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CombineAction", function() { return CombineAction; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ExecuteCodeAction", function() { return ExecuteCodeAction; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SetParentAction", function() { return SetParentAction; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _action__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./action */ "./Actions/action.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); /** * This defines an action responsible to toggle a boolean once triggered. * @see http://doc.babylonjs.com/how_to/how_to_use_actions */ var SwitchBooleanAction = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SwitchBooleanAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param target defines the object containing the boolean * @param propertyPath defines the path to the boolean property in the target object * @param condition defines the trigger related conditions */ function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this.propertyPath = propertyPath; _this._target = _this._effectiveTarget = target; return _this; } /** @hidden */ SwitchBooleanAction.prototype._prepare = function () { this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath); this._property = this._getProperty(this.propertyPath); }; /** * Execute the action toggle the boolean value. */ SwitchBooleanAction.prototype.execute = function () { this._effectiveTarget[this._property] = !this._effectiveTarget[this._property]; }; /** * Serializes the actions and its related information. * @param parent defines the object to serialize in * @returns the serialized object */ SwitchBooleanAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "SwitchBooleanAction", properties: [ _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(this._target), { name: "propertyPath", value: this.propertyPath } ] }, parent); }; return SwitchBooleanAction; }(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); /** * This defines an action responsible to set a the state field of the target * to a desired value once triggered. * @see http://doc.babylonjs.com/how_to/how_to_use_actions */ var SetStateAction = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SetStateAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param target defines the object containing the state property * @param value defines the value to store in the state field * @param condition defines the trigger related conditions */ function SetStateAction(triggerOptions, target, value, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this.value = value; _this._target = target; return _this; } /** * Execute the action and store the value on the target state property. */ SetStateAction.prototype.execute = function () { this._target.state = this.value; }; /** * Serializes the actions and its related information. * @param parent defines the object to serialize in * @returns the serialized object */ SetStateAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "SetStateAction", properties: [ _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(this._target), { name: "value", value: this.value } ] }, parent); }; return SetStateAction; }(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); /** * This defines an action responsible to set a property of the target * to a desired value once triggered. * @see http://doc.babylonjs.com/how_to/how_to_use_actions */ var SetValueAction = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SetValueAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param target defines the object containing the property * @param propertyPath defines the path of the property to set in the target * @param value defines the value to set in the property * @param condition defines the trigger related conditions */ function SetValueAction(triggerOptions, target, propertyPath, value, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this.propertyPath = propertyPath; _this.value = value; _this._target = _this._effectiveTarget = target; return _this; } /** @hidden */ SetValueAction.prototype._prepare = function () { this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath); this._property = this._getProperty(this.propertyPath); }; /** * Execute the action and set the targetted property to the desired value. */ SetValueAction.prototype.execute = function () { this._effectiveTarget[this._property] = this.value; if (this._target.markAsDirty) { this._target.markAsDirty(this._property); } }; /** * Serializes the actions and its related information. * @param parent defines the object to serialize in * @returns the serialized object */ SetValueAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "SetValueAction", properties: [ _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(this._target), { name: "propertyPath", value: this.propertyPath }, { name: "value", value: _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._SerializeValueAsString(this.value) } ] }, parent); }; return SetValueAction; }(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); /** * This defines an action responsible to increment the target value * to a desired value once triggered. * @see http://doc.babylonjs.com/how_to/how_to_use_actions */ var IncrementValueAction = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](IncrementValueAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param target defines the object containing the property * @param propertyPath defines the path of the property to increment in the target * @param value defines the value value we should increment the property by * @param condition defines the trigger related conditions */ function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this.propertyPath = propertyPath; _this.value = value; _this._target = _this._effectiveTarget = target; return _this; } /** @hidden */ IncrementValueAction.prototype._prepare = function () { this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath); this._property = this._getProperty(this.propertyPath); if (typeof this._effectiveTarget[this._property] !== "number") { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Warning: IncrementValueAction can only be used with number values"); } }; /** * Execute the action and increment the target of the value amount. */ IncrementValueAction.prototype.execute = function () { this._effectiveTarget[this._property] += this.value; if (this._target.markAsDirty) { this._target.markAsDirty(this._property); } }; /** * Serializes the actions and its related information. * @param parent defines the object to serialize in * @returns the serialized object */ IncrementValueAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "IncrementValueAction", properties: [ _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(this._target), { name: "propertyPath", value: this.propertyPath }, { name: "value", value: _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._SerializeValueAsString(this.value) } ] }, parent); }; return IncrementValueAction; }(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); /** * This defines an action responsible to start an animation once triggered. * @see http://doc.babylonjs.com/how_to/how_to_use_actions */ var PlayAnimationAction = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PlayAnimationAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param target defines the target animation or animation name * @param from defines from where the animation should start (animation frame) * @param end defines where the animation should stop (animation frame) * @param loop defines if the animation should loop or stop after the first play * @param condition defines the trigger related conditions */ function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this.from = from; _this.to = to; _this.loop = loop; _this._target = target; return _this; } /** @hidden */ PlayAnimationAction.prototype._prepare = function () { }; /** * Execute the action and play the animation. */ PlayAnimationAction.prototype.execute = function () { var scene = this._actionManager.getScene(); scene.beginAnimation(this._target, this.from, this.to, this.loop); }; /** * Serializes the actions and its related information. * @param parent defines the object to serialize in * @returns the serialized object */ PlayAnimationAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "PlayAnimationAction", properties: [ _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(this._target), { name: "from", value: String(this.from) }, { name: "to", value: String(this.to) }, { name: "loop", value: _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._SerializeValueAsString(this.loop) || false } ] }, parent); }; return PlayAnimationAction; }(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); /** * This defines an action responsible to stop an animation once triggered. * @see http://doc.babylonjs.com/how_to/how_to_use_actions */ var StopAnimationAction = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](StopAnimationAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param target defines the target animation or animation name * @param condition defines the trigger related conditions */ function StopAnimationAction(triggerOptions, target, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this._target = target; return _this; } /** @hidden */ StopAnimationAction.prototype._prepare = function () { }; /** * Execute the action and stop the animation. */ StopAnimationAction.prototype.execute = function () { var scene = this._actionManager.getScene(); scene.stopAnimation(this._target); }; /** * Serializes the actions and its related information. * @param parent defines the object to serialize in * @returns the serialized object */ StopAnimationAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "StopAnimationAction", properties: [_action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(this._target)] }, parent); }; return StopAnimationAction; }(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); /** * This defines an action responsible that does nothing once triggered. * @see http://doc.babylonjs.com/how_to/how_to_use_actions */ var DoNothingAction = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DoNothingAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param condition defines the trigger related conditions */ function DoNothingAction(triggerOptions, condition) { if (triggerOptions === void 0) { triggerOptions = _Engines_constants__WEBPACK_IMPORTED_MODULE_4__["Constants"].ACTION_NothingTrigger; } return _super.call(this, triggerOptions, condition) || this; } /** * Execute the action and do nothing. */ DoNothingAction.prototype.execute = function () { }; /** * Serializes the actions and its related information. * @param parent defines the object to serialize in * @returns the serialized object */ DoNothingAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "DoNothingAction", properties: [] }, parent); }; return DoNothingAction; }(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); /** * This defines an action responsible to trigger several actions once triggered. * @see http://doc.babylonjs.com/how_to/how_to_use_actions */ var CombineAction = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](CombineAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param children defines the list of aggregated animations to run * @param condition defines the trigger related conditions */ function CombineAction(triggerOptions, children, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this.children = children; return _this; } /** @hidden */ CombineAction.prototype._prepare = function () { for (var index = 0; index < this.children.length; index++) { this.children[index]._actionManager = this._actionManager; this.children[index]._prepare(); } }; /** * Execute the action and executes all the aggregated actions. */ CombineAction.prototype.execute = function (evt) { for (var index = 0; index < this.children.length; index++) { this.children[index].execute(evt); } }; /** * Serializes the actions and its related information. * @param parent defines the object to serialize in * @returns the serialized object */ CombineAction.prototype.serialize = function (parent) { var serializationObject = _super.prototype._serialize.call(this, { name: "CombineAction", properties: [], combine: [] }, parent); for (var i = 0; i < this.children.length; i++) { serializationObject.combine.push(this.children[i].serialize(null)); } return serializationObject; }; return CombineAction; }(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); /** * This defines an action responsible to run code (external event) once triggered. * @see http://doc.babylonjs.com/how_to/how_to_use_actions */ var ExecuteCodeAction = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ExecuteCodeAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param func defines the callback function to run * @param condition defines the trigger related conditions */ function ExecuteCodeAction(triggerOptions, func, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this.func = func; return _this; } /** * Execute the action and run the attached code. */ ExecuteCodeAction.prototype.execute = function (evt) { this.func(evt); }; return ExecuteCodeAction; }(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); /** * This defines an action responsible to set the parent property of the target once triggered. * @see http://doc.babylonjs.com/how_to/how_to_use_actions */ var SetParentAction = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SetParentAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param target defines the target containing the parent property * @param parent defines from where the animation should start (animation frame) * @param condition defines the trigger related conditions */ function SetParentAction(triggerOptions, target, parent, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this._target = target; _this._parent = parent; return _this; } /** @hidden */ SetParentAction.prototype._prepare = function () { }; /** * Execute the action and set the parent property. */ SetParentAction.prototype.execute = function () { if (this._target.parent === this._parent) { return; } var invertParentWorldMatrix = this._parent.getWorldMatrix().clone(); invertParentWorldMatrix.invert(); this._target.position = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinates(this._target.position, invertParentWorldMatrix); this._target.parent = this._parent; }; /** * Serializes the actions and its related information. * @param parent defines the object to serialize in * @returns the serialized object */ SetParentAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "SetParentAction", properties: [ _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(this._target), _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(this._parent), ] }, parent); }; return SetParentAction; }(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.SetParentAction"] = SetParentAction; _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.ExecuteCodeAction"] = ExecuteCodeAction; _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.DoNothingAction"] = DoNothingAction; _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.StopAnimationAction"] = StopAnimationAction; _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.PlayAnimationAction"] = PlayAnimationAction; _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.IncrementValueAction"] = IncrementValueAction; _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.SetValueAction"] = SetValueAction; _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.SetStateAction"] = SetStateAction; _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.SetParentAction"] = SetParentAction; /***/ }), /***/ "./Actions/directAudioActions.ts": /*!***************************************!*\ !*** ./Actions/directAudioActions.ts ***! \***************************************/ /*! exports provided: PlaySoundAction, StopSoundAction */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaySoundAction", function() { return PlaySoundAction; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StopSoundAction", function() { return StopSoundAction; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _action__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./action */ "./Actions/action.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); /** * This defines an action helpful to play a defined sound on a triggered action. */ var PlaySoundAction = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PlaySoundAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param sound defines the sound to play * @param condition defines the trigger related conditions */ function PlaySoundAction(triggerOptions, sound, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this._sound = sound; return _this; } /** @hidden */ PlaySoundAction.prototype._prepare = function () { }; /** * Execute the action and play the sound. */ PlaySoundAction.prototype.execute = function () { if (this._sound !== undefined) { this._sound.play(); } }; /** * Serializes the actions and its related information. * @param parent defines the object to serialize in * @returns the serialized object */ PlaySoundAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "PlaySoundAction", properties: [{ name: "sound", value: this._sound.name }] }, parent); }; return PlaySoundAction; }(_action__WEBPACK_IMPORTED_MODULE_1__["Action"])); /** * This defines an action helpful to stop a defined sound on a triggered action. */ var StopSoundAction = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](StopSoundAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param sound defines the sound to stop * @param condition defines the trigger related conditions */ function StopSoundAction(triggerOptions, sound, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this._sound = sound; return _this; } /** @hidden */ StopSoundAction.prototype._prepare = function () { }; /** * Execute the action and stop the sound. */ StopSoundAction.prototype.execute = function () { if (this._sound !== undefined) { this._sound.stop(); } }; /** * Serializes the actions and its related information. * @param parent defines the object to serialize in * @returns the serialized object */ StopSoundAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "StopSoundAction", properties: [{ name: "sound", value: this._sound.name }] }, parent); }; return StopSoundAction; }(_action__WEBPACK_IMPORTED_MODULE_1__["Action"])); _Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__["_TypeStore"].RegisteredTypes["BABYLON.PlaySoundAction"] = StopSoundAction; _Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__["_TypeStore"].RegisteredTypes["BABYLON.StopSoundAction"] = StopSoundAction; /***/ }), /***/ "./Actions/index.ts": /*!**************************!*\ !*** ./Actions/index.ts ***! \**************************/ /*! exports provided: Action, ActionEvent, ActionManager, Condition, ValueCondition, PredicateCondition, StateCondition, SwitchBooleanAction, SetStateAction, SetValueAction, IncrementValueAction, PlayAnimationAction, StopAnimationAction, DoNothingAction, CombineAction, ExecuteCodeAction, SetParentAction, PlaySoundAction, StopSoundAction, InterpolateValueAction */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _action__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./action */ "./Actions/action.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Action", function() { return _action__WEBPACK_IMPORTED_MODULE_0__["Action"]; }); /* harmony import */ var _actionEvent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./actionEvent */ "./Actions/actionEvent.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ActionEvent", function() { return _actionEvent__WEBPACK_IMPORTED_MODULE_1__["ActionEvent"]; }); /* harmony import */ var _actionManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./actionManager */ "./Actions/actionManager.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ActionManager", function() { return _actionManager__WEBPACK_IMPORTED_MODULE_2__["ActionManager"]; }); /* harmony import */ var _condition__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./condition */ "./Actions/condition.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Condition", function() { return _condition__WEBPACK_IMPORTED_MODULE_3__["Condition"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ValueCondition", function() { return _condition__WEBPACK_IMPORTED_MODULE_3__["ValueCondition"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PredicateCondition", function() { return _condition__WEBPACK_IMPORTED_MODULE_3__["PredicateCondition"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StateCondition", function() { return _condition__WEBPACK_IMPORTED_MODULE_3__["StateCondition"]; }); /* harmony import */ var _directActions__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./directActions */ "./Actions/directActions.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SwitchBooleanAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_4__["SwitchBooleanAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SetStateAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_4__["SetStateAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SetValueAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_4__["SetValueAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IncrementValueAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_4__["IncrementValueAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlayAnimationAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_4__["PlayAnimationAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StopAnimationAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_4__["StopAnimationAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DoNothingAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_4__["DoNothingAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CombineAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_4__["CombineAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ExecuteCodeAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_4__["ExecuteCodeAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SetParentAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_4__["SetParentAction"]; }); /* harmony import */ var _directAudioActions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./directAudioActions */ "./Actions/directAudioActions.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlaySoundAction", function() { return _directAudioActions__WEBPACK_IMPORTED_MODULE_5__["PlaySoundAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StopSoundAction", function() { return _directAudioActions__WEBPACK_IMPORTED_MODULE_5__["StopSoundAction"]; }); /* harmony import */ var _interpolateValueAction__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./interpolateValueAction */ "./Actions/interpolateValueAction.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InterpolateValueAction", function() { return _interpolateValueAction__WEBPACK_IMPORTED_MODULE_6__["InterpolateValueAction"]; }); /***/ }), /***/ "./Actions/interpolateValueAction.ts": /*!*******************************************!*\ !*** ./Actions/interpolateValueAction.ts ***! \*******************************************/ /*! exports provided: InterpolateValueAction */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InterpolateValueAction", function() { return InterpolateValueAction; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _action__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./action */ "./Actions/action.ts"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Animations_animation__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Animations/animation */ "./Animations/animation.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); /** * This defines an action responsible to change the value of a property * by interpolating between its current value and the newly set one once triggered. * @see http://doc.babylonjs.com/how_to/how_to_use_actions */ var InterpolateValueAction = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](InterpolateValueAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param target defines the object containing the value to interpolate * @param propertyPath defines the path to the property in the target object * @param value defines the target value at the end of the interpolation * @param duration deines the time it will take for the property to interpolate to the value. * @param condition defines the trigger related conditions * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered * @param onInterpolationDone defines a callback raised once the interpolation animation has been done */ function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) { if (duration === void 0) { duration = 1000; } var _this = _super.call(this, triggerOptions, condition) || this; /** * Defines the time it will take for the property to interpolate to the value. */ _this.duration = 1000; /** * Observable triggered once the interpolation animation has been done. */ _this.onInterpolationDoneObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](); _this.propertyPath = propertyPath; _this.value = value; _this.duration = duration; _this.stopOtherAnimations = stopOtherAnimations; _this.onInterpolationDone = onInterpolationDone; _this._target = _this._effectiveTarget = target; return _this; } /** @hidden */ InterpolateValueAction.prototype._prepare = function () { this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath); this._property = this._getProperty(this.propertyPath); }; /** * Execute the action starts the value interpolation. */ InterpolateValueAction.prototype.execute = function () { var _this = this; var scene = this._actionManager.getScene(); var keys = [ { frame: 0, value: this._effectiveTarget[this._property] }, { frame: 100, value: this.value } ]; var dataType; if (typeof this.value === "number") { dataType = _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].ANIMATIONTYPE_FLOAT; } else if (this.value instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Color3"]) { dataType = _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].ANIMATIONTYPE_COLOR3; } else if (this.value instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"]) { dataType = _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].ANIMATIONTYPE_VECTOR3; } else if (this.value instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"]) { dataType = _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].ANIMATIONTYPE_MATRIX; } else if (this.value instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"]) { dataType = _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].ANIMATIONTYPE_QUATERNION; } else { _Misc_logger__WEBPACK_IMPORTED_MODULE_2__["Logger"].Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")"); return; } var animation = new _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"]("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].ANIMATIONLOOPMODE_CONSTANT); animation.setKeys(keys); if (this.stopOtherAnimations) { scene.stopAnimation(this._effectiveTarget); } var wrapper = function () { _this.onInterpolationDoneObservable.notifyObservers(_this); if (_this.onInterpolationDone) { _this.onInterpolationDone(); } }; scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper); }; /** * Serializes the actions and its related information. * @param parent defines the object to serialize in * @returns the serialized object */ InterpolateValueAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "InterpolateValueAction", properties: [ _action__WEBPACK_IMPORTED_MODULE_1__["Action"]._GetTargetProperty(this._target), { name: "propertyPath", value: this.propertyPath }, { name: "value", value: _action__WEBPACK_IMPORTED_MODULE_1__["Action"]._SerializeValueAsString(this.value) }, { name: "duration", value: _action__WEBPACK_IMPORTED_MODULE_1__["Action"]._SerializeValueAsString(this.duration) }, { name: "stopOtherAnimations", value: _action__WEBPACK_IMPORTED_MODULE_1__["Action"]._SerializeValueAsString(this.stopOtherAnimations) || false } ] }, parent); }; return InterpolateValueAction; }(_action__WEBPACK_IMPORTED_MODULE_1__["Action"])); _Misc_typeStore__WEBPACK_IMPORTED_MODULE_6__["_TypeStore"].RegisteredTypes["BABYLON.InterpolateValueAction"] = InterpolateValueAction; /***/ }), /***/ "./Animations/animatable.ts": /*!**********************************!*\ !*** ./Animations/animatable.ts ***! \**********************************/ /*! exports provided: Animatable */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Animatable", function() { return Animatable; }); /* harmony import */ var _animation__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./animation */ "./Animations/animation.ts"); /* harmony import */ var _runtimeAnimation__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./runtimeAnimation */ "./Animations/runtimeAnimation.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../scene */ "./scene.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Misc/precisionDate */ "./Misc/precisionDate.ts"); /* harmony import */ var _Bones_bone__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Bones/bone */ "./Bones/bone.ts"); /** * Class used to store an actual running animation */ var Animatable = /** @class */ (function () { /** * Creates a new Animatable * @param scene defines the hosting scene * @param target defines the target object * @param fromFrame defines the starting frame number (default is 0) * @param toFrame defines the ending frame number (default is 100) * @param loopAnimation defines if the animation must loop (default is false) * @param speedRatio defines the factor to apply to animation speed (default is 1) * @param onAnimationEnd defines a callback to call when animation ends if it is not looping * @param animations defines a group of animation to add to the new Animatable * @param onAnimationLoop defines a callback to call when animation loops */ function Animatable(scene, /** defines the target object */ target, /** defines the starting frame number (default is 0) */ fromFrame, /** defines the ending frame number (default is 100) */ toFrame, /** defines if the animation must loop (default is false) */ loopAnimation, speedRatio, /** defines a callback to call when animation ends if it is not looping */ onAnimationEnd, animations, /** defines a callback to call when animation loops */ onAnimationLoop) { if (fromFrame === void 0) { fromFrame = 0; } if (toFrame === void 0) { toFrame = 100; } if (loopAnimation === void 0) { loopAnimation = false; } if (speedRatio === void 0) { speedRatio = 1.0; } this.target = target; this.fromFrame = fromFrame; this.toFrame = toFrame; this.loopAnimation = loopAnimation; this.onAnimationEnd = onAnimationEnd; this.onAnimationLoop = onAnimationLoop; this._localDelayOffset = null; this._pausedDelay = null; this._runtimeAnimations = new Array(); this._paused = false; this._speedRatio = 1; this._weight = -1.0; /** * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation. * This will only apply for non looping animation (default is true) */ this.disposeOnEnd = true; /** * Gets a boolean indicating if the animation has started */ this.animationStarted = false; /** * Observer raised when the animation ends */ this.onAnimationEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Observer raised when the animation loops */ this.onAnimationLoopObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); this._scene = scene; if (animations) { this.appendAnimations(target, animations); } this._speedRatio = speedRatio; scene._activeAnimatables.push(this); } Object.defineProperty(Animatable.prototype, "syncRoot", { /** * Gets the root Animatable used to synchronize and normalize animations */ get: function () { return this._syncRoot; }, enumerable: true, configurable: true }); Object.defineProperty(Animatable.prototype, "masterFrame", { /** * Gets the current frame of the first RuntimeAnimation * Used to synchronize Animatables */ get: function () { if (this._runtimeAnimations.length === 0) { return 0; } return this._runtimeAnimations[0].currentFrame; }, enumerable: true, configurable: true }); Object.defineProperty(Animatable.prototype, "weight", { /** * Gets or sets the animatable weight (-1.0 by default meaning not weighted) */ get: function () { return this._weight; }, set: function (value) { if (value === -1) { // -1 is ok and means no weight this._weight = -1; return; } // Else weight must be in [0, 1] range this._weight = Math.min(Math.max(value, 0), 1.0); }, enumerable: true, configurable: true }); Object.defineProperty(Animatable.prototype, "speedRatio", { /** * Gets or sets the speed ratio to apply to the animatable (1.0 by default) */ get: function () { return this._speedRatio; }, set: function (value) { for (var index = 0; index < this._runtimeAnimations.length; index++) { var animation = this._runtimeAnimations[index]; animation._prepareForSpeedRatioChange(value); } this._speedRatio = value; }, enumerable: true, configurable: true }); // Methods /** * Synchronize and normalize current Animatable with a source Animatable * This is useful when using animation weights and when animations are not of the same length * @param root defines the root Animatable to synchronize with * @returns the current Animatable */ Animatable.prototype.syncWith = function (root) { this._syncRoot = root; if (root) { // Make sure this animatable will animate after the root var index = this._scene._activeAnimatables.indexOf(this); if (index > -1) { this._scene._activeAnimatables.splice(index, 1); this._scene._activeAnimatables.push(this); } } return this; }; /** * Gets the list of runtime animations * @returns an array of RuntimeAnimation */ Animatable.prototype.getAnimations = function () { return this._runtimeAnimations; }; /** * Adds more animations to the current animatable * @param target defines the target of the animations * @param animations defines the new animations to add */ Animatable.prototype.appendAnimations = function (target, animations) { for (var index = 0; index < animations.length; index++) { var animation = animations[index]; this._runtimeAnimations.push(new _runtimeAnimation__WEBPACK_IMPORTED_MODULE_1__["RuntimeAnimation"](target, animation, this._scene, this)); } }; /** * Gets the source animation for a specific property * @param property defines the propertyu to look for * @returns null or the source animation for the given property */ Animatable.prototype.getAnimationByTargetProperty = function (property) { var runtimeAnimations = this._runtimeAnimations; for (var index = 0; index < runtimeAnimations.length; index++) { if (runtimeAnimations[index].animation.targetProperty === property) { return runtimeAnimations[index].animation; } } return null; }; /** * Gets the runtime animation for a specific property * @param property defines the propertyu to look for * @returns null or the runtime animation for the given property */ Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) { var runtimeAnimations = this._runtimeAnimations; for (var index = 0; index < runtimeAnimations.length; index++) { if (runtimeAnimations[index].animation.targetProperty === property) { return runtimeAnimations[index]; } } return null; }; /** * Resets the animatable to its original state */ Animatable.prototype.reset = function () { var runtimeAnimations = this._runtimeAnimations; for (var index = 0; index < runtimeAnimations.length; index++) { runtimeAnimations[index].reset(true); } this._localDelayOffset = null; this._pausedDelay = null; }; /** * Allows the animatable to blend with current running animations * @see http://doc.babylonjs.com/babylon101/animations#animation-blending * @param blendingSpeed defines the blending speed to use */ Animatable.prototype.enableBlending = function (blendingSpeed) { var runtimeAnimations = this._runtimeAnimations; for (var index = 0; index < runtimeAnimations.length; index++) { runtimeAnimations[index].animation.enableBlending = true; runtimeAnimations[index].animation.blendingSpeed = blendingSpeed; } }; /** * Disable animation blending * @see http://doc.babylonjs.com/babylon101/animations#animation-blending */ Animatable.prototype.disableBlending = function () { var runtimeAnimations = this._runtimeAnimations; for (var index = 0; index < runtimeAnimations.length; index++) { runtimeAnimations[index].animation.enableBlending = false; } }; /** * Jump directly to a given frame * @param frame defines the frame to jump to */ Animatable.prototype.goToFrame = function (frame) { var runtimeAnimations = this._runtimeAnimations; if (runtimeAnimations[0]) { var fps = runtimeAnimations[0].animation.framePerSecond; var currentFrame = runtimeAnimations[0].currentFrame; var adjustTime = frame - currentFrame; var delay = adjustTime * 1000 / (fps * this.speedRatio); if (this._localDelayOffset === null) { this._localDelayOffset = 0; } this._localDelayOffset -= delay; } for (var index = 0; index < runtimeAnimations.length; index++) { runtimeAnimations[index].goToFrame(frame); } }; /** * Pause the animation */ Animatable.prototype.pause = function () { if (this._paused) { return; } this._paused = true; }; /** * Restart the animation */ Animatable.prototype.restart = function () { this._paused = false; }; Animatable.prototype._raiseOnAnimationEnd = function () { if (this.onAnimationEnd) { this.onAnimationEnd(); } this.onAnimationEndObservable.notifyObservers(this); }; /** * Stop and delete the current animation * @param animationName defines a string used to only stop some of the runtime animations instead of all * @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) */ Animatable.prototype.stop = function (animationName, targetMask) { if (animationName || targetMask) { var idx = this._scene._activeAnimatables.indexOf(this); if (idx > -1) { var runtimeAnimations = this._runtimeAnimations; for (var index = runtimeAnimations.length - 1; index >= 0; index--) { var runtimeAnimation = runtimeAnimations[index]; if (animationName && runtimeAnimation.animation.name != animationName) { continue; } if (targetMask && !targetMask(runtimeAnimation.target)) { continue; } runtimeAnimation.dispose(); runtimeAnimations.splice(index, 1); } if (runtimeAnimations.length == 0) { this._scene._activeAnimatables.splice(idx, 1); this._raiseOnAnimationEnd(); } } } else { var index = this._scene._activeAnimatables.indexOf(this); if (index > -1) { this._scene._activeAnimatables.splice(index, 1); var runtimeAnimations = this._runtimeAnimations; for (var index = 0; index < runtimeAnimations.length; index++) { runtimeAnimations[index].dispose(); } this._raiseOnAnimationEnd(); } } }; /** * Wait asynchronously for the animation to end * @returns a promise which will be fullfilled when the animation ends */ Animatable.prototype.waitAsync = function () { var _this = this; return new Promise(function (resolve, reject) { _this.onAnimationEndObservable.add(function () { resolve(_this); }, undefined, undefined, _this, true); }); }; /** @hidden */ Animatable.prototype._animate = function (delay) { var _this = this; if (this._paused) { this.animationStarted = false; if (this._pausedDelay === null) { this._pausedDelay = delay; } return true; } if (this._localDelayOffset === null) { this._localDelayOffset = delay; this._pausedDelay = null; } else if (this._pausedDelay !== null) { this._localDelayOffset += delay - this._pausedDelay; this._pausedDelay = null; } if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused return true; } // Animating var running = false; var runtimeAnimations = this._runtimeAnimations; var index; for (index = 0; index < runtimeAnimations.length; index++) { var animation = runtimeAnimations[index]; var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight, function () { _this.onAnimationLoopObservable.notifyObservers(_this); if (_this.onAnimationLoop) { _this.onAnimationLoop(); } }); running = running || isRunning; } this.animationStarted = running; if (!running) { if (this.disposeOnEnd) { // Remove from active animatables index = this._scene._activeAnimatables.indexOf(this); this._scene._activeAnimatables.splice(index, 1); // Dispose all runtime animations for (index = 0; index < runtimeAnimations.length; index++) { runtimeAnimations[index].dispose(); } } this._raiseOnAnimationEnd(); if (this.disposeOnEnd) { this.onAnimationEnd = null; this.onAnimationLoop = null; this.onAnimationLoopObservable.clear(); this.onAnimationEndObservable.clear(); } } return running; }; return Animatable; }()); _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype._animate = function () { if (!this.animationsEnabled || this._activeAnimatables.length === 0) { return; } // Getting time var now = _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_5__["PrecisionDate"].Now; if (!this._animationTimeLast) { if (this._pendingData.length > 0) { return; } this._animationTimeLast = now; } var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale; this._animationTime += deltaTime; this._animationTimeLast = now; for (var index = 0; index < this._activeAnimatables.length; index++) { this._activeAnimatables[index]._animate(this._animationTime); } // Late animation bindings this._processLateAnimationBindings(); }; _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask, onAnimationLoop) { if (weight === void 0) { weight = 1.0; } if (speedRatio === void 0) { speedRatio = 1.0; } var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask, onAnimationLoop); returnedAnimatable.weight = weight; return returnedAnimatable; }; _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, onAnimationLoop) { if (speedRatio === void 0) { speedRatio = 1.0; } if (stopCurrent === void 0) { stopCurrent = true; } if (from > to && speedRatio > 0) { speedRatio *= -1; } if (stopCurrent) { this.stopAnimation(target, undefined, targetMask); } if (!animatable) { animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, undefined, onAnimationLoop); } var shouldRunTargetAnimations = targetMask ? targetMask(target) : true; // Local animations if (target.animations && shouldRunTargetAnimations) { animatable.appendAnimations(target, target.animations); } // Children animations if (target.getAnimatables) { var animatables = target.getAnimatables(); for (var index = 0; index < animatables.length; index++) { this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, onAnimationLoop); } } animatable.reset(); return animatable; }; _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.beginHierarchyAnimation = function (target, directDescendantsOnly, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, onAnimationLoop) { if (speedRatio === void 0) { speedRatio = 1.0; } if (stopCurrent === void 0) { stopCurrent = true; } var children = target.getDescendants(directDescendantsOnly); var result = []; result.push(this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask)); for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { var child = children_1[_i]; result.push(this.beginAnimation(child, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask)); } return result; }; _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop) { if (speedRatio === undefined) { speedRatio = 1.0; } var animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations, onAnimationLoop); return animatable; }; _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop) { var children = target.getDescendants(directDescendantsOnly); var result = []; result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop)); for (var _i = 0, children_2 = children; _i < children_2.length; _i++) { var child = children_2[_i]; result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop)); } return result; }; _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.getAnimatableByTarget = function (target) { for (var index = 0; index < this._activeAnimatables.length; index++) { if (this._activeAnimatables[index].target === target) { return this._activeAnimatables[index]; } } return null; }; _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.getAllAnimatablesByTarget = function (target) { var result = []; for (var index = 0; index < this._activeAnimatables.length; index++) { if (this._activeAnimatables[index].target === target) { result.push(this._activeAnimatables[index]); } } return result; }; /** * 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) */ _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.stopAnimation = function (target, animationName, targetMask) { var animatables = this.getAllAnimatablesByTarget(target); for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) { var animatable = animatables_1[_i]; animatable.stop(animationName, targetMask); } }; /** * Stops and removes all animations that have been applied to the scene */ _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.stopAllAnimations = function () { if (this._activeAnimatables) { for (var i = 0; i < this._activeAnimatables.length; i++) { this._activeAnimatables[i].stop(); } this._activeAnimatables = []; } for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) { var group = _a[_i]; group.stop(); } }; _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) { var target = runtimeAnimation.target; this._registeredForLateAnimationBindings.pushNoDuplicate(target); if (!target._lateAnimationHolders) { target._lateAnimationHolders = {}; } if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) { target._lateAnimationHolders[runtimeAnimation.targetPath] = { totalWeight: 0, animations: [], originalValue: originalValue }; } target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation); target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight; }; _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype._processLateAnimationBindingsForMatrices = function (holder) { var normalizer = 1.0; var finalPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Tmp"].Vector3[0]; var finalScaling = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Tmp"].Vector3[1]; var finalQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Tmp"].Quaternion[0]; var startIndex = 0; var originalAnimation = holder.animations[0]; var originalValue = holder.originalValue; var scale = 1; if (holder.totalWeight < 1.0) { // We need to mix the original value in originalValue.decompose(finalScaling, finalQuaternion, finalPosition); scale = 1.0 - holder.totalWeight; } else { startIndex = 1; // We need to normalize the weights normalizer = holder.totalWeight; originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition); scale = originalAnimation.weight / normalizer; if (scale == 1) { return originalAnimation.currentValue; } } finalScaling.scaleInPlace(scale); finalPosition.scaleInPlace(scale); finalQuaternion.scaleInPlace(scale); for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) { var runtimeAnimation = holder.animations[animIndex]; var scale = runtimeAnimation.weight / normalizer; var currentPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Tmp"].Vector3[2]; var currentScaling = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Tmp"].Vector3[3]; var currentQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Tmp"].Quaternion[1]; runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition); currentScaling.scaleAndAddToRef(scale, finalScaling); currentQuaternion.scaleAndAddToRef(scale, finalQuaternion); currentPosition.scaleAndAddToRef(scale, finalPosition); } _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue); return originalAnimation._workValue; }; _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) { var originalAnimation = holder.animations[0]; var originalValue = holder.originalValue; if (holder.animations.length === 1) { _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion); return refQuaternion; } var normalizer = 1.0; var quaternions; var weights; if (holder.totalWeight < 1.0) { var scale = 1.0 - holder.totalWeight; quaternions = []; weights = []; quaternions.push(originalValue); weights.push(scale); } else { if (holder.animations.length === 2) { // Slerp as soon as we can _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion); return refQuaternion; } quaternions = []; weights = []; normalizer = holder.totalWeight; } for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) { var runtimeAnimation = holder.animations[animIndex]; quaternions.push(runtimeAnimation.currentValue); weights.push(runtimeAnimation.weight / normalizer); } // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions var cumulativeAmount = 0; var cumulativeQuaternion = null; for (var index = 0; index < quaternions.length;) { if (!cumulativeQuaternion) { _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion); cumulativeQuaternion = refQuaternion; cumulativeAmount = weights[index] + weights[index + 1]; index += 2; continue; } cumulativeAmount += weights[index]; _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion); index++; } return cumulativeQuaternion; }; _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype._processLateAnimationBindings = function () { if (!this._registeredForLateAnimationBindings.length) { return; } for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) { var target = this._registeredForLateAnimationBindings.data[index]; for (var path in target._lateAnimationHolders) { var holder = target._lateAnimationHolders[path]; var originalAnimation = holder.animations[0]; var originalValue = holder.originalValue; var matrixDecomposeMode = _animation__WEBPACK_IMPORTED_MODULE_0__["Animation"].AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix var finalValue = target[path]; if (matrixDecomposeMode) { finalValue = this._processLateAnimationBindingsForMatrices(holder); } else { var quaternionMode = originalValue.w !== undefined; if (quaternionMode) { finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].Identity()); } else { var startIndex = 0; var normalizer = 1.0; if (holder.totalWeight < 1.0) { // We need to mix the original value in if (originalValue.scale) { finalValue = originalValue.scale(1.0 - holder.totalWeight); } else { finalValue = originalValue * (1.0 - holder.totalWeight); } } else { // We need to normalize the weights normalizer = holder.totalWeight; var scale_1 = originalAnimation.weight / normalizer; if (scale_1 !== 1) { if (originalAnimation.currentValue.scale) { finalValue = originalAnimation.currentValue.scale(scale_1); } else { finalValue = originalAnimation.currentValue * scale_1; } } else { finalValue = originalAnimation.currentValue; } startIndex = 1; } for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) { var runtimeAnimation = holder.animations[animIndex]; var scale = runtimeAnimation.weight / normalizer; if (runtimeAnimation.currentValue.scaleAndAddToRef) { runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue); } else { finalValue += runtimeAnimation.currentValue * scale; } } } } target[path] = finalValue; } target._lateAnimationHolders = {}; } this._registeredForLateAnimationBindings.reset(); }; _Bones_bone__WEBPACK_IMPORTED_MODULE_6__["Bone"].prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) { if (rescaleAsRequired === void 0) { rescaleAsRequired = false; } if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; } // all animation may be coming from a library skeleton, so may need to create animation if (this.animations.length === 0) { this.animations.push(new _animation__WEBPACK_IMPORTED_MODULE_0__["Animation"](this.name, "_matrix", source.animations[0].framePerSecond, _animation__WEBPACK_IMPORTED_MODULE_0__["Animation"].ANIMATIONTYPE_MATRIX, 0)); this.animations[0].setKeys([]); } // get animation info / verify there is such a range from the source bone var sourceRange = source.animations[0].getRange(rangeName); if (!sourceRange) { return false; } var from = sourceRange.from; var to = sourceRange.to; var sourceKeys = source.animations[0].getKeys(); // rescaling prep var sourceBoneLength = source.length; var sourceParent = source.getParent(); var parent = this.getParent(); var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length; var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1; var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1); var destKeys = this.animations[0].getKeys(); // loop vars declaration var orig; var origTranslation; var mat; for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) { orig = sourceKeys[key]; if (orig.frame >= from && orig.frame <= to) { if (rescaleAsRequired) { mat = orig.value.clone(); // scale based on parent ratio, when bone has parent if (parentScalingReqd) { origTranslation = mat.getTranslation(); mat.setTranslation(origTranslation.scaleInPlace(parentRatio)); // scale based on skeleton dimension ratio when root bone, and value is passed } else if (dimensionsScalingReqd && skelDimensionsRatio) { origTranslation = mat.getTranslation(); mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio)); // use original when root bone, and no data for skelDimensionsRatio } else { mat = orig.value; } } else { mat = orig.value; } destKeys.push({ frame: orig.frame + frameOffset, value: mat }); } } this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset); return true; }; /***/ }), /***/ "./Animations/animation.ts": /*!*********************************!*\ !*** ./Animations/animation.ts ***! \*********************************/ /*! exports provided: Animation */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Animation", function() { return Animation; }); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math.scalar */ "./Maths/math.scalar.ts"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); /* harmony import */ var _animationKey__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./animationKey */ "./Animations/animationKey.ts"); /* harmony import */ var _animationRange__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./animationRange */ "./Animations/animationRange.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../node */ "./node.ts"); /** * Class used to store any kind of animation */ var Animation = /** @class */ (function () { /** * Initializes the animation * @param name Name of the animation * @param targetProperty Property to animate * @param framePerSecond The frames per second of the animation * @param dataType The data type of the animation * @param loopMode The loop mode of the animation * @param enableBlending Specifies if blending should be enabled */ function Animation( /**Name of the animation */ name, /**Property to animate */ targetProperty, /**The frames per second of the animation */ framePerSecond, /**The data type of the animation */ dataType, /**The loop mode of the animation */ loopMode, /**Specifies if blending should be enabled */ enableBlending) { this.name = name; this.targetProperty = targetProperty; this.framePerSecond = framePerSecond; this.dataType = dataType; this.loopMode = loopMode; this.enableBlending = enableBlending; /** * @hidden Internal use only */ this._runtimeAnimations = new Array(); /** * The set of event that will be linked to this animation */ this._events = new Array(); /** * Stores the blending speed of the animation */ this.blendingSpeed = 0.01; /** * Stores the animation ranges for the animation */ this._ranges = {}; this.targetPropertyPath = targetProperty.split("."); this.dataType = dataType; this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode; } /** * @hidden Internal use */ Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) { var dataType = undefined; if (!isNaN(parseFloat(from)) && isFinite(from)) { dataType = Animation.ANIMATIONTYPE_FLOAT; } else if (from instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"]) { dataType = Animation.ANIMATIONTYPE_QUATERNION; } else if (from instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"]) { dataType = Animation.ANIMATIONTYPE_VECTOR3; } else if (from instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"]) { dataType = Animation.ANIMATIONTYPE_VECTOR2; } else if (from instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"]) { dataType = Animation.ANIMATIONTYPE_COLOR3; } else if (from instanceof _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Size"]) { dataType = Animation.ANIMATIONTYPE_SIZE; } if (dataType == undefined) { return null; } var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode); var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }]; animation.setKeys(keys); if (easingFunction !== undefined) { animation.setEasingFunction(easingFunction); } return animation; }; /** * Sets up an animation * @param property The property to animate * @param animationType The animation type to apply * @param framePerSecond The frames per second of the animation * @param easingFunction The easing function used in the animation * @returns The created animation */ Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) { var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT); animation.setEasingFunction(easingFunction); return animation; }; /** * Create and start an animation on a node * @param name defines the name of the global animation that will be run on all nodes * @param node defines the root node where the animation will take place * @param targetProperty defines property to animate * @param framePerSecond defines the number of frame per second yo use * @param totalFrame defines the number of frames in total * @param from defines the initial value * @param to defines the final value * @param loopMode defines which loop mode you want to use (off by default) * @param easingFunction defines the easing function to use (linear by default) * @param onAnimationEnd defines the callback to call when animation end * @returns the animatable created for this animation */ Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) { var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction); if (!animation) { return null; } return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd); }; /** * Create and start an animation on a node and its descendants * @param name defines the name of the global animation that will be run on all nodes * @param node defines the root node where the animation will take place * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used * @param targetProperty defines property to animate * @param framePerSecond defines the number of frame per second to use * @param totalFrame defines the number of frames in total * @param from defines the initial value * @param to defines the final value * @param loopMode defines which loop mode you want to use (off by default) * @param easingFunction defines the easing function to use (linear by default) * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node) * @returns the list of animatables created for all nodes * @example https://www.babylonjs-playground.com/#MH0VLI */ Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) { var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction); if (!animation) { return null; } var scene = node.getScene(); return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd); }; /** * Creates a new animation, merges it with the existing animations and starts it * @param name Name of the animation * @param node Node which contains the scene that begins the animations * @param targetProperty Specifies which property to animate * @param framePerSecond The frames per second of the animation * @param totalFrame The total number of frames * @param from The frame at the beginning of the animation * @param to The frame at the end of the animation * @param loopMode Specifies the loop mode of the animation * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations * @param onAnimationEnd Callback to run once the animation is complete * @returns Nullable animation */ Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) { var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction); if (!animation) { return null; } node.animations.push(animation); return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd); }; /** * Transition property of an host to the target Value * @param property The property to transition * @param targetValue The target Value of the property * @param host The object where the property to animate belongs * @param scene Scene used to run the animation * @param frameRate Framerate (in frame/s) to use * @param transition The transition type we want to use * @param duration The duration of the animation, in milliseconds * @param onAnimationEnd Callback trigger at the end of the animation * @returns Nullable animation */ Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) { if (onAnimationEnd === void 0) { onAnimationEnd = null; } if (duration <= 0) { host[property] = targetValue; if (onAnimationEnd) { onAnimationEnd(); } return null; } var endFrame = frameRate * (duration / 1000); transition.setKeys([{ frame: 0, value: host[property].clone ? host[property].clone() : host[property] }, { frame: endFrame, value: targetValue }]); if (!host.animations) { host.animations = []; } host.animations.push(transition); var animation = scene.beginAnimation(host, 0, endFrame, false); animation.onAnimationEnd = onAnimationEnd; return animation; }; Object.defineProperty(Animation.prototype, "runtimeAnimations", { /** * Return the array of runtime animations currently using this animation */ get: function () { return this._runtimeAnimations; }, enumerable: true, configurable: true }); Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", { /** * Specifies if any of the runtime animations are currently running */ get: function () { for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) { var runtimeAnimation = _a[_i]; if (!runtimeAnimation.isStopped) { return true; } } return false; }, enumerable: true, configurable: true }); // Methods /** * Converts the animation to a string * @param fullDetails support for multiple levels of logging within scene loading * @returns String form of the animation */ Animation.prototype.toString = function (fullDetails) { var ret = "Name: " + this.name + ", property: " + this.targetProperty; ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType]; ret += ", nKeys: " + (this._keys ? this._keys.length : "none"); ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none"); if (fullDetails) { ret += ", Ranges: {"; var first = true; for (var name in this._ranges) { if (first) { ret += ", "; first = false; } ret += name; } ret += "}"; } return ret; }; /** * Add an event to this animation * @param event Event to add */ Animation.prototype.addEvent = function (event) { this._events.push(event); }; /** * Remove all events found at the given frame * @param frame The frame to remove events from */ Animation.prototype.removeEvents = function (frame) { for (var index = 0; index < this._events.length; index++) { if (this._events[index].frame === frame) { this._events.splice(index, 1); index--; } } }; /** * Retrieves all the events from the animation * @returns Events from the animation */ Animation.prototype.getEvents = function () { return this._events; }; /** * Creates an animation range * @param name Name of the animation range * @param from Starting frame of the animation range * @param to Ending frame of the animation */ Animation.prototype.createRange = function (name, from, to) { // check name not already in use; could happen for bones after serialized if (!this._ranges[name]) { this._ranges[name] = new _animationRange__WEBPACK_IMPORTED_MODULE_5__["AnimationRange"](name, from, to); } }; /** * Deletes an animation range by name * @param name Name of the animation range to delete * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false) */ Animation.prototype.deleteRange = function (name, deleteFrames) { if (deleteFrames === void 0) { deleteFrames = true; } var range = this._ranges[name]; if (!range) { return; } if (deleteFrames) { var from = range.from; var to = range.to; // this loop MUST go high to low for multiple splices to work for (var key = this._keys.length - 1; key >= 0; key--) { if (this._keys[key].frame >= from && this._keys[key].frame <= to) { this._keys.splice(key, 1); } } } this._ranges[name] = null; // said much faster than 'delete this._range[name]' }; /** * Gets the animation range by name, or null if not defined * @param name Name of the animation range * @returns Nullable animation range */ Animation.prototype.getRange = function (name) { return this._ranges[name]; }; /** * Gets the key frames from the animation * @returns The key frames of the animation */ Animation.prototype.getKeys = function () { return this._keys; }; /** * Gets the highest frame rate of the animation * @returns Highest frame rate of the animation */ Animation.prototype.getHighestFrame = function () { var ret = 0; for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) { if (ret < this._keys[key].frame) { ret = this._keys[key].frame; } } return ret; }; /** * Gets the easing function of the animation * @returns Easing function of the animation */ Animation.prototype.getEasingFunction = function () { return this._easingFunction; }; /** * Sets the easing function of the animation * @param easingFunction A custom mathematical formula for animation */ Animation.prototype.setEasingFunction = function (easingFunction) { this._easingFunction = easingFunction; }; /** * Interpolates a scalar linearly * @param startValue Start value of the animation curve * @param endValue End value of the animation curve * @param gradient Scalar amount to interpolate * @returns Interpolated scalar value */ Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) { return _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_1__["Scalar"].Lerp(startValue, endValue, gradient); }; /** * Interpolates a scalar cubically * @param startValue Start value of the animation curve * @param outTangent End tangent of the animation * @param endValue End value of the animation curve * @param inTangent Start tangent of the animation curve * @param gradient Scalar amount to interpolate * @returns Interpolated scalar value */ Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) { return _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_1__["Scalar"].Hermite(startValue, outTangent, endValue, inTangent, gradient); }; /** * Interpolates a quaternion using a spherical linear interpolation * @param startValue Start value of the animation curve * @param endValue End value of the animation curve * @param gradient Scalar amount to interpolate * @returns Interpolated quaternion value */ Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) { return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Slerp(startValue, endValue, gradient); }; /** * Interpolates a quaternion cubically * @param startValue Start value of the animation curve * @param outTangent End tangent of the animation curve * @param endValue End value of the animation curve * @param inTangent Start tangent of the animation curve * @param gradient Scalar amount to interpolate * @returns Interpolated quaternion value */ Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) { return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize(); }; /** * Interpolates a Vector3 linearl * @param startValue Start value of the animation curve * @param endValue End value of the animation curve * @param gradient Scalar amount to interpolate * @returns Interpolated scalar value */ Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) { return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Lerp(startValue, endValue, gradient); }; /** * Interpolates a Vector3 cubically * @param startValue Start value of the animation curve * @param outTangent End tangent of the animation * @param endValue End value of the animation curve * @param inTangent Start tangent of the animation curve * @param gradient Scalar amount to interpolate * @returns InterpolatedVector3 value */ Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) { return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Hermite(startValue, outTangent, endValue, inTangent, gradient); }; /** * Interpolates a Vector2 linearly * @param startValue Start value of the animation curve * @param endValue End value of the animation curve * @param gradient Scalar amount to interpolate * @returns Interpolated Vector2 value */ Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) { return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"].Lerp(startValue, endValue, gradient); }; /** * Interpolates a Vector2 cubically * @param startValue Start value of the animation curve * @param outTangent End tangent of the animation * @param endValue End value of the animation curve * @param inTangent Start tangent of the animation curve * @param gradient Scalar amount to interpolate * @returns Interpolated Vector2 value */ Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) { return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"].Hermite(startValue, outTangent, endValue, inTangent, gradient); }; /** * Interpolates a size linearly * @param startValue Start value of the animation curve * @param endValue End value of the animation curve * @param gradient Scalar amount to interpolate * @returns Interpolated Size value */ Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) { return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Size"].Lerp(startValue, endValue, gradient); }; /** * Interpolates a Color3 linearly * @param startValue Start value of the animation curve * @param endValue End value of the animation curve * @param gradient Scalar amount to interpolate * @returns Interpolated Color3 value */ Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) { return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].Lerp(startValue, endValue, gradient); }; /** * @hidden Internal use only */ Animation.prototype._getKeyValue = function (value) { if (typeof value === "function") { return value(); } return value; }; /** * @hidden Internal use only */ Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) { if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) { return highLimitValue.clone ? highLimitValue.clone() : highLimitValue; } var keys = this.getKeys(); if (keys.length === 1) { return this._getKeyValue(keys[0].value); } // Try to get a hash to find the right key var startKeyIndex = Math.max(0, Math.min(keys.length - 1, Math.floor(keys.length * (currentFrame - keys[0].frame) / (keys[keys.length - 1].frame - keys[0].frame)) - 1)); if (keys[startKeyIndex].frame >= currentFrame) { while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) { startKeyIndex--; } } for (var key = startKeyIndex; key < keys.length; key++) { var endKey = keys[key + 1]; if (endKey.frame >= currentFrame) { var startKey = keys[key]; var startValue = this._getKeyValue(startKey.value); if (startKey.interpolation === _animationKey__WEBPACK_IMPORTED_MODULE_4__["AnimationKeyInterpolation"].STEP) { return startValue; } var endValue = this._getKeyValue(endKey.value); var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined; var frameDelta = endKey.frame - startKey.frame; // gradient : percent of currentFrame between the frame inf and the frame sup var gradient = (currentFrame - startKey.frame) / frameDelta; // check for easingFunction and correction of gradient var easingFunction = this.getEasingFunction(); if (easingFunction != null) { gradient = easingFunction.ease(gradient); } switch (this.dataType) { // Float case Animation.ANIMATIONTYPE_FLOAT: var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient); switch (loopMode) { case Animation.ANIMATIONLOOPMODE_CYCLE: case Animation.ANIMATIONLOOPMODE_CONSTANT: return floatValue; case Animation.ANIMATIONLOOPMODE_RELATIVE: return offsetValue * repeatCount + floatValue; } break; // Quaternion case Animation.ANIMATIONTYPE_QUATERNION: var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient); switch (loopMode) { case Animation.ANIMATIONLOOPMODE_CYCLE: case Animation.ANIMATIONLOOPMODE_CONSTANT: return quatValue; case Animation.ANIMATIONLOOPMODE_RELATIVE: return quatValue.addInPlace(offsetValue.scale(repeatCount)); } return quatValue; // Vector3 case Animation.ANIMATIONTYPE_VECTOR3: var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient); switch (loopMode) { case Animation.ANIMATIONLOOPMODE_CYCLE: case Animation.ANIMATIONLOOPMODE_CONSTANT: return vec3Value; case Animation.ANIMATIONLOOPMODE_RELATIVE: return vec3Value.add(offsetValue.scale(repeatCount)); } // Vector2 case Animation.ANIMATIONTYPE_VECTOR2: var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient); switch (loopMode) { case Animation.ANIMATIONLOOPMODE_CYCLE: case Animation.ANIMATIONLOOPMODE_CONSTANT: return vec2Value; case Animation.ANIMATIONLOOPMODE_RELATIVE: return vec2Value.add(offsetValue.scale(repeatCount)); } // Size case Animation.ANIMATIONTYPE_SIZE: switch (loopMode) { case Animation.ANIMATIONLOOPMODE_CYCLE: case Animation.ANIMATIONLOOPMODE_CONSTANT: return this.sizeInterpolateFunction(startValue, endValue, gradient); case Animation.ANIMATIONLOOPMODE_RELATIVE: return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount)); } // Color3 case Animation.ANIMATIONTYPE_COLOR3: switch (loopMode) { case Animation.ANIMATIONLOOPMODE_CYCLE: case Animation.ANIMATIONLOOPMODE_CONSTANT: return this.color3InterpolateFunction(startValue, endValue, gradient); case Animation.ANIMATIONLOOPMODE_RELATIVE: return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount)); } // Matrix case Animation.ANIMATIONTYPE_MATRIX: switch (loopMode) { case Animation.ANIMATIONLOOPMODE_CYCLE: case Animation.ANIMATIONLOOPMODE_CONSTANT: if (Animation.AllowMatricesInterpolation) { return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue); } case Animation.ANIMATIONLOOPMODE_RELATIVE: return startValue; } default: break; } break; } } return this._getKeyValue(keys[keys.length - 1].value); }; /** * Defines the function to use to interpolate matrices * @param startValue defines the start matrix * @param endValue defines the end matrix * @param gradient defines the gradient between both matrices * @param result defines an optional target matrix where to store the interpolation * @returns the interpolated matrix */ Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) { if (Animation.AllowMatrixDecomposeForInterpolation) { if (result) { _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].DecomposeLerpToRef(startValue, endValue, gradient, result); return result; } return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].DecomposeLerp(startValue, endValue, gradient); } if (result) { _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].LerpToRef(startValue, endValue, gradient, result); return result; } return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Lerp(startValue, endValue, gradient); }; /** * Makes a copy of the animation * @returns Cloned animation */ Animation.prototype.clone = function () { var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode); clone.enableBlending = this.enableBlending; clone.blendingSpeed = this.blendingSpeed; if (this._keys) { clone.setKeys(this._keys); } if (this._ranges) { clone._ranges = {}; for (var name in this._ranges) { var range = this._ranges[name]; if (!range) { continue; } clone._ranges[name] = range.clone(); } } return clone; }; /** * Sets the key frames of the animation * @param values The animation key frames to set */ Animation.prototype.setKeys = function (values) { this._keys = values.slice(0); }; /** * Serializes the animation to an object * @returns Serialized object */ Animation.prototype.serialize = function () { var serializationObject = {}; serializationObject.name = this.name; serializationObject.property = this.targetProperty; serializationObject.framePerSecond = this.framePerSecond; serializationObject.dataType = this.dataType; serializationObject.loopBehavior = this.loopMode; serializationObject.enableBlending = this.enableBlending; serializationObject.blendingSpeed = this.blendingSpeed; var dataType = this.dataType; serializationObject.keys = []; var keys = this.getKeys(); for (var index = 0; index < keys.length; index++) { var animationKey = keys[index]; var key = {}; key.frame = animationKey.frame; switch (dataType) { case Animation.ANIMATIONTYPE_FLOAT: key.values = [animationKey.value]; break; case Animation.ANIMATIONTYPE_QUATERNION: case Animation.ANIMATIONTYPE_MATRIX: case Animation.ANIMATIONTYPE_VECTOR3: case Animation.ANIMATIONTYPE_COLOR3: key.values = animationKey.value.asArray(); break; } serializationObject.keys.push(key); } serializationObject.ranges = []; for (var name in this._ranges) { var source = this._ranges[name]; if (!source) { continue; } var range = {}; range.name = name; range.from = source.from; range.to = source.to; serializationObject.ranges.push(range); } return serializationObject; }; Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", { /** * Get the float animation type */ get: function () { return Animation._ANIMATIONTYPE_FLOAT; }, enumerable: true, configurable: true }); Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", { /** * Get the Vector3 animation type */ get: function () { return Animation._ANIMATIONTYPE_VECTOR3; }, enumerable: true, configurable: true }); Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", { /** * Get the Vector2 animation type */ get: function () { return Animation._ANIMATIONTYPE_VECTOR2; }, enumerable: true, configurable: true }); Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", { /** * Get the Size animation type */ get: function () { return Animation._ANIMATIONTYPE_SIZE; }, enumerable: true, configurable: true }); Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", { /** * Get the Quaternion animation type */ get: function () { return Animation._ANIMATIONTYPE_QUATERNION; }, enumerable: true, configurable: true }); Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", { /** * Get the Matrix animation type */ get: function () { return Animation._ANIMATIONTYPE_MATRIX; }, enumerable: true, configurable: true }); Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", { /** * Get the Color3 animation type */ get: function () { return Animation._ANIMATIONTYPE_COLOR3; }, enumerable: true, configurable: true }); Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", { /** * Get the Relative Loop Mode */ get: function () { return Animation._ANIMATIONLOOPMODE_RELATIVE; }, enumerable: true, configurable: true }); Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", { /** * Get the Cycle Loop Mode */ get: function () { return Animation._ANIMATIONLOOPMODE_CYCLE; }, enumerable: true, configurable: true }); Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", { /** * Get the Constant Loop Mode */ get: function () { return Animation._ANIMATIONLOOPMODE_CONSTANT; }, enumerable: true, configurable: true }); /** @hidden */ Animation._UniversalLerp = function (left, right, amount) { var constructor = left.constructor; if (constructor.Lerp) { // Lerp supported return constructor.Lerp(left, right, amount); } else if (constructor.Slerp) { // Slerp supported return constructor.Slerp(left, right, amount); } else if (left.toFixed) { // Number return left * (1.0 - amount) + amount * right; } else { // Blending not supported return right; } }; /** * Parses an animation object and creates an animation * @param parsedAnimation Parsed animation object * @returns Animation object */ Animation.Parse = function (parsedAnimation) { var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior); var dataType = parsedAnimation.dataType; var keys = []; var data; var index; if (parsedAnimation.enableBlending) { animation.enableBlending = parsedAnimation.enableBlending; } if (parsedAnimation.blendingSpeed) { animation.blendingSpeed = parsedAnimation.blendingSpeed; } for (index = 0; index < parsedAnimation.keys.length; index++) { var key = parsedAnimation.keys[index]; var inTangent; var outTangent; switch (dataType) { case Animation.ANIMATIONTYPE_FLOAT: data = key.values[0]; if (key.values.length >= 1) { inTangent = key.values[1]; } if (key.values.length >= 2) { outTangent = key.values[2]; } break; case Animation.ANIMATIONTYPE_QUATERNION: data = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray(key.values); if (key.values.length >= 8) { var _inTangent = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray(key.values.slice(4, 8)); if (!_inTangent.equals(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Zero())) { inTangent = _inTangent; } } if (key.values.length >= 12) { var _outTangent = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray(key.values.slice(8, 12)); if (!_outTangent.equals(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Zero())) { outTangent = _outTangent; } } break; case Animation.ANIMATIONTYPE_MATRIX: data = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].FromArray(key.values); break; case Animation.ANIMATIONTYPE_COLOR3: data = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].FromArray(key.values); break; case Animation.ANIMATIONTYPE_VECTOR3: default: data = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(key.values); break; } var keyData = {}; keyData.frame = key.frame; keyData.value = data; if (inTangent != undefined) { keyData.inTangent = inTangent; } if (outTangent != undefined) { keyData.outTangent = outTangent; } keys.push(keyData); } animation.setKeys(keys); if (parsedAnimation.ranges) { for (index = 0; index < parsedAnimation.ranges.length; index++) { data = parsedAnimation.ranges[index]; animation.createRange(data.name, data.from, data.to); } } return animation; }; /** * Appends the serialized animations from the source animations * @param source Source containing the animations * @param destination Target to store the animations */ Animation.AppendSerializedAnimations = function (source, destination) { _Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["SerializationHelper"].AppendSerializedAnimations(source, destination); }; /** * Use matrix interpolation instead of using direct key value when animating matrices */ Animation.AllowMatricesInterpolation = false; /** * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower */ Animation.AllowMatrixDecomposeForInterpolation = true; // Statics /** * Float animation type */ Animation._ANIMATIONTYPE_FLOAT = 0; /** * Vector3 animation type */ Animation._ANIMATIONTYPE_VECTOR3 = 1; /** * Quaternion animation type */ Animation._ANIMATIONTYPE_QUATERNION = 2; /** * Matrix animation type */ Animation._ANIMATIONTYPE_MATRIX = 3; /** * Color3 animation type */ Animation._ANIMATIONTYPE_COLOR3 = 4; /** * Vector2 animation type */ Animation._ANIMATIONTYPE_VECTOR2 = 5; /** * Size animation type */ Animation._ANIMATIONTYPE_SIZE = 6; /** * Relative Loop Mode */ Animation._ANIMATIONLOOPMODE_RELATIVE = 0; /** * Cycle Loop Mode */ Animation._ANIMATIONLOOPMODE_CYCLE = 1; /** * Constant Loop Mode */ Animation._ANIMATIONLOOPMODE_CONSTANT = 2; return Animation; }()); _Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__["_TypeStore"].RegisteredTypes["BABYLON.Animation"] = Animation; _node__WEBPACK_IMPORTED_MODULE_6__["Node"]._AnimationRangeFactory = function (name, from, to) { return new _animationRange__WEBPACK_IMPORTED_MODULE_5__["AnimationRange"](name, from, to); }; /***/ }), /***/ "./Animations/animationEvent.ts": /*!**************************************!*\ !*** ./Animations/animationEvent.ts ***! \**************************************/ /*! exports provided: AnimationEvent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationEvent", function() { return AnimationEvent; }); /** * Composed of a frame, and an action function */ var AnimationEvent = /** @class */ (function () { /** * Initializes the animation event * @param frame The frame for which the event is triggered * @param action The event to perform when triggered * @param onlyOnce Specifies if the event should be triggered only once */ function AnimationEvent( /** The frame for which the event is triggered **/ frame, /** The event to perform when triggered **/ action, /** Specifies if the event should be triggered only once**/ onlyOnce) { this.frame = frame; this.action = action; this.onlyOnce = onlyOnce; /** * Specifies if the animation event is done */ this.isDone = false; } /** @hidden */ AnimationEvent.prototype._clone = function () { return new AnimationEvent(this.frame, this.action, this.onlyOnce); }; return AnimationEvent; }()); /***/ }), /***/ "./Animations/animationGroup.ts": /*!**************************************!*\ !*** ./Animations/animationGroup.ts ***! \**************************************/ /*! exports provided: TargetedAnimation, AnimationGroup */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TargetedAnimation", function() { return TargetedAnimation; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationGroup", function() { return AnimationGroup; }); /* harmony import */ var _animation__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./animation */ "./Animations/animation.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts"); /** * This class defines the direct association between an animation and a target */ var TargetedAnimation = /** @class */ (function () { function TargetedAnimation() { } return TargetedAnimation; }()); /** * Use this class to create coordinated animations on multiple targets */ var AnimationGroup = /** @class */ (function () { /** * Instantiates a new Animation Group. * This helps managing several animations at once. * @see http://doc.babylonjs.com/how_to/group * @param name Defines the name of the group * @param scene Defines the scene the group belongs to */ function AnimationGroup( /** The name of the animation group */ name, scene) { if (scene === void 0) { scene = null; } this.name = name; this._targetedAnimations = new Array(); this._animatables = new Array(); this._from = Number.MAX_VALUE; this._to = -Number.MAX_VALUE; this._speedRatio = 1; /** * This observable will notify when one animation have ended */ this.onAnimationEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Observer raised when one animation loops */ this.onAnimationLoopObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * This observable will notify when all animations have ended. */ this.onAnimationGroupEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * This observable will notify when all animations have paused. */ this.onAnimationGroupPauseObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * This observable will notify when all animations are playing. */ this.onAnimationGroupPlayObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); this._scene = scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_2__["EngineStore"].LastCreatedScene; this.uniqueId = this._scene.getUniqueId(); this._scene.animationGroups.push(this); } Object.defineProperty(AnimationGroup.prototype, "from", { /** * Gets the first frame */ get: function () { return this._from; }, enumerable: true, configurable: true }); Object.defineProperty(AnimationGroup.prototype, "to", { /** * Gets the last frame */ get: function () { return this._to; }, enumerable: true, configurable: true }); Object.defineProperty(AnimationGroup.prototype, "isStarted", { /** * Define if the animations are started */ get: function () { return this._isStarted; }, enumerable: true, configurable: true }); Object.defineProperty(AnimationGroup.prototype, "isPlaying", { /** * Gets a value indicating that the current group is playing */ get: function () { return this._isStarted && !this._isPaused; }, enumerable: true, configurable: true }); Object.defineProperty(AnimationGroup.prototype, "speedRatio", { /** * Gets or sets the speed ratio to use for all animations */ get: function () { return this._speedRatio; }, /** * Gets or sets the speed ratio to use for all animations */ set: function (value) { if (this._speedRatio === value) { return; } this._speedRatio = value; for (var index = 0; index < this._animatables.length; index++) { var animatable = this._animatables[index]; animatable.speedRatio = this._speedRatio; } }, enumerable: true, configurable: true }); Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", { /** * Gets the targeted animations for this animation group */ get: function () { return this._targetedAnimations; }, enumerable: true, configurable: true }); Object.defineProperty(AnimationGroup.prototype, "animatables", { /** * returning the list of animatables controlled by this animation group. */ get: function () { return this._animatables; }, enumerable: true, configurable: true }); /** * Add an animation (with its target) in the group * @param animation defines the animation we want to add * @param target defines the target of the animation * @returns the TargetedAnimation object */ AnimationGroup.prototype.addTargetedAnimation = function (animation, target) { var targetedAnimation = { animation: animation, target: target }; var keys = animation.getKeys(); if (this._from > keys[0].frame) { this._from = keys[0].frame; } if (this._to < keys[keys.length - 1].frame) { this._to = keys[keys.length - 1].frame; } this._targetedAnimations.push(targetedAnimation); return targetedAnimation; }; /** * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame * It can add constant keys at begin or end * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null) * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null) * @returns the animation group */ AnimationGroup.prototype.normalize = function (beginFrame, endFrame) { if (beginFrame === void 0) { beginFrame = null; } if (endFrame === void 0) { endFrame = null; } if (beginFrame == null) { beginFrame = this._from; } if (endFrame == null) { endFrame = this._to; } for (var index = 0; index < this._targetedAnimations.length; index++) { var targetedAnimation = this._targetedAnimations[index]; var keys = targetedAnimation.animation.getKeys(); var startKey = keys[0]; var endKey = keys[keys.length - 1]; if (startKey.frame > beginFrame) { var newKey = { frame: beginFrame, value: startKey.value, inTangent: startKey.inTangent, outTangent: startKey.outTangent, interpolation: startKey.interpolation }; keys.splice(0, 0, newKey); } if (endKey.frame < endFrame) { var newKey = { frame: endFrame, value: endKey.value, inTangent: endKey.outTangent, outTangent: endKey.outTangent, interpolation: endKey.interpolation }; keys.push(newKey); } } this._from = beginFrame; this._to = endFrame; return this; }; /** * Start all animations on given targets * @param loop defines if animations must loop * @param speedRatio defines the ratio to apply to animation speed (1 by default) * @param from defines the from key (optional) * @param to defines the to key (optional) * @returns the current animation group */ AnimationGroup.prototype.start = function (loop, speedRatio, from, to) { var _this = this; if (loop === void 0) { loop = false; } if (speedRatio === void 0) { speedRatio = 1; } if (this._isStarted || this._targetedAnimations.length === 0) { return this; } var _loop_1 = function (targetedAnimation) { var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio); animatable.onAnimationEnd = function () { _this.onAnimationEndObservable.notifyObservers(targetedAnimation); _this._checkAnimationGroupEnded(animatable); }; animatable.onAnimationLoop = function () { _this.onAnimationLoopObservable.notifyObservers(targetedAnimation); }; this_1._animatables.push(animatable); }; var this_1 = this; for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) { var targetedAnimation = _a[_i]; _loop_1(targetedAnimation); } this._speedRatio = speedRatio; if (from !== undefined && to !== undefined && from > to && this._speedRatio > 0) { this._speedRatio = -speedRatio; } this._isStarted = true; this._isPaused = false; this.onAnimationGroupPlayObservable.notifyObservers(this); return this; }; /** * Pause all animations * @returns the animation group */ AnimationGroup.prototype.pause = function () { if (!this._isStarted) { return this; } this._isPaused = true; for (var index = 0; index < this._animatables.length; index++) { var animatable = this._animatables[index]; animatable.pause(); } this.onAnimationGroupPauseObservable.notifyObservers(this); return this; }; /** * Play all animations to initial state * This function will start() the animations if they were not started or will restart() them if they were paused * @param loop defines if animations must loop * @returns the animation group */ AnimationGroup.prototype.play = function (loop) { // only if all animatables are ready and exist if (this.isStarted && this._animatables.length === this._targetedAnimations.length) { if (loop !== undefined) { for (var index = 0; index < this._animatables.length; index++) { var animatable = this._animatables[index]; animatable.loopAnimation = loop; } } this.restart(); } else { this.stop(); this.start(loop, this._speedRatio); } this._isPaused = false; return this; }; /** * Reset all animations to initial state * @returns the animation group */ AnimationGroup.prototype.reset = function () { if (!this._isStarted) { return this; } for (var index = 0; index < this._animatables.length; index++) { var animatable = this._animatables[index]; animatable.reset(); } return this; }; /** * Restart animations from key 0 * @returns the animation group */ AnimationGroup.prototype.restart = function () { if (!this._isStarted) { return this; } for (var index = 0; index < this._animatables.length; index++) { var animatable = this._animatables[index]; animatable.restart(); } this.onAnimationGroupPlayObservable.notifyObservers(this); return this; }; /** * Stop all animations * @returns the animation group */ AnimationGroup.prototype.stop = function () { if (!this._isStarted) { return this; } var list = this._animatables.slice(); for (var index = 0; index < list.length; index++) { list[index].stop(); } this._isStarted = false; return this; }; /** * Set animation weight for all animatables * @param weight defines the weight to use * @return the animationGroup * @see http://doc.babylonjs.com/babylon101/animations#animation-weights */ AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) { for (var index = 0; index < this._animatables.length; index++) { var animatable = this._animatables[index]; animatable.weight = weight; } return this; }; /** * Synchronize and normalize all animatables with a source animatable * @param root defines the root animatable to synchronize with * @return the animationGroup * @see http://doc.babylonjs.com/babylon101/animations#animation-weights */ AnimationGroup.prototype.syncAllAnimationsWith = function (root) { for (var index = 0; index < this._animatables.length; index++) { var animatable = this._animatables[index]; animatable.syncWith(root); } return this; }; /** * Goes to a specific frame in this animation group * @param frame the frame number to go to * @return the animationGroup */ AnimationGroup.prototype.goToFrame = function (frame) { if (!this._isStarted) { return this; } for (var index = 0; index < this._animatables.length; index++) { var animatable = this._animatables[index]; animatable.goToFrame(frame); } return this; }; /** * Dispose all associated resources */ AnimationGroup.prototype.dispose = function () { this._targetedAnimations = []; this._animatables = []; var index = this._scene.animationGroups.indexOf(this); if (index > -1) { this._scene.animationGroups.splice(index, 1); } this.onAnimationEndObservable.clear(); this.onAnimationGroupEndObservable.clear(); this.onAnimationGroupPauseObservable.clear(); this.onAnimationGroupPlayObservable.clear(); this.onAnimationLoopObservable.clear(); }; AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) { // animatable should be taken out of the array var idx = this._animatables.indexOf(animatable); if (idx > -1) { this._animatables.splice(idx, 1); } // all animatables were removed? animation group ended! if (this._animatables.length === 0) { this._isStarted = false; this.onAnimationGroupEndObservable.notifyObservers(this); } }; /** * Clone the current animation group and returns a copy * @param newName defines the name of the new group * @param targetConverter defines an optional function used to convert current animation targets to new ones * @returns the new aniamtion group */ AnimationGroup.prototype.clone = function (newName, targetConverter) { var newGroup = new AnimationGroup(newName || this.name, this._scene); for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) { var targetAnimation = _a[_i]; newGroup.addTargetedAnimation(targetAnimation.animation.clone(), targetConverter ? targetConverter(targetAnimation.target) : targetAnimation.target); } return newGroup; }; // Statics /** * Returns a new AnimationGroup object parsed from the source provided. * @param parsedAnimationGroup defines the source * @param scene defines the scene that will receive the animationGroup * @returns a new AnimationGroup */ AnimationGroup.Parse = function (parsedAnimationGroup, scene) { var animationGroup = new AnimationGroup(parsedAnimationGroup.name, scene); for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) { var targetedAnimation = parsedAnimationGroup.targetedAnimations[i]; var animation = _animation__WEBPACK_IMPORTED_MODULE_0__["Animation"].Parse(targetedAnimation.animation); var id = targetedAnimation.targetId; if (targetedAnimation.animation.property === "influence") { // morph target animation var morphTarget = scene.getMorphTargetById(id); if (morphTarget) { animationGroup.addTargetedAnimation(animation, morphTarget); } } else { var targetNode = scene.getNodeByID(id); if (targetNode != null) { animationGroup.addTargetedAnimation(animation, targetNode); } } } if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null) { animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to); } return animationGroup; }; /** * Returns the string "AnimationGroup" * @returns "AnimationGroup" */ AnimationGroup.prototype.getClassName = function () { return "AnimationGroup"; }; /** * Creates a detailled string about the object * @param fullDetails defines if the output string will support multiple levels of logging within scene loading * @returns a string representing the object */ AnimationGroup.prototype.toString = function (fullDetails) { var ret = "Name: " + this.name; ret += ", type: " + this.getClassName(); if (fullDetails) { ret += ", from: " + this._from; ret += ", to: " + this._to; ret += ", isStarted: " + this._isStarted; ret += ", speedRatio: " + this._speedRatio; ret += ", targetedAnimations length: " + this._targetedAnimations.length; ret += ", animatables length: " + this._animatables; } return ret; }; return AnimationGroup; }()); /***/ }), /***/ "./Animations/animationKey.ts": /*!************************************!*\ !*** ./Animations/animationKey.ts ***! \************************************/ /*! exports provided: AnimationKeyInterpolation */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationKeyInterpolation", function() { return AnimationKeyInterpolation; }); /** * Enum for the animation key frame interpolation type */ var AnimationKeyInterpolation; (function (AnimationKeyInterpolation) { /** * Do not interpolate between keys and use the start key value only. Tangents are ignored */ AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP"; })(AnimationKeyInterpolation || (AnimationKeyInterpolation = {})); /***/ }), /***/ "./Animations/animationPropertiesOverride.ts": /*!***************************************************!*\ !*** ./Animations/animationPropertiesOverride.ts ***! \***************************************************/ /*! exports provided: AnimationPropertiesOverride */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationPropertiesOverride", function() { return AnimationPropertiesOverride; }); /* harmony import */ var _Animations_animation__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Animations/animation */ "./Animations/animation.ts"); /** * Class used to override all child animations of a given target */ var AnimationPropertiesOverride = /** @class */ (function () { function AnimationPropertiesOverride() { /** * Gets or sets a value indicating if animation blending must be used */ this.enableBlending = false; /** * Gets or sets the blending speed to use when enableBlending is true */ this.blendingSpeed = 0.01; /** * Gets or sets the default loop mode to use */ this.loopMode = _Animations_animation__WEBPACK_IMPORTED_MODULE_0__["Animation"].ANIMATIONLOOPMODE_CYCLE; } return AnimationPropertiesOverride; }()); /***/ }), /***/ "./Animations/animationRange.ts": /*!**************************************!*\ !*** ./Animations/animationRange.ts ***! \**************************************/ /*! exports provided: AnimationRange */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationRange", function() { return AnimationRange; }); /** * Represents the range of an animation */ var AnimationRange = /** @class */ (function () { /** * Initializes the range of an animation * @param name The name of the animation range * @param from The starting frame of the animation * @param to The ending frame of the animation */ function AnimationRange( /**The name of the animation range**/ name, /**The starting frame of the animation */ from, /**The ending frame of the animation*/ to) { this.name = name; this.from = from; this.to = to; } /** * Makes a copy of the animation range * @returns A copy of the animation range */ AnimationRange.prototype.clone = function () { return new AnimationRange(this.name, this.from, this.to); }; return AnimationRange; }()); /***/ }), /***/ "./Animations/easing.ts": /*!******************************!*\ !*** ./Animations/easing.ts ***! \******************************/ /*! exports provided: EasingFunction, CircleEase, BackEase, BounceEase, CubicEase, ElasticEase, ExponentialEase, PowerEase, QuadraticEase, QuarticEase, QuinticEase, SineEase, BezierCurveEase */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EasingFunction", function() { return EasingFunction; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CircleEase", function() { return CircleEase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BackEase", function() { return BackEase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BounceEase", function() { return BounceEase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CubicEase", function() { return CubicEase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ElasticEase", function() { return ElasticEase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ExponentialEase", function() { return ExponentialEase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PowerEase", function() { return PowerEase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QuadraticEase", function() { return QuadraticEase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QuarticEase", function() { return QuarticEase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QuinticEase", function() { return QuinticEase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SineEase", function() { return SineEase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BezierCurveEase", function() { return BezierCurveEase; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /** * Base class used for every default easing function. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions */ var EasingFunction = /** @class */ (function () { function EasingFunction() { this._easingMode = EasingFunction.EASINGMODE_EASEIN; } /** * Sets the easing mode of the current function. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT) */ EasingFunction.prototype.setEasingMode = function (easingMode) { var n = Math.min(Math.max(easingMode, 0), 2); this._easingMode = n; }; /** * Gets the current easing mode. * @returns the easing mode */ EasingFunction.prototype.getEasingMode = function () { return this._easingMode; }; /** * @hidden */ EasingFunction.prototype.easeInCore = function (gradient) { throw new Error('You must implement this method'); }; /** * Given an input gradient between 0 and 1, this returns the corrseponding value * of the easing function. * @param gradient Defines the value between 0 and 1 we want the easing value for * @returns the corresponding value on the curve defined by the easing function */ EasingFunction.prototype.ease = function (gradient) { switch (this._easingMode) { case EasingFunction.EASINGMODE_EASEIN: return this.easeInCore(gradient); case EasingFunction.EASINGMODE_EASEOUT: return (1 - this.easeInCore(1 - gradient)); } if (gradient >= 0.5) { return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5); } return (this.easeInCore(gradient * 2) * 0.5); }; /** * Interpolation follows the mathematical formula associated with the easing function. */ EasingFunction.EASINGMODE_EASEIN = 0; /** * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function. */ EasingFunction.EASINGMODE_EASEOUT = 1; /** * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half. */ EasingFunction.EASINGMODE_EASEINOUT = 2; return EasingFunction; }()); /** * Easing function with a circle shape (see link below). * @see https://easings.net/#easeInCirc * @see http://doc.babylonjs.com/babylon101/animations#easing-functions */ var CircleEase = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](CircleEase, _super); function CircleEase() { return _super !== null && _super.apply(this, arguments) || this; } /** @hidden */ CircleEase.prototype.easeInCore = function (gradient) { gradient = Math.max(0, Math.min(1, gradient)); return (1.0 - Math.sqrt(1.0 - (gradient * gradient))); }; return CircleEase; }(EasingFunction)); /** * Easing function with a ease back shape (see link below). * @see https://easings.net/#easeInBack * @see http://doc.babylonjs.com/babylon101/animations#easing-functions */ var BackEase = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BackEase, _super); /** * Instantiates a back ease easing * @see https://easings.net/#easeInBack * @param amplitude Defines the amplitude of the function */ function BackEase( /** Defines the amplitude of the function */ amplitude) { if (amplitude === void 0) { amplitude = 1; } var _this = _super.call(this) || this; _this.amplitude = amplitude; return _this; } /** @hidden */ BackEase.prototype.easeInCore = function (gradient) { var num = Math.max(0, this.amplitude); return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient))); }; return BackEase; }(EasingFunction)); /** * Easing function with a bouncing shape (see link below). * @see https://easings.net/#easeInBounce * @see http://doc.babylonjs.com/babylon101/animations#easing-functions */ var BounceEase = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BounceEase, _super); /** * Instantiates a bounce easing * @see https://easings.net/#easeInBounce * @param bounces Defines the number of bounces * @param bounciness Defines the amplitude of the bounce */ function BounceEase( /** Defines the number of bounces */ bounces, /** Defines the amplitude of the bounce */ bounciness) { if (bounces === void 0) { bounces = 3; } if (bounciness === void 0) { bounciness = 2; } var _this = _super.call(this) || this; _this.bounces = bounces; _this.bounciness = bounciness; return _this; } /** @hidden */ BounceEase.prototype.easeInCore = function (gradient) { var y = Math.max(0.0, this.bounces); var bounciness = this.bounciness; if (bounciness <= 1.0) { bounciness = 1.001; } var num9 = Math.pow(bounciness, y); var num5 = 1.0 - bounciness; var num4 = ((1.0 - num9) / num5) + (num9 * 0.5); var num15 = gradient * num4; var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness); var num3 = Math.floor(num65); var num13 = num3 + 1.0; var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4); var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4); var num7 = (num8 + num12) * 0.5; var num6 = gradient - num7; var num2 = num7 - num8; return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2)); }; return BounceEase; }(EasingFunction)); /** * Easing function with a power of 3 shape (see link below). * @see https://easings.net/#easeInCubic * @see http://doc.babylonjs.com/babylon101/animations#easing-functions */ var CubicEase = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](CubicEase, _super); function CubicEase() { return _super !== null && _super.apply(this, arguments) || this; } /** @hidden */ CubicEase.prototype.easeInCore = function (gradient) { return (gradient * gradient * gradient); }; return CubicEase; }(EasingFunction)); /** * Easing function with an elastic shape (see link below). * @see https://easings.net/#easeInElastic * @see http://doc.babylonjs.com/babylon101/animations#easing-functions */ var ElasticEase = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ElasticEase, _super); /** * Instantiates an elastic easing function * @see https://easings.net/#easeInElastic * @param oscillations Defines the number of oscillations * @param springiness Defines the amplitude of the oscillations */ function ElasticEase( /** Defines the number of oscillations*/ oscillations, /** Defines the amplitude of the oscillations*/ springiness) { if (oscillations === void 0) { oscillations = 3; } if (springiness === void 0) { springiness = 3; } var _this = _super.call(this) || this; _this.oscillations = oscillations; _this.springiness = springiness; return _this; } /** @hidden */ ElasticEase.prototype.easeInCore = function (gradient) { var num2; var num3 = Math.max(0.0, this.oscillations); var num = Math.max(0.0, this.springiness); if (num == 0) { num2 = gradient; } else { num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0); } return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient)); }; return ElasticEase; }(EasingFunction)); /** * Easing function with an exponential shape (see link below). * @see https://easings.net/#easeInExpo * @see http://doc.babylonjs.com/babylon101/animations#easing-functions */ var ExponentialEase = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ExponentialEase, _super); /** * Instantiates an exponential easing function * @see https://easings.net/#easeInExpo * @param exponent Defines the exponent of the function */ function ExponentialEase( /** Defines the exponent of the function */ exponent) { if (exponent === void 0) { exponent = 2; } var _this = _super.call(this) || this; _this.exponent = exponent; return _this; } /** @hidden */ ExponentialEase.prototype.easeInCore = function (gradient) { if (this.exponent <= 0) { return gradient; } return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0)); }; return ExponentialEase; }(EasingFunction)); /** * Easing function with a power shape (see link below). * @see https://easings.net/#easeInQuad * @see http://doc.babylonjs.com/babylon101/animations#easing-functions */ var PowerEase = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PowerEase, _super); /** * Instantiates an power base easing function * @see https://easings.net/#easeInQuad * @param power Defines the power of the function */ function PowerEase( /** Defines the power of the function */ power) { if (power === void 0) { power = 2; } var _this = _super.call(this) || this; _this.power = power; return _this; } /** @hidden */ PowerEase.prototype.easeInCore = function (gradient) { var y = Math.max(0.0, this.power); return Math.pow(gradient, y); }; return PowerEase; }(EasingFunction)); /** * Easing function with a power of 2 shape (see link below). * @see https://easings.net/#easeInQuad * @see http://doc.babylonjs.com/babylon101/animations#easing-functions */ var QuadraticEase = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](QuadraticEase, _super); function QuadraticEase() { return _super !== null && _super.apply(this, arguments) || this; } /** @hidden */ QuadraticEase.prototype.easeInCore = function (gradient) { return (gradient * gradient); }; return QuadraticEase; }(EasingFunction)); /** * Easing function with a power of 4 shape (see link below). * @see https://easings.net/#easeInQuart * @see http://doc.babylonjs.com/babylon101/animations#easing-functions */ var QuarticEase = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](QuarticEase, _super); function QuarticEase() { return _super !== null && _super.apply(this, arguments) || this; } /** @hidden */ QuarticEase.prototype.easeInCore = function (gradient) { return (gradient * gradient * gradient * gradient); }; return QuarticEase; }(EasingFunction)); /** * Easing function with a power of 5 shape (see link below). * @see https://easings.net/#easeInQuint * @see http://doc.babylonjs.com/babylon101/animations#easing-functions */ var QuinticEase = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](QuinticEase, _super); function QuinticEase() { return _super !== null && _super.apply(this, arguments) || this; } /** @hidden */ QuinticEase.prototype.easeInCore = function (gradient) { return (gradient * gradient * gradient * gradient * gradient); }; return QuinticEase; }(EasingFunction)); /** * Easing function with a sin shape (see link below). * @see https://easings.net/#easeInSine * @see http://doc.babylonjs.com/babylon101/animations#easing-functions */ var SineEase = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SineEase, _super); function SineEase() { return _super !== null && _super.apply(this, arguments) || this; } /** @hidden */ SineEase.prototype.easeInCore = function (gradient) { return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient))); }; return SineEase; }(EasingFunction)); /** * Easing function with a bezier shape (see link below). * @see http://cubic-bezier.com/#.17,.67,.83,.67 * @see http://doc.babylonjs.com/babylon101/animations#easing-functions */ var BezierCurveEase = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BezierCurveEase, _super); /** * Instantiates a bezier function * @see http://cubic-bezier.com/#.17,.67,.83,.67 * @param x1 Defines the x component of the start tangent in the bezier curve * @param y1 Defines the y component of the start tangent in the bezier curve * @param x2 Defines the x component of the end tangent in the bezier curve * @param y2 Defines the y component of the end tangent in the bezier curve */ function BezierCurveEase( /** Defines the x component of the start tangent in the bezier curve */ x1, /** Defines the y component of the start tangent in the bezier curve */ y1, /** Defines the x component of the end tangent in the bezier curve */ x2, /** Defines the y component of the end tangent in the bezier curve */ y2) { if (x1 === void 0) { x1 = 0; } if (y1 === void 0) { y1 = 0; } if (x2 === void 0) { x2 = 1; } if (y2 === void 0) { y2 = 1; } var _this = _super.call(this) || this; _this.x1 = x1; _this.y1 = y1; _this.x2 = x2; _this.y2 = y2; return _this; } /** @hidden */ BezierCurveEase.prototype.easeInCore = function (gradient) { return _Maths_math__WEBPACK_IMPORTED_MODULE_1__["BezierCurve"].Interpolate(gradient, this.x1, this.y1, this.x2, this.y2); }; return BezierCurveEase; }(EasingFunction)); /***/ }), /***/ "./Animations/index.ts": /*!*****************************!*\ !*** ./Animations/index.ts ***! \*****************************/ /*! exports provided: Animatable, Animation, TargetedAnimation, AnimationGroup, AnimationPropertiesOverride, EasingFunction, CircleEase, BackEase, BounceEase, CubicEase, ElasticEase, ExponentialEase, PowerEase, QuadraticEase, QuarticEase, QuinticEase, SineEase, BezierCurveEase, RuntimeAnimation, AnimationEvent, AnimationKeyInterpolation, AnimationRange */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _animatable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./animatable */ "./Animations/animatable.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Animatable", function() { return _animatable__WEBPACK_IMPORTED_MODULE_0__["Animatable"]; }); /* harmony import */ var _animation__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./animation */ "./Animations/animation.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Animation", function() { return _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"]; }); /* harmony import */ var _animationGroup__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./animationGroup */ "./Animations/animationGroup.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TargetedAnimation", function() { return _animationGroup__WEBPACK_IMPORTED_MODULE_2__["TargetedAnimation"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationGroup", function() { return _animationGroup__WEBPACK_IMPORTED_MODULE_2__["AnimationGroup"]; }); /* harmony import */ var _animationPropertiesOverride__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./animationPropertiesOverride */ "./Animations/animationPropertiesOverride.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationPropertiesOverride", function() { return _animationPropertiesOverride__WEBPACK_IMPORTED_MODULE_3__["AnimationPropertiesOverride"]; }); /* harmony import */ var _easing__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./easing */ "./Animations/easing.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EasingFunction", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["EasingFunction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CircleEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["CircleEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BackEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["BackEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BounceEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["BounceEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CubicEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["CubicEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ElasticEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["ElasticEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ExponentialEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["ExponentialEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PowerEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["PowerEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "QuadraticEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["QuadraticEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "QuarticEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["QuarticEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "QuinticEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["QuinticEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SineEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["SineEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BezierCurveEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["BezierCurveEase"]; }); /* harmony import */ var _runtimeAnimation__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./runtimeAnimation */ "./Animations/runtimeAnimation.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RuntimeAnimation", function() { return _runtimeAnimation__WEBPACK_IMPORTED_MODULE_5__["RuntimeAnimation"]; }); /* harmony import */ var _animationEvent__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./animationEvent */ "./Animations/animationEvent.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationEvent", function() { return _animationEvent__WEBPACK_IMPORTED_MODULE_6__["AnimationEvent"]; }); /* empty/unused harmony star reexport *//* harmony import */ var _animationKey__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./animationKey */ "./Animations/animationKey.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationKeyInterpolation", function() { return _animationKey__WEBPACK_IMPORTED_MODULE_7__["AnimationKeyInterpolation"]; }); /* harmony import */ var _animationRange__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./animationRange */ "./Animations/animationRange.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationRange", function() { return _animationRange__WEBPACK_IMPORTED_MODULE_8__["AnimationRange"]; }); /***/ }), /***/ "./Animations/runtimeAnimation.ts": /*!****************************************!*\ !*** ./Animations/runtimeAnimation.ts ***! \****************************************/ /*! exports provided: RuntimeAnimation */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RuntimeAnimation", function() { return RuntimeAnimation; }); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _animation__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./animation */ "./Animations/animation.ts"); // Static values to help the garbage collector // Quaternion var _staticOffsetValueQuaternion = Object.freeze(new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"](0, 0, 0, 0)); // Vector3 var _staticOffsetValueVector3 = Object.freeze(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero()); // Vector2 var _staticOffsetValueVector2 = Object.freeze(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"].Zero()); // Size var _staticOffsetValueSize = Object.freeze(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Size"].Zero()); // Color3 var _staticOffsetValueColor3 = Object.freeze(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].Black()); /** * Defines a runtime animation */ var RuntimeAnimation = /** @class */ (function () { /** * Create a new RuntimeAnimation object * @param target defines the target of the animation * @param animation defines the source animation object * @param scene defines the hosting scene * @param host defines the initiating Animatable */ function RuntimeAnimation(target, animation, scene, host) { var _this = this; this._events = new Array(); /** * The current frame of the runtime animation */ this._currentFrame = 0; /** * The original value of the runtime animation */ this._originalValue = new Array(); /** * The offsets cache of the runtime animation */ this._offsetsCache = {}; /** * The high limits cache of the runtime animation */ this._highLimitsCache = {}; /** * Specifies if the runtime animation has been stopped */ this._stopped = false; /** * The blending factor of the runtime animation */ this._blendingFactor = 0; /** * The target path of the runtime animation */ this._targetPath = ""; /** * The weight of the runtime animation */ this._weight = 1.0; /** * The ratio offset of the runtime animation */ this._ratioOffset = 0; /** * The previous delay of the runtime animation */ this._previousDelay = 0; /** * The previous ratio of the runtime animation */ this._previousRatio = 0; this._animation = animation; this._target = target; this._scene = scene; this._host = host; animation._runtimeAnimations.push(this); // Cloning events locally var events = animation.getEvents(); if (events && events.length > 0) { events.forEach(function (e) { _this._events.push(e._clone()); }); } this._correctLoopMode = this._getCorrectLoopMode(); this._enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending; } Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", { /** * Gets the current frame of the runtime animation */ get: function () { return this._currentFrame; }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeAnimation.prototype, "weight", { /** * Gets the weight of the runtime animation */ get: function () { return this._weight; }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeAnimation.prototype, "currentValue", { /** * Gets the current value of the runtime animation */ get: function () { return this._currentValue; }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeAnimation.prototype, "targetPath", { /** * Gets the target path of the runtime animation */ get: function () { return this._targetPath; }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeAnimation.prototype, "target", { /** * Gets the actual target of the runtime animation */ get: function () { return this._activeTarget; }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeAnimation.prototype, "animation", { /** * Gets the animation from the runtime animation */ get: function () { return this._animation; }, enumerable: true, configurable: true }); /** * Resets the runtime animation to the beginning * @param restoreOriginal defines whether to restore the target property to the original value */ RuntimeAnimation.prototype.reset = function (restoreOriginal) { if (restoreOriginal === void 0) { restoreOriginal = false; } if (restoreOriginal) { if (this._target instanceof Array) { var index = 0; for (var _i = 0, _a = this._target; _i < _a.length; _i++) { var target = _a[_i]; if (this._originalValue[index] !== undefined) { this._setValue(target, this._originalValue[index], -1); } index++; } } else { if (this._originalValue[0] !== undefined) { this._setValue(this._target, this._originalValue[0], -1); } } } this._offsetsCache = {}; this._highLimitsCache = {}; this._currentFrame = 0; this._blendingFactor = 0; this._originalValue = new Array(); // Events for (var index = 0; index < this._events.length; index++) { this._events[index].isDone = false; } }; /** * Specifies if the runtime animation is stopped * @returns Boolean specifying if the runtime animation is stopped */ RuntimeAnimation.prototype.isStopped = function () { return this._stopped; }; /** * Disposes of the runtime animation */ RuntimeAnimation.prototype.dispose = function () { var index = this._animation.runtimeAnimations.indexOf(this); if (index > -1) { this._animation.runtimeAnimations.splice(index, 1); } }; /** * Interpolates the animation from the current frame * @param currentFrame The frame to interpolate the animation to * @param repeatCount The number of times that the animation should loop * @param loopMode The type of looping mode to use * @param offsetValue Animation offset value * @param highLimitValue The high limit value * @returns The interpolated value */ RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) { this._currentFrame = currentFrame; if (this._animation.dataType === _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_MATRIX && !this._workValue) { this._workValue = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Zero(); } return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue); }; /** * Apply the interpolated value to the target * @param currentValue defines the value computed by the animation * @param weight defines the weight to apply to this value (Defaults to 1.0) */ RuntimeAnimation.prototype.setValue = function (currentValue, weight) { if (weight === void 0) { weight = 1.0; } if (this._target instanceof Array) { var index = 0; for (var _i = 0, _a = this._target; _i < _a.length; _i++) { var target = _a[_i]; this._setValue(target, currentValue, weight, index); index++; } } else { this._setValue(this._target, currentValue, weight); } }; RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) { if (targetIndex === void 0) { targetIndex = 0; } // Set value var path; var destination; if (!this._targetPath) { var targetPropertyPath = this._animation.targetPropertyPath; if (targetPropertyPath.length > 1) { var property = target[targetPropertyPath[0]]; for (var index = 1; index < targetPropertyPath.length - 1; index++) { property = property[targetPropertyPath[index]]; } path = targetPropertyPath[targetPropertyPath.length - 1]; destination = property; } else { path = targetPropertyPath[0]; destination = target; } this._targetPath = path; this._activeTarget = destination; } else { path = this._targetPath; destination = this._activeTarget; } this._weight = weight; if (this._originalValue[targetIndex] === undefined) { var originalValue = void 0; if (destination.getRestPose && path === "_matrix") { // For bones originalValue = destination.getRestPose(); } else { originalValue = destination[path]; } if (originalValue && originalValue.clone) { this._originalValue[targetIndex] = originalValue.clone(); } else { this._originalValue[targetIndex] = originalValue; } } // Blending if (this._enableBlending && this._blendingFactor <= 1.0) { if (!this._originalBlendValue) { var originalValue = destination[path]; if (originalValue.clone) { this._originalBlendValue = originalValue.clone(); } else { this._originalBlendValue = originalValue; } } if (this._originalBlendValue.m) { // Matrix if (_animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].AllowMatrixDecomposeForInterpolation) { if (this._currentValue) { _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue); } else { this._currentValue = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor); } } else { if (this._currentValue) { _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue); } else { this._currentValue = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Lerp(this._originalBlendValue, currentValue, this._blendingFactor); } } } else { this._currentValue = _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"]._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor); } var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed; this._blendingFactor += blendingSpeed; } else { this._currentValue = currentValue; } if (weight !== -1.0) { this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]); } else { destination[path] = this._currentValue; } if (target.markAsDirty) { target.markAsDirty(this._animation.targetProperty); } }; /** * Gets the loop pmode of the runtime animation * @returns Loop Mode */ RuntimeAnimation.prototype._getCorrectLoopMode = function () { if (this._target && this._target.animationPropertiesOverride) { return this._target.animationPropertiesOverride.loopMode; } return this._animation.loopMode; }; /** * Move the current animation to a given frame * @param frame defines the frame to move to */ RuntimeAnimation.prototype.goToFrame = function (frame) { var keys = this._animation.getKeys(); if (frame < keys[0].frame) { frame = keys[0].frame; } else if (frame > keys[keys.length - 1].frame) { frame = keys[keys.length - 1].frame; } var currentValue = this._interpolate(frame, 0, this._correctLoopMode); this.setValue(currentValue, -1); }; /** * @hidden Internal use only */ RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) { var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0; this._ratioOffset = this._previousRatio - newRatio; }; /** * Execute the current animation * @param delay defines the delay to add to the current frame * @param from defines the lower bound of the animation range * @param to defines the upper bound of the animation range * @param loop defines if the current animation must loop * @param speedRatio defines the current speed ratio * @param weight defines the weight of the animation (default is -1 so no weight) * @param onLoop optional callback called when animation loops * @returns a boolean indicating if the animation is running */ RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight, onLoop) { if (weight === void 0) { weight = -1.0; } var targetPropertyPath = this._animation.targetPropertyPath; if (!targetPropertyPath || targetPropertyPath.length < 1) { this._stopped = true; return false; } var returnValue = true; var keys = this._animation.getKeys(); var min = keys[0].frame; var max = keys[keys.length - 1].frame; // Add a start key at frame 0 if missing if (min !== 0) { var newKey = { frame: 0, value: keys[0].value }; keys.splice(0, 0, newKey); } // Check limits if (from < min || from > max) { from = min; } if (to < min || to > max) { to = max; } var range = to - from; var offsetValue; // Compute ratio which represents the frame delta between from and to var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset; var highLimitValue = 0; this._previousDelay = delay; this._previousRatio = ratio; if ((to > from && ratio >= range) && !loop) { // If we are out of range and not looping get back to caller returnValue = false; highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value); } else if ((from > to && ratio <= range) && !loop) { returnValue = false; highLimitValue = this._animation._getKeyValue(keys[0].value); } else { // Get max value if required if (this._correctLoopMode !== _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONLOOPMODE_CYCLE) { var keyOffset = to.toString() + from.toString(); if (!this._offsetsCache[keyOffset]) { var fromValue = this._interpolate(from, 0, _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONLOOPMODE_CYCLE); var toValue = this._interpolate(to, 0, _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONLOOPMODE_CYCLE); switch (this._animation.dataType) { // Float case _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_FLOAT: this._offsetsCache[keyOffset] = toValue - fromValue; break; // Quaternion case _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_QUATERNION: this._offsetsCache[keyOffset] = toValue.subtract(fromValue); break; // Vector3 case _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_VECTOR3: this._offsetsCache[keyOffset] = toValue.subtract(fromValue); // Vector2 case _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_VECTOR2: this._offsetsCache[keyOffset] = toValue.subtract(fromValue); // Size case _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_SIZE: this._offsetsCache[keyOffset] = toValue.subtract(fromValue); // Color3 case _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_COLOR3: this._offsetsCache[keyOffset] = toValue.subtract(fromValue); default: break; } this._highLimitsCache[keyOffset] = toValue; } highLimitValue = this._highLimitsCache[keyOffset]; offsetValue = this._offsetsCache[keyOffset]; } } if (offsetValue === undefined) { switch (this._animation.dataType) { // Float case _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_FLOAT: offsetValue = 0; break; // Quaternion case _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_QUATERNION: offsetValue = _staticOffsetValueQuaternion; break; // Vector3 case _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_VECTOR3: offsetValue = _staticOffsetValueVector3; break; // Vector2 case _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_VECTOR2: offsetValue = _staticOffsetValueVector2; break; // Size case _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_SIZE: offsetValue = _staticOffsetValueSize; break; // Color3 case _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_COLOR3: offsetValue = _staticOffsetValueColor3; } } // Compute value var currentFrame = (returnValue && range !== 0) ? from + ratio % range : to; // Need to normalize? if (this._host && this._host.syncRoot) { var syncRoot = this._host.syncRoot; var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame); currentFrame = from + (to - from) * hostNormalizedFrame; } // Reset events if looping var events = this._events; if (range > 0 && this.currentFrame > currentFrame || range < 0 && this.currentFrame < currentFrame) { if (onLoop) { onLoop(); } // Need to reset animation events for (var index = 0; index < events.length; index++) { if (!events[index].onlyOnce) { // reset event, the animation is looping events[index].isDone = false; } } } var repeatCount = range === 0 ? 0 : (ratio / range) >> 0; var currentValue = this._interpolate(currentFrame, repeatCount, this._correctLoopMode, offsetValue, highLimitValue); // Set value this.setValue(currentValue, weight); // Check events for (var index = 0; index < events.length; index++) { // Make sure current frame has passed event frame and that event frame is within the current range // Also, handle both forward and reverse animations if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) || (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) { var event = events[index]; if (!event.isDone) { // If event should be done only once, remove it. if (event.onlyOnce) { events.splice(index, 1); index--; } event.isDone = true; event.action(currentFrame); } // Don't do anything if the event has already be done. } } if (!returnValue) { this._stopped = true; } return returnValue; }; return RuntimeAnimation; }()); /***/ }), /***/ "./Audio/analyser.ts": /*!***************************!*\ !*** ./Audio/analyser.ts ***! \***************************/ /*! exports provided: Analyser */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Analyser", function() { return Analyser; }); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); /** * Class used to work with sound analyzer using fast fourier transform (FFT) * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music */ var Analyser = /** @class */ (function () { /** * Creates a new analyser * @param scene defines hosting scene */ function Analyser(scene) { /** * Gets or sets the smoothing * @ignorenaming */ this.SMOOTHING = 0.75; /** * Gets or sets the FFT table size * @ignorenaming */ this.FFT_SIZE = 512; /** * Gets or sets the bar graph amplitude * @ignorenaming */ this.BARGRAPHAMPLITUDE = 256; /** * Gets or sets the position of the debug canvas * @ignorenaming */ this.DEBUGCANVASPOS = { x: 20, y: 20 }; /** * Gets or sets the debug canvas size * @ignorenaming */ this.DEBUGCANVASSIZE = { width: 320, height: 200 }; this._scene = scene; this._audioEngine = _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine; if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) { this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser(); this._webAudioAnalyser.minDecibels = -140; this._webAudioAnalyser.maxDecibels = 0; this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount); this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount); this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount); } } /** * Get the number of data values you will have to play with for the visualization * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount * @returns a number */ Analyser.prototype.getFrequencyBinCount = function () { if (this._audioEngine.canUseWebAudio) { return this._webAudioAnalyser.frequencyBinCount; } else { return 0; } }; /** * Gets the current frequency data as a byte array * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData * @returns a Uint8Array */ Analyser.prototype.getByteFrequencyData = function () { if (this._audioEngine.canUseWebAudio) { this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING; this._webAudioAnalyser.fftSize = this.FFT_SIZE; this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs); } return this._byteFreqs; }; /** * Gets the current waveform as a byte array * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData * @returns a Uint8Array */ Analyser.prototype.getByteTimeDomainData = function () { if (this._audioEngine.canUseWebAudio) { this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING; this._webAudioAnalyser.fftSize = this.FFT_SIZE; this._webAudioAnalyser.getByteTimeDomainData(this._byteTime); } return this._byteTime; }; /** * Gets the current frequency data as a float array * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData * @returns a Float32Array */ Analyser.prototype.getFloatFrequencyData = function () { if (this._audioEngine.canUseWebAudio) { this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING; this._webAudioAnalyser.fftSize = this.FFT_SIZE; this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs); } return this._floatFreqs; }; /** * Renders the debug canvas */ Analyser.prototype.drawDebugCanvas = function () { var _this = this; if (this._audioEngine.canUseWebAudio) { if (!this._debugCanvas) { this._debugCanvas = document.createElement("canvas"); this._debugCanvas.width = this.DEBUGCANVASSIZE.width; this._debugCanvas.height = this.DEBUGCANVASSIZE.height; this._debugCanvas.style.position = "absolute"; this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px"; this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px"; this._debugCanvasContext = this._debugCanvas.getContext("2d"); document.body.appendChild(this._debugCanvas); this._registerFunc = function () { _this.drawDebugCanvas(); }; this._scene.registerBeforeRender(this._registerFunc); } if (this._registerFunc && this._debugCanvasContext) { var workingArray = this.getByteFrequencyData(); this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)'; this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height); // Draw the frequency domain chart. for (var i = 0; i < this.getFrequencyBinCount(); i++) { var value = workingArray[i]; var percent = value / this.BARGRAPHAMPLITUDE; var height = this.DEBUGCANVASSIZE.height * percent; var offset = this.DEBUGCANVASSIZE.height - height - 1; var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount(); var hue = i / this.getFrequencyBinCount() * 360; this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)'; this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height); } } } }; /** * Stops rendering the debug canvas and removes it */ Analyser.prototype.stopDebugCanvas = function () { if (this._debugCanvas) { if (this._registerFunc) { this._scene.unregisterBeforeRender(this._registerFunc); this._registerFunc = null; } document.body.removeChild(this._debugCanvas); this._debugCanvas = null; this._debugCanvasContext = null; } }; /** * Connects two audio nodes * @param inputAudioNode defines first node to connect * @param outputAudioNode defines second node to connect */ Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) { if (this._audioEngine.canUseWebAudio) { inputAudioNode.connect(this._webAudioAnalyser); this._webAudioAnalyser.connect(outputAudioNode); } }; /** * Releases all associated resources */ Analyser.prototype.dispose = function () { if (this._audioEngine.canUseWebAudio) { this._webAudioAnalyser.disconnect(); } }; return Analyser; }()); /***/ }), /***/ "./Audio/audioEngine.ts": /*!******************************!*\ !*** ./Audio/audioEngine.ts ***! \******************************/ /*! exports provided: AudioEngine */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AudioEngine", function() { return AudioEngine; }); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); // Sets the default audio engine to Babylon.js _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].AudioEngineFactory = function (hostElement) { return new AudioEngine(hostElement); }; /** * This represents the default audio engine used in babylon. * It is responsible to play, synchronize and analyse sounds throughout the application. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music */ var AudioEngine = /** @class */ (function () { /** * Instantiates a new audio engine. * * There should be only one per page as some browsers restrict the number * of audio contexts you can create. * @param hostElement defines the host element where to display the mute icon if necessary */ function AudioEngine(hostElement) { if (hostElement === void 0) { hostElement = null; } var _this = this; this._audioContext = null; this._audioContextInitialized = false; this._muteButton = null; /** * Gets whether the current host supports Web Audio and thus could create AudioContexts. */ this.canUseWebAudio = false; /** * Defines if Babylon should emit a warning if WebAudio is not supported. * @ignoreNaming */ this.WarnedWebAudioUnsupported = false; /** * Gets whether or not mp3 are supported by your browser. */ this.isMP3supported = false; /** * Gets whether or not ogg are supported by your browser. */ this.isOGGsupported = false; /** * Gets whether audio has been unlocked on the device. * Some Browsers have strong restrictions about Audio and won t autoplay unless * a user interaction has happened. */ this.unlocked = true; /** * Defines if the audio engine relies on a custom unlocked button. * In this case, the embedded button will not be displayed. */ this.useCustomUnlockedButton = false; /** * Event raised when audio has been unlocked on the browser. */ this.onAudioUnlockedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); /** * Event raised when audio has been locked on the browser. */ this.onAudioLockedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); this._tryToRun = false; this._onResize = function () { _this._moveButtonToTopLeft(); }; if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') { window.AudioContext = window.AudioContext || window.webkitAudioContext; this.canUseWebAudio = true; } var audioElem = document.createElement('audio'); this._hostElement = hostElement; try { if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) { this.isMP3supported = true; } } catch (e) { // protect error during capability check. } try { if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) { this.isOGGsupported = true; } } catch (e) { // protect error during capability check. } } Object.defineProperty(AudioEngine.prototype, "audioContext", { /** * Gets the current AudioContext if available. */ get: function () { if (!this._audioContextInitialized) { this._initializeAudioContext(); } else { if (!this.unlocked && !this._muteButton) { this._displayMuteButton(); } } return this._audioContext; }, enumerable: true, configurable: true }); /** * Flags the audio engine in Locked state. * This happens due to new browser policies preventing audio to autoplay. */ AudioEngine.prototype.lock = function () { this._triggerSuspendedState(); }; /** * Unlocks the audio engine once a user action has been done on the dom. * This is helpful to resume play once browser policies have been satisfied. */ AudioEngine.prototype.unlock = function () { this._triggerRunningState(); }; AudioEngine.prototype._resumeAudioContext = function () { var result; if (this._audioContext.resume) { result = this._audioContext.resume(); } return result || Promise.resolve(); }; AudioEngine.prototype._initializeAudioContext = function () { try { if (this.canUseWebAudio) { this._audioContext = new AudioContext(); // create a global volume gain node this.masterGain = this._audioContext.createGain(); this.masterGain.gain.value = 1; this.masterGain.connect(this._audioContext.destination); this._audioContextInitialized = true; if (this._audioContext.state === "running") { // Do not wait for the promise to unlock. this._triggerRunningState(); } } } catch (e) { this.canUseWebAudio = false; _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Error("Web Audio: " + e.message); } }; AudioEngine.prototype._triggerRunningState = function () { var _this = this; if (this._tryToRun) { return; } this._tryToRun = true; this._resumeAudioContext() .then(function () { _this._tryToRun = false; if (_this._muteButton) { _this._hideMuteButton(); } }).catch(function () { _this._tryToRun = false; _this.unlocked = false; }); // Notify users that the audio stack is unlocked/unmuted this.unlocked = true; this.onAudioUnlockedObservable.notifyObservers(this); }; AudioEngine.prototype._triggerSuspendedState = function () { this.unlocked = false; this.onAudioLockedObservable.notifyObservers(this); this._displayMuteButton(); }; AudioEngine.prototype._displayMuteButton = function () { var _this = this; if (this.useCustomUnlockedButton || this._muteButton) { return; } this._muteButton = document.createElement("BUTTON"); this._muteButton.className = "babylonUnmuteIcon"; this._muteButton.id = "babylonUnmuteIconBtn"; this._muteButton.title = "Unmute"; var css = ".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }"; var style = document.createElement('style'); style.appendChild(document.createTextNode(css)); document.getElementsByTagName('head')[0].appendChild(style); document.body.appendChild(this._muteButton); this._moveButtonToTopLeft(); this._muteButton.addEventListener('touchend', function () { _this._triggerRunningState(); }, true); this._muteButton.addEventListener('click', function () { _this._triggerRunningState(); }, true); window.addEventListener("resize", this._onResize); }; AudioEngine.prototype._moveButtonToTopLeft = function () { if (this._hostElement && this._muteButton) { this._muteButton.style.top = this._hostElement.offsetTop + 20 + "px"; this._muteButton.style.left = this._hostElement.offsetLeft + 20 + "px"; } }; AudioEngine.prototype._hideMuteButton = function () { if (this._muteButton) { document.body.removeChild(this._muteButton); this._muteButton = null; } }; /** * Destroy and release the resources associated with the audio ccontext. */ AudioEngine.prototype.dispose = function () { if (this.canUseWebAudio && this._audioContextInitialized) { if (this._connectedAnalyser && this._audioContext) { this._connectedAnalyser.stopDebugCanvas(); this._connectedAnalyser.dispose(); this.masterGain.disconnect(); this.masterGain.connect(this._audioContext.destination); this._connectedAnalyser = null; } this.masterGain.gain.value = 1; } this.WarnedWebAudioUnsupported = false; this._hideMuteButton(); window.removeEventListener("resize", this._onResize); this.onAudioUnlockedObservable.clear(); this.onAudioLockedObservable.clear(); }; /** * Gets the global volume sets on the master gain. * @returns the global volume if set or -1 otherwise */ AudioEngine.prototype.getGlobalVolume = function () { if (this.canUseWebAudio && this._audioContextInitialized) { return this.masterGain.gain.value; } else { return -1; } }; /** * Sets the global volume of your experience (sets on the master gain). * @param newVolume Defines the new global volume of the application */ AudioEngine.prototype.setGlobalVolume = function (newVolume) { if (this.canUseWebAudio && this._audioContextInitialized) { this.masterGain.gain.value = newVolume; } }; /** * Connect the audio engine to an audio analyser allowing some amazing * synchornization between the sounds/music and your visualization (VuMeter for instance). * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser * @param analyser The analyser to connect to the engine */ AudioEngine.prototype.connectToAnalyser = function (analyser) { if (this._connectedAnalyser) { this._connectedAnalyser.stopDebugCanvas(); } if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) { this._connectedAnalyser = analyser; this.masterGain.disconnect(); this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination); } }; return AudioEngine; }()); /***/ }), /***/ "./Audio/audioSceneComponent.ts": /*!**************************************!*\ !*** ./Audio/audioSceneComponent.ts ***! \**************************************/ /*! exports provided: AudioSceneComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AudioSceneComponent", function() { return AudioSceneComponent; }); /* harmony import */ var _sound__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./sound */ "./Audio/sound.ts"); /* harmony import */ var _soundTrack__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./soundTrack */ "./Audio/soundTrack.ts"); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../sceneComponent */ "./sceneComponent.ts"); /* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../scene */ "./scene.ts"); /* harmony import */ var _abstractScene__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../abstractScene */ "./abstractScene.ts"); // Adds the parser to the scene parsers. _abstractScene__WEBPACK_IMPORTED_MODULE_6__["AbstractScene"].AddParser(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO, function (parsedData, scene, container, rootUrl) { // TODO: add sound var loadedSounds = []; var loadedSound; container.sounds = container.sounds || []; if (parsedData.sounds !== undefined && parsedData.sounds !== null) { for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) { var parsedSound = parsedData.sounds[index]; if (_Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].audioEngine.canUseWebAudio) { if (!parsedSound.url) { parsedSound.url = parsedSound.name; } if (!loadedSounds[parsedSound.url]) { loadedSound = _sound__WEBPACK_IMPORTED_MODULE_0__["Sound"].Parse(parsedSound, scene, rootUrl); loadedSounds[parsedSound.url] = loadedSound; container.sounds.push(loadedSound); } else { container.sounds.push(_sound__WEBPACK_IMPORTED_MODULE_0__["Sound"].Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url])); } } else { container.sounds.push(new _sound__WEBPACK_IMPORTED_MODULE_0__["Sound"](parsedSound.name, null, scene)); } } } loadedSounds = []; }); Object.defineProperty(_scene__WEBPACK_IMPORTED_MODULE_5__["Scene"].prototype, "mainSoundTrack", { get: function () { var compo = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO); if (!compo) { compo = new AudioSceneComponent(this); this._addComponent(compo); } if (!this._mainSoundTrack) { this._mainSoundTrack = new _soundTrack__WEBPACK_IMPORTED_MODULE_1__["SoundTrack"](this, { mainTrack: true }); } return this._mainSoundTrack; }, enumerable: true, configurable: true }); _scene__WEBPACK_IMPORTED_MODULE_5__["Scene"].prototype.getSoundByName = function (name) { var index; for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) { if (this.mainSoundTrack.soundCollection[index].name === name) { return this.mainSoundTrack.soundCollection[index]; } } if (this.soundTracks) { for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) { for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) { if (this.soundTracks[sdIndex].soundCollection[index].name === name) { return this.soundTracks[sdIndex].soundCollection[index]; } } } } return null; }; Object.defineProperty(_scene__WEBPACK_IMPORTED_MODULE_5__["Scene"].prototype, "audioEnabled", { get: function () { var compo = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO); if (!compo) { compo = new AudioSceneComponent(this); this._addComponent(compo); } return compo.audioEnabled; }, set: function (value) { var compo = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO); if (!compo) { compo = new AudioSceneComponent(this); this._addComponent(compo); } if (value) { compo.enableAudio(); } else { compo.disableAudio(); } }, enumerable: true, configurable: true }); Object.defineProperty(_scene__WEBPACK_IMPORTED_MODULE_5__["Scene"].prototype, "headphone", { get: function () { var compo = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO); if (!compo) { compo = new AudioSceneComponent(this); this._addComponent(compo); } return compo.headphone; }, set: function (value) { var compo = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO); if (!compo) { compo = new AudioSceneComponent(this); this._addComponent(compo); } if (value) { compo.switchAudioModeForHeadphones(); } else { compo.switchAudioModeForNormalSpeakers(); } }, enumerable: true, configurable: true }); /** * Defines the sound scene component responsible to manage any sounds * in a given scene. */ var AudioSceneComponent = /** @class */ (function () { /** * Creates a new instance of the component for the given scene * @param scene Defines the scene to register the component in */ function AudioSceneComponent(scene) { /** * The component name helpfull to identify the component in the list of scene components. */ this.name = _sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO; this._audioEnabled = true; this._headphone = false; this.scene = scene; scene.soundTracks = new Array(); scene.sounds = new Array(); } Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", { /** * Gets whether audio is enabled or not. * Please use related enable/disable method to switch state. */ get: function () { return this._audioEnabled; }, enumerable: true, configurable: true }); Object.defineProperty(AudioSceneComponent.prototype, "headphone", { /** * Gets whether audio is outputing to headphone or not. * Please use the according Switch methods to change output. */ get: function () { return this._headphone; }, enumerable: true, configurable: true }); /** * Registers the component in a given scene */ AudioSceneComponent.prototype.register = function () { this.scene._afterRenderStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].STEP_AFTERRENDER_AUDIO, this, this._afterRender); }; /** * Rebuilds the elements related to this component in case of * context lost for instance. */ AudioSceneComponent.prototype.rebuild = function () { // Nothing to do here. (Not rendering related) }; /** * Serializes the component data to the specified json object * @param serializationObject The object to serialize to */ AudioSceneComponent.prototype.serialize = function (serializationObject) { serializationObject.sounds = []; if (this.scene.soundTracks) { for (var index = 0; index < this.scene.soundTracks.length; index++) { var soundtrack = this.scene.soundTracks[index]; for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) { serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize()); } } } }; /** * Adds all the element from the container to the scene * @param container the container holding the elements */ AudioSceneComponent.prototype.addFromContainer = function (container) { var _this = this; if (!container.sounds) { return; } container.sounds.forEach(function (sound) { sound.play(); sound.autoplay = true; _this.scene.mainSoundTrack.AddSound(sound); }); }; /** * Removes all the elements in the container from the scene * @param container contains the elements to remove * @param dispose if the removed element should be disposed (default: false) */ AudioSceneComponent.prototype.removeFromContainer = function (container, dispose) { var _this = this; if (dispose === void 0) { dispose = false; } if (!container.sounds) { return; } container.sounds.forEach(function (sound) { sound.stop(); sound.autoplay = false; _this.scene.mainSoundTrack.RemoveSound(sound); if (dispose) { sound.dispose(); } }); }; /** * Disposes the component and the associated ressources. */ AudioSceneComponent.prototype.dispose = function () { var scene = this.scene; if (scene._mainSoundTrack) { scene.mainSoundTrack.dispose(); } if (scene.soundTracks) { for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) { scene.soundTracks[scIndex].dispose(); } } }; /** * Disables audio in the associated scene. */ AudioSceneComponent.prototype.disableAudio = function () { var scene = this.scene; this._audioEnabled = false; var i; for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) { scene.mainSoundTrack.soundCollection[i].pause(); } if (scene.soundTracks) { for (i = 0; i < scene.soundTracks.length; i++) { for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) { scene.soundTracks[i].soundCollection[j].pause(); } } } }; /** * Enables audio in the associated scene. */ AudioSceneComponent.prototype.enableAudio = function () { var scene = this.scene; this._audioEnabled = true; var i; for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) { if (scene.mainSoundTrack.soundCollection[i].isPaused) { scene.mainSoundTrack.soundCollection[i].play(); } } if (scene.soundTracks) { for (i = 0; i < scene.soundTracks.length; i++) { for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) { if (scene.soundTracks[i].soundCollection[j].isPaused) { scene.soundTracks[i].soundCollection[j].play(); } } } } }; /** * Switch audio to headphone output. */ AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () { var scene = this.scene; this._headphone = true; scene.mainSoundTrack.switchPanningModelToHRTF(); if (scene.soundTracks) { for (var i = 0; i < scene.soundTracks.length; i++) { scene.soundTracks[i].switchPanningModelToHRTF(); } } }; /** * Switch audio to normal speakers. */ AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () { var scene = this.scene; this._headphone = false; scene.mainSoundTrack.switchPanningModelToEqualPower(); if (scene.soundTracks) { for (var i = 0; i < scene.soundTracks.length; i++) { scene.soundTracks[i].switchPanningModelToEqualPower(); } } }; AudioSceneComponent.prototype._afterRender = function () { var scene = this.scene; if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) { return; } var listeningCamera; var audioEngine = _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].audioEngine; if (scene.activeCameras.length > 0) { listeningCamera = scene.activeCameras[0]; } else { listeningCamera = scene.activeCamera; } if (listeningCamera && audioEngine.audioContext) { audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z); // for VR cameras if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) { listeningCamera = listeningCamera.rigCameras[0]; } var mat = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Invert(listeningCamera.getViewMatrix()); var cameraDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformNormal(new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, -1), mat); cameraDirection.normalize(); // To avoid some errors on GearVR if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) { audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0); } var i; for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) { var sound = scene.mainSoundTrack.soundCollection[i]; if (sound.useCustomAttenuation) { sound.updateDistanceFromListener(); } } if (scene.soundTracks) { for (i = 0; i < scene.soundTracks.length; i++) { for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) { sound = scene.soundTracks[i].soundCollection[j]; if (sound.useCustomAttenuation) { sound.updateDistanceFromListener(); } } } } } }; return AudioSceneComponent; }()); _sound__WEBPACK_IMPORTED_MODULE_0__["Sound"]._SceneComponentInitialization = function (scene) { var compo = scene._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO); if (!compo) { compo = new AudioSceneComponent(scene); scene._addComponent(compo); } }; /***/ }), /***/ "./Audio/index.ts": /*!************************!*\ !*** ./Audio/index.ts ***! \************************/ /*! exports provided: Analyser, AudioEngine, AudioSceneComponent, Sound, SoundTrack, WeightedSound */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _analyser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./analyser */ "./Audio/analyser.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Analyser", function() { return _analyser__WEBPACK_IMPORTED_MODULE_0__["Analyser"]; }); /* harmony import */ var _audioEngine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./audioEngine */ "./Audio/audioEngine.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AudioEngine", function() { return _audioEngine__WEBPACK_IMPORTED_MODULE_1__["AudioEngine"]; }); /* harmony import */ var _audioSceneComponent__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./audioSceneComponent */ "./Audio/audioSceneComponent.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AudioSceneComponent", function() { return _audioSceneComponent__WEBPACK_IMPORTED_MODULE_2__["AudioSceneComponent"]; }); /* harmony import */ var _sound__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./sound */ "./Audio/sound.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Sound", function() { return _sound__WEBPACK_IMPORTED_MODULE_3__["Sound"]; }); /* harmony import */ var _soundTrack__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./soundTrack */ "./Audio/soundTrack.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SoundTrack", function() { return _soundTrack__WEBPACK_IMPORTED_MODULE_4__["SoundTrack"]; }); /* harmony import */ var _weightedsound__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./weightedsound */ "./Audio/weightedsound.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WeightedSound", function() { return _weightedsound__WEBPACK_IMPORTED_MODULE_5__["WeightedSound"]; }); /***/ }), /***/ "./Audio/sound.ts": /*!************************!*\ !*** ./Audio/sound.ts ***! \************************/ /*! exports provided: Sound */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Sound", function() { return Sound; }); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Misc/devTools */ "./Misc/devTools.ts"); /** * Defines a sound that can be played in the application. * The sound can either be an ambient track or a simple sound played in reaction to a user action. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music */ var Sound = /** @class */ (function () { /** * Create a sound and attach it to a scene * @param name Name of your sound * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams * @param scene defines the scene the sound belongs to * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming */ function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) { if (readyToPlayCallback === void 0) { readyToPlayCallback = null; } var _this = this; /** * Does the sound autoplay once loaded. */ this.autoplay = false; /** * Does the sound loop after it finishes playing once. */ this.loop = false; /** * Does the sound use a custom attenuation curve to simulate the falloff * happening when the source gets further away from the camera. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function */ this.useCustomAttenuation = false; /** * Is this sound currently played. */ this.isPlaying = false; /** * Is this sound currently paused. */ this.isPaused = false; /** * Does this sound enables spatial sound. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound */ this.spatialSound = false; /** * Define the reference distance the sound should be heard perfectly. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound */ this.refDistance = 1; /** * Define the roll off factor of spatial sounds. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound */ this.rolloffFactor = 1; /** * Define the max distance the sound should be heard (intensity just became 0 at this point). * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound */ this.maxDistance = 100; /** * Define the distance attenuation model the sound will follow. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound */ this.distanceModel = "linear"; /** * Observable event when the current playing sound finishes. */ this.onEndedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); this._panningModel = "equalpower"; this._playbackRate = 1; this._streaming = false; this._startTime = 0; this._startOffset = 0; this._position = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); /** @hidden */ this._positionInEmitterSpace = false; this._localDirection = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](1, 0, 0); this._volume = 1; this._isReadyToPlay = false; this._isDirectional = false; // Used if you'd like to create a directional sound. // If not set, the sound will be omnidirectional this._coneInnerAngle = 360; this._coneOuterAngle = 360; this._coneOuterGain = 0; this._isOutputConnected = false; this._urlType = "Unknown"; this.name = name; this._scene = scene; Sound._SceneComponentInitialization(scene); this._readyToPlayCallback = readyToPlayCallback; // Default custom attenuation function is a linear attenuation this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) { if (currentDistance < maxDistance) { return currentVolume * (1 - currentDistance / maxDistance); } else { return 0; } }; if (options) { this.autoplay = options.autoplay || false; this.loop = options.loop || false; // if volume === 0, we need another way to check this option if (options.volume !== undefined) { this._volume = options.volume; } this.spatialSound = options.spatialSound || false; this.maxDistance = options.maxDistance || 100; this.useCustomAttenuation = options.useCustomAttenuation || false; this.rolloffFactor = options.rolloffFactor || 1; this.refDistance = options.refDistance || 1; this.distanceModel = options.distanceModel || "linear"; this._playbackRate = options.playbackRate || 1; this._streaming = options.streaming || false; } if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext) { this._soundGain = _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.createGain(); this._soundGain.gain.value = this._volume; this._inputAudioNode = this._soundGain; this._outputAudioNode = this._soundGain; if (this.spatialSound) { this._createSpatialParameters(); } this._scene.mainSoundTrack.AddSound(this); var validParameter = true; // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound if (urlOrArrayBuffer) { try { if (typeof (urlOrArrayBuffer) === "string") { this._urlType = "String"; } else if (urlOrArrayBuffer instanceof ArrayBuffer) { this._urlType = "ArrayBuffer"; } else if (urlOrArrayBuffer instanceof MediaStream) { this._urlType = "MediaStream"; } else if (Array.isArray(urlOrArrayBuffer)) { this._urlType = "Array"; } var urls = []; var codecSupportedFound = false; switch (this._urlType) { case "MediaStream": this._streaming = true; this._isReadyToPlay = true; this._streamingSource = _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer); if (this.autoplay) { this.play(); } if (this._readyToPlayCallback) { this._readyToPlayCallback(); } break; case "ArrayBuffer": if (urlOrArrayBuffer.byteLength > 0) { codecSupportedFound = true; this._soundLoaded(urlOrArrayBuffer); } break; case "String": urls.push(urlOrArrayBuffer); case "Array": if (urls.length === 0) { urls = urlOrArrayBuffer; } // If we found a supported format, we load it immediately and stop the loop for (var i = 0; i < urls.length; i++) { var url = urls[i]; if (url.indexOf(".mp3", url.length - 4) !== -1 && _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.isMP3supported) { codecSupportedFound = true; } if (url.indexOf(".ogg", url.length - 4) !== -1 && _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.isOGGsupported) { codecSupportedFound = true; } if (url.indexOf(".wav", url.length - 4) !== -1) { codecSupportedFound = true; } if (url.indexOf("blob:") !== -1) { codecSupportedFound = true; } if (codecSupportedFound) { // Loading sound using XHR2 if (!this._streaming) { this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true, function (exception) { if (exception) { _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("XHR " + exception.status + " error on: " + url + "."); } _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("Sound creation aborted."); _this._scene.mainSoundTrack.RemoveSound(_this); }); } // Streaming sound using HTML5 Audio tag else { this._htmlAudioElement = new Audio(url); this._htmlAudioElement.controls = false; this._htmlAudioElement.loop = this.loop; _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].SetCorsBehavior(url, this._htmlAudioElement); this._htmlAudioElement.preload = "auto"; this._htmlAudioElement.addEventListener("canplaythrough", function () { _this._isReadyToPlay = true; if (_this.autoplay) { _this.play(); } if (_this._readyToPlayCallback) { _this._readyToPlayCallback(); } }); document.body.appendChild(this._htmlAudioElement); this._htmlAudioElement.load(); } break; } } break; default: validParameter = false; break; } if (!validParameter) { _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound."); } else { if (!codecSupportedFound) { this._isReadyToPlay = true; // Simulating a ready to play event to avoid breaking code path if (this._readyToPlayCallback) { window.setTimeout(function () { if (_this._readyToPlayCallback) { _this._readyToPlayCallback(); } }, 1000); } } } } catch (ex) { _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("Unexpected error. Sound creation aborted."); this._scene.mainSoundTrack.RemoveSound(this); } } } else { // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers this._scene.mainSoundTrack.AddSound(this); if (!_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.WarnedWebAudioUnsupported) { _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("Web Audio is not supported by your browser."); _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.WarnedWebAudioUnsupported = true; } // Simulating a ready to play event to avoid breaking code for non web audio browsers if (this._readyToPlayCallback) { window.setTimeout(function () { if (_this._readyToPlayCallback) { _this._readyToPlayCallback(); } }, 1000); } } } /** * Release the sound and its associated resources */ Sound.prototype.dispose = function () { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio) { if (this.isPlaying) { this.stop(); } this._isReadyToPlay = false; if (this.soundTrackId === -1) { this._scene.mainSoundTrack.RemoveSound(this); } else if (this._scene.soundTracks) { this._scene.soundTracks[this.soundTrackId].RemoveSound(this); } if (this._soundGain) { this._soundGain.disconnect(); this._soundGain = null; } if (this._soundPanner) { this._soundPanner.disconnect(); this._soundPanner = null; } if (this._soundSource) { this._soundSource.disconnect(); this._soundSource = null; } this._audioBuffer = null; if (this._htmlAudioElement) { this._htmlAudioElement.pause(); this._htmlAudioElement.src = ""; document.body.removeChild(this._htmlAudioElement); } if (this._streamingSource) { this._streamingSource.disconnect(); } if (this._connectedTransformNode && this._registerFunc) { this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc); this._connectedTransformNode = null; } } }; /** * Gets if the sounds is ready to be played or not. * @returns true if ready, otherwise false */ Sound.prototype.isReady = function () { return this._isReadyToPlay; }; Sound.prototype._soundLoaded = function (audioData) { var _this = this; if (!_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext) { return; } _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.decodeAudioData(audioData, function (buffer) { _this._audioBuffer = buffer; _this._isReadyToPlay = true; if (_this.autoplay) { _this.play(); } if (_this._readyToPlayCallback) { _this._readyToPlayCallback(); } }, function (err) { _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); }); }; /** * Sets the data of the sound from an audiobuffer * @param audioBuffer The audioBuffer containing the data */ Sound.prototype.setAudioBuffer = function (audioBuffer) { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio) { this._audioBuffer = audioBuffer; this._isReadyToPlay = true; } }; /** * Updates the current sounds options such as maxdistance, loop... * @param options A JSON object containing values named as the object properties */ Sound.prototype.updateOptions = function (options) { if (options) { this.loop = options.loop || this.loop; this.maxDistance = options.maxDistance || this.maxDistance; this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation; this.rolloffFactor = options.rolloffFactor || this.rolloffFactor; this.refDistance = options.refDistance || this.refDistance; this.distanceModel = options.distanceModel || this.distanceModel; this._playbackRate = options.playbackRate || this._playbackRate; this._updateSpatialParameters(); if (this.isPlaying) { if (this._streaming && this._htmlAudioElement) { this._htmlAudioElement.playbackRate = this._playbackRate; } else { if (this._soundSource) { this._soundSource.playbackRate.value = this._playbackRate; } } } } }; Sound.prototype._createSpatialParameters = function () { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext) { if (this._scene.headphone) { this._panningModel = "HRTF"; } this._soundPanner = _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.createPanner(); this._updateSpatialParameters(); this._soundPanner.connect(this._outputAudioNode); this._inputAudioNode = this._soundPanner; } }; Sound.prototype._updateSpatialParameters = function () { if (this.spatialSound && this._soundPanner) { if (this.useCustomAttenuation) { // Tricks to disable in a way embedded Web Audio attenuation this._soundPanner.distanceModel = "linear"; this._soundPanner.maxDistance = Number.MAX_VALUE; this._soundPanner.refDistance = 1; this._soundPanner.rolloffFactor = 1; this._soundPanner.panningModel = this._panningModel; } else { this._soundPanner.distanceModel = this.distanceModel; this._soundPanner.maxDistance = this.maxDistance; this._soundPanner.refDistance = this.refDistance; this._soundPanner.rolloffFactor = this.rolloffFactor; this._soundPanner.panningModel = this._panningModel; } } }; /** * Switch the panning model to HRTF: * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound */ Sound.prototype.switchPanningModelToHRTF = function () { this._panningModel = "HRTF"; this._switchPanningModel(); }; /** * Switch the panning model to Equal Power: * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound */ Sound.prototype.switchPanningModelToEqualPower = function () { this._panningModel = "equalpower"; this._switchPanningModel(); }; Sound.prototype._switchPanningModel = function () { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) { this._soundPanner.panningModel = this._panningModel; } }; /** * Connect this sound to a sound track audio node like gain... * @param soundTrackAudioNode the sound track audio node to connect to */ Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio) { if (this._isOutputConnected) { this._outputAudioNode.disconnect(); } this._outputAudioNode.connect(soundTrackAudioNode); this._isOutputConnected = true; } }; /** * Transform this sound into a directional source * @param coneInnerAngle Size of the inner cone in degree * @param coneOuterAngle Size of the outer cone in degree * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0) */ Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) { if (coneOuterAngle < coneInnerAngle) { _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle."); return; } this._coneInnerAngle = coneInnerAngle; this._coneOuterAngle = coneOuterAngle; this._coneOuterGain = coneOuterGain; this._isDirectional = true; if (this.isPlaying && this.loop) { this.stop(); this.play(); } }; Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", { /** * Gets or sets the inner angle for the directional cone. */ get: function () { return this._coneInnerAngle; }, /** * Gets or sets the inner angle for the directional cone. */ set: function (value) { if (value != this._coneInnerAngle) { if (this._coneOuterAngle < value) { _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle."); return; } this._coneInnerAngle = value; if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) { this._soundPanner.coneInnerAngle = this._coneInnerAngle; } } }, enumerable: true, configurable: true }); Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", { /** * Gets or sets the outer angle for the directional cone. */ get: function () { return this._coneOuterAngle; }, /** * Gets or sets the outer angle for the directional cone. */ set: function (value) { if (value != this._coneOuterAngle) { if (value < this._coneInnerAngle) { _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle."); return; } this._coneOuterAngle = value; if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) { this._soundPanner.coneOuterAngle = this._coneOuterAngle; } } }, enumerable: true, configurable: true }); /** * Sets the position of the emitter if spatial sound is enabled * @param newPosition Defines the new posisiton */ Sound.prototype.setPosition = function (newPosition) { this._position = newPosition; if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) { this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z); } }; /** * Sets the local direction of the emitter if spatial sound is enabled * @param newLocalDirection Defines the new local direction */ Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) { this._localDirection = newLocalDirection; if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && this._connectedTransformNode && this.isPlaying) { this._updateDirection(); } }; Sound.prototype._updateDirection = function () { if (!this._connectedTransformNode || !this._soundPanner) { return; } var mat = this._connectedTransformNode.getWorldMatrix(); var direction = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformNormal(this._localDirection, mat); direction.normalize(); this._soundPanner.setOrientation(direction.x, direction.y, direction.z); }; /** @hidden */ Sound.prototype.updateDistanceFromListener = function () { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && this._connectedTransformNode && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) { var distance = this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera); this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor); } }; /** * Sets a new custom attenuation function for the sound. * @param callback Defines the function used for the attenuation * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function */ Sound.prototype.setAttenuationFunction = function (callback) { this._customAttenuationFunction = callback; }; /** * Play the sound * @param time (optional) Start the sound after X seconds. Start immediately (0) by default. * @param offset (optional) Start the sound setting it at a specific time */ Sound.prototype.play = function (time, offset) { var _this = this; if (this._isReadyToPlay && this._scene.audioEnabled && _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext) { try { if (this._startOffset < 0) { time = -this._startOffset; this._startOffset = 0; } var startTime = time ? _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime + time : _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime; if (!this._soundSource || !this._streamingSource) { if (this.spatialSound && this._soundPanner) { if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) { this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z); } if (this._isDirectional) { this._soundPanner.coneInnerAngle = this._coneInnerAngle; this._soundPanner.coneOuterAngle = this._coneOuterAngle; this._soundPanner.coneOuterGain = this._coneOuterGain; if (this._connectedTransformNode) { this._updateDirection(); } else { this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z); } } } } if (this._streaming) { if (!this._streamingSource) { this._streamingSource = _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement); this._htmlAudioElement.onended = function () { _this._onended(); }; this._htmlAudioElement.playbackRate = this._playbackRate; } this._streamingSource.disconnect(); this._streamingSource.connect(this._inputAudioNode); if (this._htmlAudioElement) { // required to manage properly the new suspended default state of Chrome // When the option 'streaming: true' is used, we need first to wait for // the audio engine to be unlocked by a user gesture before trying to play // an HTML Audio elememt var tryToPlay = function () { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.unlocked) { var playPromise = _this._htmlAudioElement.play(); // In browsers that don’t yet support this functionality, // playPromise won’t be defined. if (playPromise !== undefined) { playPromise.catch(function (error) { // Automatic playback failed. // Waiting for the audio engine to be unlocked by user click on unmute _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.lock(); if (_this.loop || _this.autoplay) { _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); }); } }); } } else { if (_this.loop || _this.autoplay) { _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); }); } } }; tryToPlay(); } } else { var tryToPlay = function () { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext) { _this._soundSource = _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.createBufferSource(); _this._soundSource.buffer = _this._audioBuffer; _this._soundSource.connect(_this._inputAudioNode); _this._soundSource.loop = _this.loop; _this._soundSource.playbackRate.value = _this._playbackRate; _this._soundSource.onended = function () { _this._onended(); }; startTime = time ? _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime + time : _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime; _this._soundSource.start(startTime, _this.isPaused ? _this._startOffset % _this._soundSource.buffer.duration : offset ? offset : 0); } }; if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.state === "suspended") { // Wait a bit for FF as context seems late to be ready. setTimeout(function () { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.state === "suspended") { // Automatic playback failed. // Waiting for the audio engine to be unlocked by user click on unmute _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.lock(); if (_this.loop || _this.autoplay) { _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); }); } } else { tryToPlay(); } }, 500); } else { tryToPlay(); } } this._startTime = startTime; this.isPlaying = true; this.isPaused = false; } catch (ex) { _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("Error while trying to play audio: " + this.name + ", " + ex.message); } } }; Sound.prototype._onended = function () { this.isPlaying = false; if (this.onended) { this.onended(); } this.onEndedObservable.notifyObservers(this); }; /** * Stop the sound * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default. */ Sound.prototype.stop = function (time) { var _this = this; if (this.isPlaying) { if (this._streaming) { if (this._htmlAudioElement) { this._htmlAudioElement.pause(); // Test needed for Firefox or it will generate an Invalid State Error if (this._htmlAudioElement.currentTime > 0) { this._htmlAudioElement.currentTime = 0; } } else { this._streamingSource.disconnect(); } this.isPlaying = false; } else if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext && this._soundSource) { var stopTime = time ? _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime + time : _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime; this._soundSource.stop(stopTime); this._soundSource.onended = function () { _this.isPlaying = false; }; if (!this.isPaused) { this._startOffset = 0; } } } }; /** * Put the sound in pause */ Sound.prototype.pause = function () { if (this.isPlaying) { this.isPaused = true; if (this._streaming) { if (this._htmlAudioElement) { this._htmlAudioElement.pause(); } else { this._streamingSource.disconnect(); } } else if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext) { this.stop(0); this._startOffset += _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime - this._startTime; } } }; /** * Sets a dedicated volume for this sounds * @param newVolume Define the new volume of the sound * @param time Define in how long the sound should be at this value */ Sound.prototype.setVolume = function (newVolume, time) { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && this._soundGain) { if (time && _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext) { this._soundGain.gain.cancelScheduledValues(_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime); this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime); this._soundGain.gain.linearRampToValueAtTime(newVolume, _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime + time); } else { this._soundGain.gain.value = newVolume; } } this._volume = newVolume; }; /** * Set the sound play back rate * @param newPlaybackRate Define the playback rate the sound should be played at */ Sound.prototype.setPlaybackRate = function (newPlaybackRate) { this._playbackRate = newPlaybackRate; if (this.isPlaying) { if (this._streaming && this._htmlAudioElement) { this._htmlAudioElement.playbackRate = this._playbackRate; } else if (this._soundSource) { this._soundSource.playbackRate.value = this._playbackRate; } } }; /** * Gets the volume of the sound. * @returns the volume of the sound */ Sound.prototype.getVolume = function () { return this._volume; }; /** * Attach the sound to a dedicated mesh * @param transformNode The transform node to connect the sound with * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh */ Sound.prototype.attachToMesh = function (transformNode) { var _this = this; if (this._connectedTransformNode && this._registerFunc) { this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc); this._registerFunc = null; } this._connectedTransformNode = transformNode; if (!this.spatialSound) { this.spatialSound = true; this._createSpatialParameters(); if (this.isPlaying && this.loop) { this.stop(); this.play(); } } this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode); this._registerFunc = function (transformNode) { return _this._onRegisterAfterWorldMatrixUpdate(transformNode); }; this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc); }; /** * Detach the sound from the previously attached mesh * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh */ Sound.prototype.detachFromMesh = function () { if (this._connectedTransformNode && this._registerFunc) { this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc); this._registerFunc = null; this._connectedTransformNode = null; } }; Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) { if (!node.getBoundingInfo) { return; } var mesh = node; if (this._positionInEmitterSpace) { mesh.worldMatrixFromCache.invertToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Tmp"].Matrix[0]); this.setPosition(_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Tmp"].Matrix[0].getTranslation()); } else { var boundingInfo = mesh.getBoundingInfo(); this.setPosition(boundingInfo.boundingSphere.centerWorld); } if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) { this._updateDirection(); } }; /** * Clone the current sound in the scene. * @returns the new sound clone */ Sound.prototype.clone = function () { var _this = this; if (!this._streaming) { var setBufferAndRun = function () { if (_this._isReadyToPlay) { clonedSound._audioBuffer = _this.getAudioBuffer(); clonedSound._isReadyToPlay = true; if (clonedSound.autoplay) { clonedSound.play(); } } else { window.setTimeout(setBufferAndRun, 300); } }; var currentOptions = { autoplay: this.autoplay, loop: this.loop, volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance, useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor, refDistance: this.refDistance, distanceModel: this.distanceModel }; var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions); if (this.useCustomAttenuation) { clonedSound.setAttenuationFunction(this._customAttenuationFunction); } clonedSound.setPosition(this._position); clonedSound.setPlaybackRate(this._playbackRate); setBufferAndRun(); return clonedSound; } // Can't clone a streaming sound else { return null; } }; /** * Gets the current underlying audio buffer containing the data * @returns the audio buffer */ Sound.prototype.getAudioBuffer = function () { return this._audioBuffer; }; /** * Serializes the Sound in a JSON representation * @returns the JSON representation of the sound */ Sound.prototype.serialize = function () { var serializationObject = { name: this.name, url: this.name, autoplay: this.autoplay, loop: this.loop, volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance, rolloffFactor: this.rolloffFactor, refDistance: this.refDistance, distanceModel: this.distanceModel, playbackRate: this._playbackRate, panningModel: this._panningModel, soundTrackId: this.soundTrackId }; if (this.spatialSound) { if (this._connectedTransformNode) { serializationObject.connectedMeshId = this._connectedTransformNode.id; } serializationObject.position = this._position.asArray(); serializationObject.refDistance = this.refDistance; serializationObject.distanceModel = this.distanceModel; serializationObject.isDirectional = this._isDirectional; serializationObject.localDirectionToMesh = this._localDirection.asArray(); serializationObject.coneInnerAngle = this._coneInnerAngle; serializationObject.coneOuterAngle = this._coneOuterAngle; serializationObject.coneOuterGain = this._coneOuterGain; } return serializationObject; }; /** * Parse a JSON representation of a sound to innstantiate in a given scene * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method) * @param scene Define the scene the new parsed sound should be created in * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies * @param sourceSound Define a cound place holder if do not need to instantiate a new one * @returns the newly parsed sound */ Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) { var soundName = parsedSound.name; var soundUrl; if (parsedSound.url) { soundUrl = rootUrl + parsedSound.url; } else { soundUrl = rootUrl + soundName; } var options = { autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume, spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance, rolloffFactor: parsedSound.rolloffFactor, refDistance: parsedSound.refDistance, distanceModel: parsedSound.distanceModel, playbackRate: parsedSound.playbackRate }; var newSound; if (!sourceSound) { newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options); scene._addPendingData(newSound); } else { var setBufferAndRun = function () { if (sourceSound._isReadyToPlay) { newSound._audioBuffer = sourceSound.getAudioBuffer(); newSound._isReadyToPlay = true; if (newSound.autoplay) { newSound.play(); } } else { window.setTimeout(setBufferAndRun, 300); } }; newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options); setBufferAndRun(); } if (parsedSound.position) { var soundPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].FromArray(parsedSound.position); newSound.setPosition(soundPosition); } if (parsedSound.isDirectional) { newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0); if (parsedSound.localDirectionToMesh) { var localDirectionToMesh = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].FromArray(parsedSound.localDirectionToMesh); newSound.setLocalDirectionToMesh(localDirectionToMesh); } } if (parsedSound.connectedMeshId) { var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId); if (connectedMesh) { newSound.attachToMesh(connectedMesh); } } return newSound; }; /** @hidden */ Sound._SceneComponentInitialization = function (_) { throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_5__["_DevTools"].WarnImport("AudioSceneComponent"); }; return Sound; }()); /***/ }), /***/ "./Audio/soundTrack.ts": /*!*****************************!*\ !*** ./Audio/soundTrack.ts ***! \*****************************/ /*! exports provided: SoundTrack */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SoundTrack", function() { return SoundTrack; }); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); /** * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds. * It will be also used in a future release to apply effects on a specific track. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks */ var SoundTrack = /** @class */ (function () { /** * Creates a new sound track. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks * @param scene Define the scene the sound track belongs to * @param options */ function SoundTrack(scene, options) { if (options === void 0) { options = {}; } /** * The unique identifier of the sound track in the scene. */ this.id = -1; this._isMainTrack = false; this._isInitialized = false; this._scene = scene; this.soundCollection = new Array(); this._options = options; if (!this._isMainTrack && this._scene.soundTracks) { this._scene.soundTracks.push(this); this.id = this._scene.soundTracks.length - 1; } } SoundTrack.prototype._initializeSoundTrackAudioGraph = function () { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.canUseWebAudio && _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.audioContext) { this._outputAudioNode = _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.audioContext.createGain(); this._outputAudioNode.connect(_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.masterGain); if (this._options) { if (this._options.volume) { this._outputAudioNode.gain.value = this._options.volume; } if (this._options.mainTrack) { this._isMainTrack = this._options.mainTrack; } } this._isInitialized = true; } }; /** * Release the sound track and its associated resources */ SoundTrack.prototype.dispose = function () { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine && _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.canUseWebAudio) { if (this._connectedAnalyser) { this._connectedAnalyser.stopDebugCanvas(); } while (this.soundCollection.length) { this.soundCollection[0].dispose(); } if (this._outputAudioNode) { this._outputAudioNode.disconnect(); } this._outputAudioNode = null; } }; /** * Adds a sound to this sound track * @param sound define the cound to add * @ignoreNaming */ SoundTrack.prototype.AddSound = function (sound) { if (!this._isInitialized) { this._initializeSoundTrackAudioGraph(); } if (_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.canUseWebAudio && this._outputAudioNode) { sound.connectToSoundTrackAudioNode(this._outputAudioNode); } if (sound.soundTrackId) { if (sound.soundTrackId === -1) { this._scene.mainSoundTrack.RemoveSound(sound); } else if (this._scene.soundTracks) { this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound); } } this.soundCollection.push(sound); sound.soundTrackId = this.id; }; /** * Removes a sound to this sound track * @param sound define the cound to remove * @ignoreNaming */ SoundTrack.prototype.RemoveSound = function (sound) { var index = this.soundCollection.indexOf(sound); if (index !== -1) { this.soundCollection.splice(index, 1); } }; /** * Set a global volume for the full sound track. * @param newVolume Define the new volume of the sound track */ SoundTrack.prototype.setVolume = function (newVolume) { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.canUseWebAudio && this._outputAudioNode) { this._outputAudioNode.gain.value = newVolume; } }; /** * Switch the panning model to HRTF: * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound */ SoundTrack.prototype.switchPanningModelToHRTF = function () { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.canUseWebAudio) { for (var i = 0; i < this.soundCollection.length; i++) { this.soundCollection[i].switchPanningModelToHRTF(); } } }; /** * Switch the panning model to Equal Power: * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound */ SoundTrack.prototype.switchPanningModelToEqualPower = function () { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.canUseWebAudio) { for (var i = 0; i < this.soundCollection.length; i++) { this.soundCollection[i].switchPanningModelToEqualPower(); } } }; /** * Connect the sound track to an audio analyser allowing some amazing * synchornization between the sounds/music and your visualization (VuMeter for instance). * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser * @param analyser The analyser to connect to the engine */ SoundTrack.prototype.connectToAnalyser = function (analyser) { if (this._connectedAnalyser) { this._connectedAnalyser.stopDebugCanvas(); } this._connectedAnalyser = analyser; if (_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.canUseWebAudio && this._outputAudioNode) { this._outputAudioNode.disconnect(); this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.masterGain); } }; return SoundTrack; }()); /***/ }), /***/ "./Audio/weightedsound.ts": /*!********************************!*\ !*** ./Audio/weightedsound.ts ***! \********************************/ /*! exports provided: WeightedSound */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WeightedSound", function() { return WeightedSound; }); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /** * Wraps one or more Sound objects and selects one with random weight for playback. */ var WeightedSound = /** @class */ (function () { /** * Creates a new WeightedSound from the list of sounds given. * @param loop When true a Sound will be selected and played when the current playing Sound completes. * @param sounds Array of Sounds that will be selected from. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1 */ function WeightedSound(loop, sounds, weights) { var _this = this; /** When true a Sound will be selected and played when the current playing Sound completes. */ this.loop = false; this._coneInnerAngle = 360; this._coneOuterAngle = 360; this._volume = 1; /** A Sound is currently playing. */ this.isPlaying = false; /** A Sound is currently paused. */ this.isPaused = false; this._sounds = []; this._weights = []; if (sounds.length !== weights.length) { throw new Error('Sounds length does not equal weights length'); } this.loop = loop; this._weights = weights; // Normalize the weights var weightSum = 0; for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) { var weight = weights_1[_i]; weightSum += weight; } var invWeightSum = weightSum > 0 ? 1 / weightSum : 0; for (var i = 0; i < this._weights.length; i++) { this._weights[i] *= invWeightSum; } this._sounds = sounds; for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) { var sound = _b[_a]; sound.onEndedObservable.add(function () { _this._onended(); }); } } Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", { /** * The size of cone in degrees for a directional sound in which there will be no attenuation. */ get: function () { return this._coneInnerAngle; }, /** * The size of cone in degress for a directional sound in which there will be no attenuation. */ set: function (value) { if (value !== this._coneInnerAngle) { if (this._coneOuterAngle < value) { _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle."); return; } this._coneInnerAngle = value; for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) { var sound = _a[_i]; sound.directionalConeInnerAngle = value; } } }, enumerable: true, configurable: true }); Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", { /** * Size of cone in degrees for a directional sound outside of which there will be no sound. * Listener angles between innerAngle and outerAngle will falloff linearly. */ get: function () { return this._coneOuterAngle; }, /** * Size of cone in degrees for a directional sound outside of which there will be no sound. * Listener angles between innerAngle and outerAngle will falloff linearly. */ set: function (value) { if (value !== this._coneOuterAngle) { if (value < this._coneInnerAngle) { _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle."); return; } this._coneOuterAngle = value; for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) { var sound = _a[_i]; sound.directionalConeOuterAngle = value; } } }, enumerable: true, configurable: true }); Object.defineProperty(WeightedSound.prototype, "volume", { /** * Playback volume. */ get: function () { return this._volume; }, /** * Playback volume. */ set: function (value) { if (value !== this._volume) { for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) { var sound = _a[_i]; sound.setVolume(value); } } }, enumerable: true, configurable: true }); WeightedSound.prototype._onended = function () { if (this._currentIndex !== undefined) { this._sounds[this._currentIndex].autoplay = false; } if (this.loop && this.isPlaying) { this.play(); } else { this.isPlaying = false; } }; /** * Suspend playback */ WeightedSound.prototype.pause = function () { this.isPaused = true; if (this._currentIndex !== undefined) { this._sounds[this._currentIndex].pause(); } }; /** * Stop playback */ WeightedSound.prototype.stop = function () { this.isPlaying = false; if (this._currentIndex !== undefined) { this._sounds[this._currentIndex].stop(); } }; /** * Start playback. * @param startOffset Position the clip head at a specific time in seconds. */ WeightedSound.prototype.play = function (startOffset) { if (!this.isPaused) { this.stop(); var randomValue = Math.random(); var total = 0; for (var i = 0; i < this._weights.length; i++) { total += this._weights[i]; if (randomValue <= total) { this._currentIndex = i; break; } } } var sound = this._sounds[this._currentIndex]; if (sound.isReady()) { sound.play(0, this.isPaused ? undefined : startOffset); } else { sound.autoplay = true; } this.isPlaying = true; this.isPaused = false; }; return WeightedSound; }()); /***/ }), /***/ "./Behaviors/Cameras/autoRotationBehavior.ts": /*!***************************************************!*\ !*** ./Behaviors/Cameras/autoRotationBehavior.ts ***! \***************************************************/ /*! exports provided: AutoRotationBehavior */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AutoRotationBehavior", function() { return AutoRotationBehavior; }); /* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); /* harmony import */ var _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/precisionDate */ "./Misc/precisionDate.ts"); /** * The autoRotation behavior (AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior */ var AutoRotationBehavior = /** @class */ (function () { function AutoRotationBehavior() { this._zoomStopsAnimation = false; this._idleRotationSpeed = 0.05; this._idleRotationWaitTime = 2000; this._idleRotationSpinupTime = 2000; this._isPointerDown = false; this._lastFrameTime = null; this._lastInteractionTime = -Infinity; this._cameraRotationSpeed = 0; this._lastFrameRadius = 0; } Object.defineProperty(AutoRotationBehavior.prototype, "name", { /** * Gets the name of the behavior. */ get: function () { return "AutoRotation"; }, enumerable: true, configurable: true }); Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", { /** * Gets the flag that indicates if user zooming should stop animation. */ get: function () { return this._zoomStopsAnimation; }, /** * Sets the flag that indicates if user zooming should stop animation. */ set: function (flag) { this._zoomStopsAnimation = flag; }, enumerable: true, configurable: true }); Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", { /** * Gets the default speed at which the camera rotates around the model. */ get: function () { return this._idleRotationSpeed; }, /** * Sets the default speed at which the camera rotates around the model. */ set: function (speed) { this._idleRotationSpeed = speed; }, enumerable: true, configurable: true }); Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", { /** * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating. */ get: function () { return this._idleRotationWaitTime; }, /** * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating. */ set: function (time) { this._idleRotationWaitTime = time; }, enumerable: true, configurable: true }); Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", { /** * Gets the time (milliseconds) to take to spin up to the full idle rotation speed. */ get: function () { return this._idleRotationSpinupTime; }, /** * Sets the time (milliseconds) to take to spin up to the full idle rotation speed. */ set: function (time) { this._idleRotationSpinupTime = time; }, enumerable: true, configurable: true }); Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", { /** * Gets a value indicating if the camera is currently rotating because of this behavior */ get: function () { return Math.abs(this._cameraRotationSpeed) > 0; }, enumerable: true, configurable: true }); /** * Initializes the behavior. */ AutoRotationBehavior.prototype.init = function () { // Do notihng }; /** * Attaches the behavior to its arc rotate camera. * @param camera Defines the camera to attach the behavior to */ AutoRotationBehavior.prototype.attach = function (camera) { var _this = this; this._attachedCamera = camera; var scene = this._attachedCamera.getScene(); this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) { if (pointerInfoPre.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOWN) { _this._isPointerDown = true; return; } if (pointerInfoPre.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERUP) { _this._isPointerDown = false; } }); this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () { var now = _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_1__["PrecisionDate"].Now; var dt = 0; if (_this._lastFrameTime != null) { dt = now - _this._lastFrameTime; } _this._lastFrameTime = now; // Stop the animation if there is user interaction and the animation should stop for this interaction _this._applyUserInteraction(); var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime; var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0); _this._cameraRotationSpeed = _this._idleRotationSpeed * scale; // Step camera rotation by rotation speed if (_this._attachedCamera) { _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000); } }); }; /** * Detaches the behavior from its current arc rotate camera. */ AutoRotationBehavior.prototype.detach = function () { if (!this._attachedCamera) { return; } var scene = this._attachedCamera.getScene(); if (this._onPrePointerObservableObserver) { scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver); } this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver); this._attachedCamera = null; }; /** * Returns true if user is scrolling. * @return true if user is scrolling. */ AutoRotationBehavior.prototype._userIsZooming = function () { if (!this._attachedCamera) { return false; } return this._attachedCamera.inertialRadiusOffset !== 0; }; AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () { if (!this._attachedCamera) { return false; } var zoomHasHitLimit = false; if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) { zoomHasHitLimit = true; } // Update the record of previous radius - works as an approx. indicator of hitting radius limits this._lastFrameRadius = this._attachedCamera.radius; return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming(); }; /** * Applies any current user interaction to the camera. Takes into account maximum alpha rotation. */ AutoRotationBehavior.prototype._applyUserInteraction = function () { if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) { this._lastInteractionTime = _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_1__["PrecisionDate"].Now; } }; // Tools AutoRotationBehavior.prototype._userIsMoving = function () { if (!this._attachedCamera) { return false; } return this._attachedCamera.inertialAlphaOffset !== 0 || this._attachedCamera.inertialBetaOffset !== 0 || this._attachedCamera.inertialRadiusOffset !== 0 || this._attachedCamera.inertialPanningX !== 0 || this._attachedCamera.inertialPanningY !== 0 || this._isPointerDown; }; return AutoRotationBehavior; }()); /***/ }), /***/ "./Behaviors/Cameras/bouncingBehavior.ts": /*!***********************************************!*\ !*** ./Behaviors/Cameras/bouncingBehavior.ts ***! \***********************************************/ /*! exports provided: BouncingBehavior */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BouncingBehavior", function() { return BouncingBehavior; }); /* harmony import */ var _Animations_easing__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Animations/easing */ "./Animations/easing.ts"); /* harmony import */ var _Animations_animation__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Animations/animation */ "./Animations/animation.ts"); /** * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior */ var BouncingBehavior = /** @class */ (function () { function BouncingBehavior() { /** * The duration of the animation, in milliseconds */ this.transitionDuration = 450; /** * Length of the distance animated by the transition when lower radius is reached */ this.lowerRadiusTransitionRange = 2; /** * Length of the distance animated by the transition when upper radius is reached */ this.upperRadiusTransitionRange = -2; this._autoTransitionRange = false; // Animations this._radiusIsAnimating = false; this._radiusBounceTransition = null; this._animatables = new Array(); } Object.defineProperty(BouncingBehavior.prototype, "name", { /** * Gets the name of the behavior. */ get: function () { return "Bouncing"; }, enumerable: true, configurable: true }); Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", { /** * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically */ get: function () { return this._autoTransitionRange; }, /** * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically * Transition ranges will be set to 5% of the bounding box diagonal in world space */ set: function (value) { var _this = this; if (this._autoTransitionRange === value) { return; } this._autoTransitionRange = value; var camera = this._attachedCamera; if (!camera) { return; } if (value) { this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) { if (!mesh) { return; } mesh.computeWorldMatrix(true); var diagonal = mesh.getBoundingInfo().diagonalLength; _this.lowerRadiusTransitionRange = diagonal * 0.05; _this.upperRadiusTransitionRange = diagonal * 0.05; }); } else if (this._onMeshTargetChangedObserver) { camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver); } }, enumerable: true, configurable: true }); /** * Initializes the behavior. */ BouncingBehavior.prototype.init = function () { // Do notihng }; /** * Attaches the behavior to its arc rotate camera. * @param camera Defines the camera to attach the behavior to */ BouncingBehavior.prototype.attach = function (camera) { var _this = this; this._attachedCamera = camera; this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () { if (!_this._attachedCamera) { return; } // Add the bounce animation to the lower radius limit if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) { _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange); } // Add the bounce animation to the upper radius limit if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) { _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange); } }); }; /** * Detaches the behavior from its current arc rotate camera. */ BouncingBehavior.prototype.detach = function () { if (!this._attachedCamera) { return; } if (this._onAfterCheckInputsObserver) { this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver); } if (this._onMeshTargetChangedObserver) { this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver); } this._attachedCamera = null; }; /** * Checks if the camera radius is at the specified limit. Takes into account animation locks. * @param radiusLimit The limit to check against. * @return Bool to indicate if at limit. */ BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) { if (!this._attachedCamera) { return false; } if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) { return true; } return false; }; /** * Applies an animation to the radius of the camera, extending by the radiusDelta. * @param radiusDelta The delta by which to animate to. Can be negative. */ BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) { var _this = this; if (!this._attachedCamera) { return; } if (!this._radiusBounceTransition) { BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode); this._radiusBounceTransition = _Animations_animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].CreateAnimation("radius", _Animations_animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction); } // Prevent zoom until bounce has completed this._cachedWheelPrecision = this._attachedCamera.wheelPrecision; this._attachedCamera.wheelPrecision = Infinity; this._attachedCamera.inertialRadiusOffset = 0; // Animate to the radius limit this.stopAllAnimations(); this._radiusIsAnimating = true; var animatable = _Animations_animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); }); if (animatable) { this._animatables.push(animatable); } }; /** * Removes all animation locks. Allows new animations to be added to any of the camera properties. */ BouncingBehavior.prototype._clearAnimationLocks = function () { this._radiusIsAnimating = false; if (this._attachedCamera) { this._attachedCamera.wheelPrecision = this._cachedWheelPrecision; } }; /** * Stops and removes all animations that have been applied to the camera */ BouncingBehavior.prototype.stopAllAnimations = function () { if (this._attachedCamera) { this._attachedCamera.animations = []; } while (this._animatables.length) { this._animatables[0].onAnimationEnd = null; this._animatables[0].stop(); this._animatables.shift(); } }; /** * The easing function used by animations */ BouncingBehavior.EasingFunction = new _Animations_easing__WEBPACK_IMPORTED_MODULE_0__["BackEase"](0.3); /** * The easing mode used by animations */ BouncingBehavior.EasingMode = _Animations_easing__WEBPACK_IMPORTED_MODULE_0__["EasingFunction"].EASINGMODE_EASEOUT; return BouncingBehavior; }()); /***/ }), /***/ "./Behaviors/Cameras/framingBehavior.ts": /*!**********************************************!*\ !*** ./Behaviors/Cameras/framingBehavior.ts ***! \**********************************************/ /*! exports provided: FramingBehavior */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FramingBehavior", function() { return FramingBehavior; }); /* harmony import */ var _Animations_easing__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Animations/easing */ "./Animations/easing.ts"); /* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/precisionDate */ "./Misc/precisionDate.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Animations_animation__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Animations/animation */ "./Animations/animation.ts"); /** * The framing behavior (FramingBehavior) is designed to automatically position an ArcRotateCamera when its target is set to a mesh. It is also useful if you want to prevent the camera to go under a virtual horizontal plane. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior */ var FramingBehavior = /** @class */ (function () { function FramingBehavior() { this._mode = FramingBehavior.FitFrustumSidesMode; this._radiusScale = 1.0; this._positionScale = 0.5; this._defaultElevation = 0.3; this._elevationReturnTime = 1500; this._elevationReturnWaitTime = 1000; this._zoomStopsAnimation = false; this._framingTime = 1500; /** * Define if the behavior should automatically change the configured * camera limits and sensibilities. */ this.autoCorrectCameraLimitsAndSensibility = true; this._isPointerDown = false; this._lastInteractionTime = -Infinity; // Framing control this._animatables = new Array(); this._betaIsAnimating = false; } Object.defineProperty(FramingBehavior.prototype, "name", { /** * Gets the name of the behavior. */ get: function () { return "Framing"; }, enumerable: true, configurable: true }); Object.defineProperty(FramingBehavior.prototype, "mode", { /** * Gets current mode used by the behavior. */ get: function () { return this._mode; }, /** * Sets the current mode used by the behavior */ set: function (mode) { this._mode = mode; }, enumerable: true, configurable: true }); Object.defineProperty(FramingBehavior.prototype, "radiusScale", { /** * Gets the scale applied to the radius */ get: function () { return this._radiusScale; }, /** * Sets the scale applied to the radius (1 by default) */ set: function (radius) { this._radiusScale = radius; }, enumerable: true, configurable: true }); Object.defineProperty(FramingBehavior.prototype, "positionScale", { /** * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box. */ get: function () { return this._positionScale; }, /** * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box. */ set: function (scale) { this._positionScale = scale; }, enumerable: true, configurable: true }); Object.defineProperty(FramingBehavior.prototype, "defaultElevation", { /** * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle * behaviour is triggered, in radians. */ get: function () { return this._defaultElevation; }, /** * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle * behaviour is triggered, in radians. */ set: function (elevation) { this._defaultElevation = elevation; }, enumerable: true, configurable: true }); Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", { /** * Gets the time (in milliseconds) taken to return to the default beta position. * Negative value indicates camera should not return to default. */ get: function () { return this._elevationReturnTime; }, /** * Sets the time (in milliseconds) taken to return to the default beta position. * Negative value indicates camera should not return to default. */ set: function (speed) { this._elevationReturnTime = speed; }, enumerable: true, configurable: true }); Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", { /** * Gets the delay (in milliseconds) taken before the camera returns to the default beta position. */ get: function () { return this._elevationReturnWaitTime; }, /** * Sets the delay (in milliseconds) taken before the camera returns to the default beta position. */ set: function (time) { this._elevationReturnWaitTime = time; }, enumerable: true, configurable: true }); Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", { /** * Gets the flag that indicates if user zooming should stop animation. */ get: function () { return this._zoomStopsAnimation; }, /** * Sets the flag that indicates if user zooming should stop animation. */ set: function (flag) { this._zoomStopsAnimation = flag; }, enumerable: true, configurable: true }); Object.defineProperty(FramingBehavior.prototype, "framingTime", { /** * Gets the transition time when framing the mesh, in milliseconds */ get: function () { return this._framingTime; }, /** * Sets the transition time when framing the mesh, in milliseconds */ set: function (time) { this._framingTime = time; }, enumerable: true, configurable: true }); /** * Initializes the behavior. */ FramingBehavior.prototype.init = function () { // Do notihng }; /** * Attaches the behavior to its arc rotate camera. * @param camera Defines the camera to attach the behavior to */ FramingBehavior.prototype.attach = function (camera) { var _this = this; this._attachedCamera = camera; var scene = this._attachedCamera.getScene(); FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode); this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) { if (pointerInfoPre.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_1__["PointerEventTypes"].POINTERDOWN) { _this._isPointerDown = true; return; } if (pointerInfoPre.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_1__["PointerEventTypes"].POINTERUP) { _this._isPointerDown = false; } }); this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) { if (mesh) { _this.zoomOnMesh(mesh); } }); this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () { // Stop the animation if there is user interaction and the animation should stop for this interaction _this._applyUserInteraction(); // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it // back to the default position after a given timeout _this._maintainCameraAboveGround(); }); }; /** * Detaches the behavior from its current arc rotate camera. */ FramingBehavior.prototype.detach = function () { if (!this._attachedCamera) { return; } var scene = this._attachedCamera.getScene(); if (this._onPrePointerObservableObserver) { scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver); } if (this._onAfterCheckInputsObserver) { this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver); } if (this._onMeshTargetChangedObserver) { this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver); } this._attachedCamera = null; }; /** * Targets the given mesh and updates zoom level accordingly. * @param mesh The mesh to target. * @param radius Optional. If a cached radius position already exists, overrides default. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh * @param onAnimationEnd Callback triggered at the end of the framing animation */ FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) { if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; } if (onAnimationEnd === void 0) { onAnimationEnd = null; } mesh.computeWorldMatrix(true); var boundingBox = mesh.getBoundingInfo().boundingBox; this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd); }; /** * Targets the given mesh with its children and updates zoom level accordingly. * @param mesh The mesh to target. * @param radius Optional. If a cached radius position already exists, overrides default. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh * @param onAnimationEnd Callback triggered at the end of the framing animation */ FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) { if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; } if (onAnimationEnd === void 0) { onAnimationEnd = null; } mesh.computeWorldMatrix(true); var boundingBox = mesh.getHierarchyBoundingVectors(true); this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd); }; /** * Targets the given meshes with their children and updates zoom level accordingly. * @param meshes The mesh to target. * @param radius Optional. If a cached radius position already exists, overrides default. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh * @param onAnimationEnd Callback triggered at the end of the framing animation */ FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) { if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; } if (onAnimationEnd === void 0) { onAnimationEnd = null; } var min = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); var max = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"](-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); for (var i = 0; i < meshes.length; i++) { var boundingInfo = meshes[i].getHierarchyBoundingVectors(true); _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].CheckExtends(boundingInfo.min, min, max); _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].CheckExtends(boundingInfo.max, min, max); } this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd); }; /** * Targets the bounding box info defined by its extends and updates zoom level accordingly. * @param minimumWorld Determines the smaller position of the bounding box extend * @param maximumWorld Determines the bigger position of the bounding box extend * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh * @param onAnimationEnd Callback triggered at the end of the framing animation */ FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) { var _this = this; if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; } if (onAnimationEnd === void 0) { onAnimationEnd = null; } var zoomTarget; if (!this._attachedCamera) { return; } // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY var bottom = minimumWorld.y; var top = maximumWorld.y; var zoomTargetY = bottom + (top - bottom) * this._positionScale; var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5); if (focusOnOriginXZ) { zoomTarget = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"](0, zoomTargetY, 0); } else { var centerWorld = minimumWorld.add(radiusWorld); zoomTarget = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"](centerWorld.x, zoomTargetY, centerWorld.z); } if (!this._vectorTransition) { this._vectorTransition = _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].CreateAnimation("target", _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction); } this._betaIsAnimating = true; var animatable = _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime); if (animatable) { this._animatables.push(animatable); } // sets the radius and lower radius bounds // Small delta ensures camera is not always at lower zoom limit. var radius = 0; if (this._mode === FramingBehavior.FitFrustumSidesMode) { var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld); if (this.autoCorrectCameraLimitsAndSensibility) { this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ; } radius = position; } else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) { radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld); if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) { this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ; } } // Set sensibilities if (this.autoCorrectCameraLimitsAndSensibility) { var extend = maximumWorld.subtract(minimumWorld).length(); this._attachedCamera.panningSensibility = 5000 / extend; this._attachedCamera.wheelPrecision = 100 / radius; } // transition to new radius if (!this._radiusTransition) { this._radiusTransition = _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].CreateAnimation("radius", _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction); } animatable = _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () { _this.stopAllAnimations(); if (onAnimationEnd) { onAnimationEnd(); } if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) { _this._attachedCamera.storeState(); } }); if (animatable) { this._animatables.push(animatable); } }; /** * Calculates the lowest radius for the camera based on the bounding box of the mesh. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary * frustum width. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order * to fully enclose the mesh in the viewing frustum. */ FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) { var size = maximumWorld.subtract(minimumWorld); var boxVectorGlobalDiagonal = size.length(); var frustumSlope = this._getFrustumSlope(); // Formula for setting distance // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene) var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5; // Horizon distance var radius = radiusWithoutFraming * this._radiusScale; var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x)); var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y)); var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum); var camera = this._attachedCamera; if (!camera) { return 0; } if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) { // Don't exceed the requested limit distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance; } // Don't exceed the upper radius limit if (camera.upperRadiusLimit) { distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance; } return distance; }; /** * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera * is automatically returned to its default position (expected to be above ground plane). */ FramingBehavior.prototype._maintainCameraAboveGround = function () { var _this = this; if (this._elevationReturnTime < 0) { return; } var timeSinceInteraction = _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_3__["PrecisionDate"].Now - this._lastInteractionTime; var defaultBeta = Math.PI * 0.5 - this._defaultElevation; var limitBeta = Math.PI * 0.5; // Bring the camera back up if below the ground plane if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) { this._betaIsAnimating = true; //Transition to new position this.stopAllAnimations(); if (!this._betaTransition) { this._betaTransition = _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].CreateAnimation("beta", _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction); } var animatabe = _Animations_animation__WEBPACK_IMPORTED_MODULE_5__["Animation"].TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () { _this._clearAnimationLocks(); _this.stopAllAnimations(); }); if (animatabe) { this._animatables.push(animatabe); } } }; /** * Returns the frustum slope based on the canvas ratio and camera FOV * @returns The frustum slope represented as a Vector2 with X and Y slopes */ FramingBehavior.prototype._getFrustumSlope = function () { // Calculate the viewport ratio // Aspect Ratio is Height/Width. var camera = this._attachedCamera; if (!camera) { return _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector2"].Zero(); } var engine = camera.getScene().getEngine(); var aspectRatio = engine.getAspectRatio(camera); // Camera FOV is the vertical field of view (top-bottom) in radians. // Slope of the frustum top/bottom planes in view space, relative to the forward vector. var frustumSlopeY = Math.tan(camera.fov / 2); // Slope of the frustum left/right planes in view space, relative to the forward vector. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit // along the forward vector. var frustumSlopeX = frustumSlopeY * aspectRatio; return new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector2"](frustumSlopeX, frustumSlopeY); }; /** * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties. */ FramingBehavior.prototype._clearAnimationLocks = function () { this._betaIsAnimating = false; }; /** * Applies any current user interaction to the camera. Takes into account maximum alpha rotation. */ FramingBehavior.prototype._applyUserInteraction = function () { if (this.isUserIsMoving) { this._lastInteractionTime = _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_3__["PrecisionDate"].Now; this.stopAllAnimations(); this._clearAnimationLocks(); } }; /** * Stops and removes all animations that have been applied to the camera */ FramingBehavior.prototype.stopAllAnimations = function () { if (this._attachedCamera) { this._attachedCamera.animations = []; } while (this._animatables.length) { if (this._animatables[0]) { this._animatables[0].onAnimationEnd = null; this._animatables[0].stop(); } this._animatables.shift(); } }; Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", { /** * Gets a value indicating if the user is moving the camera */ get: function () { if (!this._attachedCamera) { return false; } return this._attachedCamera.inertialAlphaOffset !== 0 || this._attachedCamera.inertialBetaOffset !== 0 || this._attachedCamera.inertialRadiusOffset !== 0 || this._attachedCamera.inertialPanningX !== 0 || this._attachedCamera.inertialPanningY !== 0 || this._isPointerDown; }, enumerable: true, configurable: true }); /** * The easing function used by animations */ FramingBehavior.EasingFunction = new _Animations_easing__WEBPACK_IMPORTED_MODULE_0__["ExponentialEase"](); /** * The easing mode used by animations */ FramingBehavior.EasingMode = _Animations_easing__WEBPACK_IMPORTED_MODULE_0__["EasingFunction"].EASINGMODE_EASEINOUT; // Statics /** * The camera can move all the way towards the mesh. */ FramingBehavior.IgnoreBoundsSizeMode = 0; /** * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides */ FramingBehavior.FitFrustumSidesMode = 1; return FramingBehavior; }()); /***/ }), /***/ "./Behaviors/Cameras/index.ts": /*!************************************!*\ !*** ./Behaviors/Cameras/index.ts ***! \************************************/ /*! exports provided: AutoRotationBehavior, BouncingBehavior, FramingBehavior */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _autoRotationBehavior__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./autoRotationBehavior */ "./Behaviors/Cameras/autoRotationBehavior.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AutoRotationBehavior", function() { return _autoRotationBehavior__WEBPACK_IMPORTED_MODULE_0__["AutoRotationBehavior"]; }); /* harmony import */ var _bouncingBehavior__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bouncingBehavior */ "./Behaviors/Cameras/bouncingBehavior.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BouncingBehavior", function() { return _bouncingBehavior__WEBPACK_IMPORTED_MODULE_1__["BouncingBehavior"]; }); /* harmony import */ var _framingBehavior__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./framingBehavior */ "./Behaviors/Cameras/framingBehavior.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FramingBehavior", function() { return _framingBehavior__WEBPACK_IMPORTED_MODULE_2__["FramingBehavior"]; }); /***/ }), /***/ "./Behaviors/Meshes/attachToBoxBehavior.ts": /*!*************************************************!*\ !*** ./Behaviors/Meshes/attachToBoxBehavior.ts ***! \*************************************************/ /*! exports provided: AttachToBoxBehavior */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AttachToBoxBehavior", function() { return AttachToBoxBehavior; }); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /** * @hidden */ var FaceDirectionInfo = /** @class */ (function () { function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) { if (rotatedDirection === void 0) { rotatedDirection = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](); } if (diff === void 0) { diff = 0; } if (ignore === void 0) { ignore = false; } this.direction = direction; this.rotatedDirection = rotatedDirection; this.diff = diff; this.ignore = ignore; } return FaceDirectionInfo; }()); /** * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera */ var AttachToBoxBehavior = /** @class */ (function () { /** * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera * @param ui The transform node that should be attched to the mesh */ function AttachToBoxBehavior(ui) { this.ui = ui; /** * The name of the behavior */ this.name = "AttachToBoxBehavior"; /** * The distance away from the face of the mesh that the UI should be attached to (default: 0.15) */ this.distanceAwayFromFace = 0.15; /** * The distance from the bottom of the face that the UI should be attached to (default: 0.15) */ this.distanceAwayFromBottomOfFace = 0.15; this._faceVectors = [new FaceDirectionInfo(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Up()), new FaceDirectionInfo(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Down()), new FaceDirectionInfo(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Left()), new FaceDirectionInfo(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Right()), new FaceDirectionInfo(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Forward()), new FaceDirectionInfo(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Forward().scaleInPlace(-1))]; this._tmpMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"](); this._tmpVector = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](); this._zeroVector = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); this._lookAtTmpMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"](); /* Does nothing */ } /** * Initializes the behavior */ AttachToBoxBehavior.prototype.init = function () { /* Does nothing */ }; AttachToBoxBehavior.prototype._closestFace = function (targetDirection) { var _this = this; // Go over each face and calculate the angle between the face's normal and targetDirection this._faceVectors.forEach(function (v) { if (!_this._target.rotationQuaternion) { _this._target.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z); } _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix); _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection); v.diff = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].GetAngleBetweenVectors(v.rotatedDirection, targetDirection, _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Cross(v.rotatedDirection, targetDirection)); }); // Return the face information of the one with the normal closeset to target direction return this._faceVectors.reduce(function (min, p) { if (min.ignore) { return p; } else if (p.ignore) { return min; } else { return min.diff < p.diff ? min : p; } }, this._faceVectors[0]); }; AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) { if (up === void 0) { up = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0, 1, 0); } _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix); this._lookAtTmpMatrix.invert(); _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromRotationMatrixToRef(this._lookAtTmpMatrix, ref); }; /** * Attaches the AttachToBoxBehavior to the passed in mesh * @param target The mesh that the specified node will be attached to */ AttachToBoxBehavior.prototype.attach = function (target) { var _this = this; this._target = target; this._scene = this._target.getScene(); // Every frame, update the app bars position this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () { if (!_this._scene.activeCamera) { return; } // Find the face closest to the cameras position var cameraPos = _this._scene.activeCamera.position; if (_this._scene.activeCamera.devicePosition) { cameraPos = _this._scene.activeCamera.devicePosition; } var facing = _this._closestFace(cameraPos.subtract(target.position)); if (_this._scene.activeCamera.leftCamera) { _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix); } else { _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix); } // Get camera up direction _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].TransformCoordinatesToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Up(), _this._tmpMatrix, _this._tmpVector); // Ignore faces to not select a parrelel face for the up vector of the UI _this._faceVectors.forEach(function (v) { if (facing.direction.x && v.direction.x) { v.ignore = true; } if (facing.direction.y && v.direction.y) { v.ignore = true; } if (facing.direction.z && v.direction.z) { v.ignore = true; } }); var facingUp = _this._closestFace(_this._tmpVector); // Unignore faces _this._faceVectors.forEach(function (v) { v.ignore = false; }); // Position the app bar on that face _this.ui.position.copyFrom(target.position); if (facing.direction.x) { facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector); _this.ui.position.addInPlace(_this._tmpVector); } if (facing.direction.y) { facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector); _this.ui.position.addInPlace(_this._tmpVector); } if (facing.direction.z) { facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector); _this.ui.position.addInPlace(_this._tmpVector); } // Rotate to be oriented properly to the camera if (!_this.ui.rotationQuaternion) { _this.ui.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z); } facing.rotatedDirection.scaleToRef(-1, _this._tmpVector); _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion); // Place ui the correct distance from the bottom of the mesh if (facingUp.direction.x) { _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector); } if (facingUp.direction.y) { _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector); } if (facingUp.direction.z) { _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector); } _this.ui.position.addInPlace(_this._tmpVector); }); }; /** * Detaches the behavior from the mesh */ AttachToBoxBehavior.prototype.detach = function () { this._scene.onBeforeRenderObservable.remove(this._onRenderObserver); }; return AttachToBoxBehavior; }()); /***/ }), /***/ "./Behaviors/Meshes/fadeInOutBehavior.ts": /*!***********************************************!*\ !*** ./Behaviors/Meshes/fadeInOutBehavior.ts ***! \***********************************************/ /*! exports provided: FadeInOutBehavior */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FadeInOutBehavior", function() { return FadeInOutBehavior; }); /** * A behavior that when attached to a mesh will allow the mesh to fade in and out */ var FadeInOutBehavior = /** @class */ (function () { /** * Instatiates the FadeInOutBehavior */ function FadeInOutBehavior() { var _this = this; /** * Time in milliseconds to delay before fading in (Default: 0) */ this.delay = 0; /** * Time in milliseconds for the mesh to fade in (Default: 300) */ this.fadeInTime = 300; this._millisecondsPerFrame = 1000 / 60; this._hovered = false; this._hoverValue = 0; this._ownerNode = null; this._update = function () { if (_this._ownerNode) { _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame; _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime); if (_this._ownerNode.visibility > 1) { _this._setAllVisibility(_this._ownerNode, 1); _this._hoverValue = _this.fadeInTime + _this.delay; return; } else if (_this._ownerNode.visibility < 0) { _this._setAllVisibility(_this._ownerNode, 0); if (_this._hoverValue < 0) { _this._hoverValue = 0; return; } } setTimeout(_this._update, _this._millisecondsPerFrame); } }; } Object.defineProperty(FadeInOutBehavior.prototype, "name", { /** * The name of the behavior */ get: function () { return "FadeInOut"; }, enumerable: true, configurable: true }); /** * Initializes the behavior */ FadeInOutBehavior.prototype.init = function () { }; /** * Attaches the fade behavior on the passed in mesh * @param ownerNode The mesh that will be faded in/out once attached */ FadeInOutBehavior.prototype.attach = function (ownerNode) { this._ownerNode = ownerNode; this._setAllVisibility(this._ownerNode, 0); }; /** * Detaches the behavior from the mesh */ FadeInOutBehavior.prototype.detach = function () { this._ownerNode = null; }; /** * Triggers the mesh to begin fading in or out * @param value if the object should fade in or out (true to fade in) */ FadeInOutBehavior.prototype.fadeIn = function (value) { this._hovered = value; this._update(); }; FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) { var _this = this; mesh.visibility = value; mesh.getChildMeshes().forEach(function (c) { _this._setAllVisibility(c, value); }); }; return FadeInOutBehavior; }()); /***/ }), /***/ "./Behaviors/Meshes/index.ts": /*!***********************************!*\ !*** ./Behaviors/Meshes/index.ts ***! \***********************************/ /*! exports provided: AttachToBoxBehavior, FadeInOutBehavior, MultiPointerScaleBehavior, PointerDragBehavior, SixDofDragBehavior */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _attachToBoxBehavior__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./attachToBoxBehavior */ "./Behaviors/Meshes/attachToBoxBehavior.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AttachToBoxBehavior", function() { return _attachToBoxBehavior__WEBPACK_IMPORTED_MODULE_0__["AttachToBoxBehavior"]; }); /* harmony import */ var _fadeInOutBehavior__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./fadeInOutBehavior */ "./Behaviors/Meshes/fadeInOutBehavior.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FadeInOutBehavior", function() { return _fadeInOutBehavior__WEBPACK_IMPORTED_MODULE_1__["FadeInOutBehavior"]; }); /* harmony import */ var _multiPointerScaleBehavior__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./multiPointerScaleBehavior */ "./Behaviors/Meshes/multiPointerScaleBehavior.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiPointerScaleBehavior", function() { return _multiPointerScaleBehavior__WEBPACK_IMPORTED_MODULE_2__["MultiPointerScaleBehavior"]; }); /* harmony import */ var _pointerDragBehavior__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./pointerDragBehavior */ "./Behaviors/Meshes/pointerDragBehavior.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerDragBehavior", function() { return _pointerDragBehavior__WEBPACK_IMPORTED_MODULE_3__["PointerDragBehavior"]; }); /* harmony import */ var _sixDofDragBehavior__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./sixDofDragBehavior */ "./Behaviors/Meshes/sixDofDragBehavior.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SixDofDragBehavior", function() { return _sixDofDragBehavior__WEBPACK_IMPORTED_MODULE_4__["SixDofDragBehavior"]; }); /***/ }), /***/ "./Behaviors/Meshes/multiPointerScaleBehavior.ts": /*!*******************************************************!*\ !*** ./Behaviors/Meshes/multiPointerScaleBehavior.ts ***! \*******************************************************/ /*! exports provided: MultiPointerScaleBehavior */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MultiPointerScaleBehavior", function() { return MultiPointerScaleBehavior; }); /* harmony import */ var _pointerDragBehavior__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./pointerDragBehavior */ "./Behaviors/Meshes/pointerDragBehavior.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /** * A behavior that when attached to a mesh will allow the mesh to be scaled */ var MultiPointerScaleBehavior = /** @class */ (function () { /** * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled */ function MultiPointerScaleBehavior() { this._startDistance = 0; this._initialScale = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, 0); this._targetScale = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, 0); this._sceneRenderObserver = null; this._dragBehaviorA = new _pointerDragBehavior__WEBPACK_IMPORTED_MODULE_0__["PointerDragBehavior"]({}); this._dragBehaviorA.moveAttached = false; this._dragBehaviorB = new _pointerDragBehavior__WEBPACK_IMPORTED_MODULE_0__["PointerDragBehavior"]({}); this._dragBehaviorB.moveAttached = false; } Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", { /** * The name of the behavior */ get: function () { return "MultiPointerScale"; }, enumerable: true, configurable: true }); /** * Initializes the behavior */ MultiPointerScaleBehavior.prototype.init = function () { }; MultiPointerScaleBehavior.prototype._getCurrentDistance = function () { return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length(); }; /** * Attaches the scale behavior the passed in mesh * @param ownerNode The mesh that will be scaled around once attached */ MultiPointerScaleBehavior.prototype.attach = function (ownerNode) { var _this = this; this._ownerNode = ownerNode; // Create 2 drag behaviors such that each will only be triggered by a separate pointer this._dragBehaviorA.onDragStartObservable.add(function (e) { if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) { if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) { _this._dragBehaviorA.releaseDrag(); } else { _this._initialScale.copyFrom(ownerNode.scaling); _this._startDistance = _this._getCurrentDistance(); } } }); this._dragBehaviorB.onDragStartObservable.add(function (e) { if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) { if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) { _this._dragBehaviorB.releaseDrag(); } else { _this._initialScale.copyFrom(ownerNode.scaling); _this._startDistance = _this._getCurrentDistance(); } } }); // Once both drag behaviors are active scale based on the distance between the two pointers [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) { behavior.onDragObservable.add(function () { if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) { var ratio = _this._getCurrentDistance() / _this._startDistance; _this._initialScale.scaleToRef(ratio, _this._targetScale); } }); }); ownerNode.addBehavior(this._dragBehaviorA); ownerNode.addBehavior(this._dragBehaviorB); // On every frame move towards target scaling to avoid jitter caused by vr controllers this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () { if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) { var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1); if (change.length() > 0.01) { ownerNode.scaling.addInPlace(change); } } }); }; /** * Detaches the behavior from the mesh */ MultiPointerScaleBehavior.prototype.detach = function () { var _this = this; this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver); [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) { behavior.onDragStartObservable.clear(); behavior.onDragObservable.clear(); _this._ownerNode.removeBehavior(behavior); }); }; return MultiPointerScaleBehavior; }()); /***/ }), /***/ "./Behaviors/Meshes/pointerDragBehavior.ts": /*!*************************************************!*\ !*** ./Behaviors/Meshes/pointerDragBehavior.ts ***! \*************************************************/ /*! exports provided: PointerDragBehavior */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerDragBehavior", function() { return PointerDragBehavior; }); /* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Meshes/mesh */ "./Meshes/mesh.ts"); /* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../scene */ "./scene.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); /* harmony import */ var _Culling_ray__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Culling/ray */ "./Culling/ray.ts"); /* harmony import */ var _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Misc/pivotTools */ "./Misc/pivotTools.ts"); /* harmony import */ var _Meshes_Builders_planeBuilder__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Meshes/Builders/planeBuilder */ "./Meshes/Builders/planeBuilder.ts"); /** * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events */ var PointerDragBehavior = /** @class */ (function () { /** * Creates a pointer drag behavior that can be attached to a mesh * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera) */ function PointerDragBehavior(options) { this._useAlternatePickedPointAboveMaxDragAngleDragSpeed = -1.1; /** * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0) */ this.maxDragAngle = 0; /** * @hidden */ this._useAlternatePickedPointAboveMaxDragAngle = false; /** * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active) */ this.currentDraggingPointerID = -1; /** * If the behavior is currently in a dragging state */ this.dragging = false; /** * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2) */ this.dragDeltaRatio = 0.2; /** * If the drag plane orientation should be updated during the dragging (Default: true) */ this.updateDragPlane = true; // Debug mode will display drag planes to help visualize behavior this._debugMode = false; this._moving = false; /** * Fires each time the attached mesh is dragged with the pointer * * delta between last drag position and current drag position in world space * * dragDistance along the drag axis * * dragPlaneNormal normal of the current drag plane used during the drag * * dragPlanePoint in world space where the drag intersects the drag plane */ this.onDragObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Fires each time a drag begins (eg. mouse down on mesh) */ this.onDragStartObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Fires each time a drag ends (eg. mouse release after drag) */ this.onDragEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * If the attached mesh should be moved when dragged */ this.moveAttached = true; /** * If the drag behavior will react to drag events (Default: true) */ this.enabled = true; /** * If camera controls should be detached during the drag */ this.detachCameraControls = true; /** * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true) */ this.useObjectOrienationForDragging = true; /** * Predicate to determine if it is valid to move the object to a new position when it is moved */ this.validateDrag = function (targetPosition) { return true; }; this._tmpVector = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); this._alternatePickedPoint = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); this._worldDragAxis = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); this._targetPosition = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); this._attachedElement = null; this._startDragRay = new _Culling_ray__WEBPACK_IMPORTED_MODULE_5__["Ray"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"]()); this._lastPointerRay = {}; this._dragDelta = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](); // Variables to avoid instantiation in the below method this._pointA = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); this._pointB = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); this._pointC = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); this._lineA = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); this._lineB = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); this._localAxis = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); this._lookAt = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); this._options = options ? options : {}; var optionCount = 0; if (this._options.dragAxis) { optionCount++; } if (this._options.dragPlaneNormal) { optionCount++; } if (optionCount > 1) { throw "Multiple drag modes specified in dragBehavior options. Only one expected"; } } Object.defineProperty(PointerDragBehavior.prototype, "name", { /** * The name of the behavior */ get: function () { return "PointerDrag"; }, enumerable: true, configurable: true }); /** * Initializes the behavior */ PointerDragBehavior.prototype.init = function () { }; /** * Attaches the drag behavior the passed in mesh * @param ownerNode The mesh that will be dragged around once attached */ PointerDragBehavior.prototype.attach = function (ownerNode) { var _this = this; this._scene = ownerNode.getScene(); this._attachedNode = ownerNode; // Initialize drag plane to not interfere with existing scene if (!PointerDragBehavior._planeScene) { if (this._debugMode) { PointerDragBehavior._planeScene = this._scene; } else { PointerDragBehavior._planeScene = new _scene__WEBPACK_IMPORTED_MODULE_1__["Scene"](this._scene.getEngine()); PointerDragBehavior._planeScene.detachControl(); this._scene.getEngine().scenes.pop(); this._scene.onDisposeObservable.addOnce(function () { PointerDragBehavior._planeScene.dispose(); PointerDragBehavior._planeScene = null; }); } } this._dragPlane = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_0__["Mesh"].CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, _Meshes_mesh__WEBPACK_IMPORTED_MODULE_0__["Mesh"].DOUBLESIDE); // State of the drag this.lastDragPosition = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); var pickPredicate = function (m) { return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode); }; this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) { if (!_this.enabled) { return; } if (pointerInfo.type == _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERDOWN) { if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) { _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint); } } else if (pointerInfo.type == _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERUP) { if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) { _this.releaseDrag(); } } else if (pointerInfo.type == _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERMOVE) { var pointerId = pointerInfo.event.pointerId; // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") { if (_this._lastPointerRay[_this.currentDraggingPointerID]) { _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID]; delete _this._lastPointerRay[_this.currentDraggingPointerID]; } _this.currentDraggingPointerID = pointerId; } // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag() if (!_this._lastPointerRay[pointerId]) { _this._lastPointerRay[pointerId] = new _Culling_ray__WEBPACK_IMPORTED_MODULE_5__["Ray"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"]()); } if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) { _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin); _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction); if (_this.currentDraggingPointerID == pointerId && _this.dragging) { _this._moveDrag(pointerInfo.pickInfo.ray); } } } }); this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () { if (_this._moving && _this.moveAttached) { _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__["PivotTools"]._RemoveAndStorePivotPoint(_this._attachedNode); // Slowly move mesh to avoid jitter _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector); _this._tmpVector.scaleInPlace(_this.dragDeltaRatio); (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector); if (_this.validateDrag(_this._tmpVector)) { (_this._attachedNode).setAbsolutePosition(_this._tmpVector); } _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__["PivotTools"]._RestorePivotPoint(_this._attachedNode); } }); }; /** * Force relase the drag action by code. */ PointerDragBehavior.prototype.releaseDrag = function () { this.dragging = false; this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID }); this.currentDraggingPointerID = -1; this._moving = false; // Reattach camera controls if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) { this._scene.activeCamera.attachControl(this._attachedElement, true); } }; /** * Simulates the start of a pointer drag event on the behavior * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID) * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh) * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position) */ PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) { if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; } this._startDrag(pointerId, fromRay, startPickedPoint); var lastRay = this._lastPointerRay[pointerId]; if (pointerId === PointerDragBehavior._AnyMouseID) { lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]; } if (lastRay) { // if there was a last pointer ray drag the object there this._moveDrag(lastRay); } }; PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) { if (!this._scene.activeCamera || this.dragging || !this._attachedNode) { return; } _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__["PivotTools"]._RemoveAndStorePivotPoint(this._attachedNode); // Create start ray from the camera to the object if (fromRay) { this._startDragRay.direction.copyFrom(fromRay.direction); this._startDragRay.origin.copyFrom(fromRay.origin); } else { this._startDragRay.origin.copyFrom(this._scene.activeCamera.position); this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector); this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction); } this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector); var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay); if (pickedPoint) { this.dragging = true; this.currentDraggingPointerID = pointerId; this.lastDragPosition.copyFrom(pickedPoint); this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID }); this._targetPosition.copyFrom((this._attachedNode).absolutePosition); // Detatch camera controls if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) { if (this._scene.activeCamera.inputs.attachedElement) { this._attachedElement = this._scene.activeCamera.inputs.attachedElement; this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement); } else { this._attachedElement = null; } } } _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__["PivotTools"]._RestorePivotPoint(this._attachedNode); }; PointerDragBehavior.prototype._moveDrag = function (ray) { this._moving = true; var pickedPoint = this._pickWithRayOnDragPlane(ray); if (pickedPoint) { if (this.updateDragPlane) { this._updateDragPlanePosition(ray, pickedPoint); } var dragLength = 0; // depending on the drag mode option drag accordingly if (this._options.dragAxis) { // Convert local drag axis to world _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis); // Project delta drag from the drag plane onto the drag axis pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector); dragLength = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Dot(this._tmpVector, this._worldDragAxis); this._worldDragAxis.scaleToRef(dragLength, this._dragDelta); } else { dragLength = this._dragDelta.length(); pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta); } this._targetPosition.addInPlace(this._dragDelta); this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID }); this.lastDragPosition.copyFrom(pickedPoint); } }; PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) { var _this = this; if (!ray) { return null; } // Calculate angle between plane normal and ray var angle = Math.acos(_Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Dot(this._dragPlane.forward, ray.direction)); // Correct if ray is casted from oposite side if (angle > Math.PI / 2) { angle = Math.PI - angle; } // If the angle is too perpendicular to the plane pick another point on the plane where it is looking if (this.maxDragAngle > 0 && angle > this.maxDragAngle) { if (this._useAlternatePickedPointAboveMaxDragAngle) { // Invert ray direction along the towards object axis this._tmpVector.copyFrom(ray.direction); (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint); this._alternatePickedPoint.normalize(); this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed * _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Dot(this._alternatePickedPoint, this._tmpVector)); this._tmpVector.addInPlace(this._alternatePickedPoint); // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point var dot = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Dot(this._dragPlane.forward, this._tmpVector); this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint); this._alternatePickedPoint.addInPlace(this._tmpVector); this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition); return this._alternatePickedPoint; } else { return null; } } var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; }); if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) { return pickResult.pickedPoint; } else { return null; } }; // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) { this._pointA.copyFrom(dragPlanePosition); if (this._options.dragAxis) { this.useObjectOrienationForDragging ? _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis); // Calculate plane normal in direction of camera but perpendicular to drag axis this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis ray.origin.subtractToRef(this._pointA, this._pointC); this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera // Get perpendicular line from direction to camera and drag axis this._pointB.subtractToRef(this._pointA, this._lineA); this._pointC.subtractToRef(this._pointA, this._lineB); _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].CrossToRef(this._lineA, this._lineB, this._lookAt); // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].CrossToRef(this._lineA, this._lookAt, this._lookAt); this._lookAt.normalize(); this._dragPlane.position.copyFrom(this._pointA); this._pointA.addToRef(this._lookAt, this._lookAt); this._dragPlane.lookAt(this._lookAt); } else if (this._options.dragPlaneNormal) { this.useObjectOrienationForDragging ? _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal); this._dragPlane.position.copyFrom(this._pointA); this._pointA.addToRef(this._localAxis, this._lookAt); this._dragPlane.lookAt(this._lookAt); } else { this._dragPlane.position.copyFrom(this._pointA); this._dragPlane.lookAt(ray.origin); } // Update the position of the drag plane so it doesn't get out of sync with the node (eg. when moving back and forth quickly) this._dragPlane.position.copyFrom(this._attachedNode.absolutePosition); this._dragPlane.computeWorldMatrix(true); }; /** * Detaches the behavior from the mesh */ PointerDragBehavior.prototype.detach = function () { if (this._pointerObserver) { this._scene.onPointerObservable.remove(this._pointerObserver); } if (this._beforeRenderObserver) { this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver); } this.releaseDrag(); }; PointerDragBehavior._AnyMouseID = -2; return PointerDragBehavior; }()); /***/ }), /***/ "./Behaviors/Meshes/sixDofDragBehavior.ts": /*!************************************************!*\ !*** ./Behaviors/Meshes/sixDofDragBehavior.ts ***! \************************************************/ /*! exports provided: SixDofDragBehavior */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SixDofDragBehavior", function() { return SixDofDragBehavior; }); /* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts"); /* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../scene */ "./scene.ts"); /* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Misc/pivotTools */ "./Misc/pivotTools.ts"); /** * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray */ var SixDofDragBehavior = /** @class */ (function () { /** * Instantiates a behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray */ function SixDofDragBehavior() { this._sceneRenderObserver = null; this._targetPosition = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); this._moving = false; this._startingOrientation = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); /** * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 3) */ this.zDragFactor = 3; /** * If the object should rotate to face the drag origin */ this.rotateDraggedObject = true; /** * If the behavior is currently in a dragging state */ this.dragging = false; /** * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2) */ this.dragDeltaRatio = 0.2; /** * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active) */ this.currentDraggingPointerID = -1; /** * If camera controls should be detached during the drag */ this.detachCameraControls = true; /** * Fires each time a drag starts */ this.onDragStartObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_4__["Observable"](); /** * Fires each time a drag ends (eg. mouse release after drag) */ this.onDragEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_4__["Observable"](); } Object.defineProperty(SixDofDragBehavior.prototype, "name", { /** * The name of the behavior */ get: function () { return "SixDofDrag"; }, enumerable: true, configurable: true }); /** * Initializes the behavior */ SixDofDragBehavior.prototype.init = function () { }; /** * Attaches the scale behavior the passed in mesh * @param ownerNode The mesh that will be scaled around once attached */ SixDofDragBehavior.prototype.attach = function (ownerNode) { var _this = this; this._ownerNode = ownerNode; this._scene = this._ownerNode.getScene(); if (!SixDofDragBehavior._virtualScene) { SixDofDragBehavior._virtualScene = new _scene__WEBPACK_IMPORTED_MODULE_1__["Scene"](this._scene.getEngine()); SixDofDragBehavior._virtualScene.detachControl(); this._scene.getEngine().scenes.pop(); } var pickedMesh = null; var lastSixDofOriginPosition = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); // Setup virtual meshes to be used for dragging without dirtying the existing scene this._virtualOriginMesh = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_0__["AbstractMesh"]("", SixDofDragBehavior._virtualScene); this._virtualOriginMesh.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); this._virtualDragMesh = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_0__["AbstractMesh"]("", SixDofDragBehavior._virtualScene); this._virtualDragMesh.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); var pickPredicate = function (m) { return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode); }; var attachedElement = null; this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) { if (pointerInfo.type == _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_2__["PointerEventTypes"].POINTERDOWN) { if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) { if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == _Cameras_camera__WEBPACK_IMPORTED_MODULE_5__["Camera"].RIG_MODE_NONE) { pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.globalPosition); } pickedMesh = _this._ownerNode; _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__["PivotTools"]._RemoveAndStorePivotPoint(pickedMesh); lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin); // Set position and orientation of the controller _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin); _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.add(pointerInfo.pickInfo.ray.direction)); // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged _this._virtualOriginMesh.removeChild(_this._virtualDragMesh); pickedMesh.computeWorldMatrix(); _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition); if (!pickedMesh.rotationQuaternion) { pickedMesh.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z); } var oldParent = pickedMesh.parent; pickedMesh.setParent(null); _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion); pickedMesh.setParent(oldParent); _this._virtualOriginMesh.addChild(_this._virtualDragMesh); // Update state _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition); _this.dragging = true; _this.currentDraggingPointerID = pointerInfo.event.pointerId; // Detatch camera controls if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) { if (_this._scene.activeCamera.inputs.attachedElement) { attachedElement = _this._scene.activeCamera.inputs.attachedElement; _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement); } else { attachedElement = null; } } _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__["PivotTools"]._RestorePivotPoint(pickedMesh); _this.onDragStartObservable.notifyObservers({}); } } else if (pointerInfo.type == _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_2__["PointerEventTypes"].POINTERUP) { if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) { _this.dragging = false; _this._moving = false; _this.currentDraggingPointerID = -1; pickedMesh = null; _this._virtualOriginMesh.removeChild(_this._virtualDragMesh); // Reattach camera controls if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) { _this._scene.activeCamera.attachControl(attachedElement, true); } _this.onDragEndObservable.notifyObservers({}); } } else if (pointerInfo.type == _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_2__["PointerEventTypes"].POINTERMOVE) { if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) { var zDragFactor = _this.zDragFactor; if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == _Cameras_camera__WEBPACK_IMPORTED_MODULE_5__["Camera"].RIG_MODE_NONE) { pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.globalPosition); zDragFactor = 0; } // Calculate controller drag distance in controller space var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition); lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin); var localOriginDragDifference = -_Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Dot(originDragDifference, pointerInfo.pickInfo.ray.direction); _this._virtualOriginMesh.addChild(_this._virtualDragMesh); // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z; if (_this._virtualDragMesh.position.z < 0) { _this._virtualDragMesh.position.z = 0; } // Update the controller position _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin); _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.add(pointerInfo.pickInfo.ray.direction)); _this._virtualOriginMesh.removeChild(_this._virtualDragMesh); // Move the virtualObjectsPosition into the picked mesh's space if needed _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition); if (pickedMesh.parent) { _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(_this._targetPosition, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition); } if (!_this._moving) { _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion); } _this._moving = true; } } }); var tmpQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); // On every frame move towards target scaling to avoid jitter caused by vr controllers this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () { if (_this.dragging && _this._moving && pickedMesh) { _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__["PivotTools"]._RemoveAndStorePivotPoint(pickedMesh); // Slowly move mesh to avoid jitter pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio)); if (_this.rotateDraggedObject) { // Get change in rotation tmpQuaternion.copyFrom(_this._startingOrientation); tmpQuaternion.x = -tmpQuaternion.x; tmpQuaternion.y = -tmpQuaternion.y; tmpQuaternion.z = -tmpQuaternion.z; _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion); // Convert change in rotation to only y axis rotation _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion); tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion); // Slowly move mesh to avoid jitter var oldParent = pickedMesh.parent; // Only rotate the mesh if it's parent has uniform scaling if (!oldParent || (oldParent.scaling && !oldParent.scaling.isNonUniformWithinEpsilon(0.001))) { pickedMesh.setParent(null); _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion); pickedMesh.setParent(oldParent); } } _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__["PivotTools"]._RestorePivotPoint(pickedMesh); } }); }; /** * Detaches the behavior from the mesh */ SixDofDragBehavior.prototype.detach = function () { if (this._scene) { this._scene.onPointerObservable.remove(this._pointerObserver); } if (this._ownerNode) { this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver); } if (this._virtualOriginMesh) { this._virtualOriginMesh.dispose(); } if (this._virtualDragMesh) { this._virtualDragMesh.dispose(); } this.onDragEndObservable.clear(); this.onDragStartObservable.clear(); }; return SixDofDragBehavior; }()); /***/ }), /***/ "./Behaviors/index.ts": /*!****************************!*\ !*** ./Behaviors/index.ts ***! \****************************/ /*! exports provided: AutoRotationBehavior, BouncingBehavior, FramingBehavior, AttachToBoxBehavior, FadeInOutBehavior, MultiPointerScaleBehavior, PointerDragBehavior, SixDofDragBehavior */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _Cameras_index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Cameras/index */ "./Behaviors/Cameras/index.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AutoRotationBehavior", function() { return _Cameras_index__WEBPACK_IMPORTED_MODULE_0__["AutoRotationBehavior"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BouncingBehavior", function() { return _Cameras_index__WEBPACK_IMPORTED_MODULE_0__["BouncingBehavior"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FramingBehavior", function() { return _Cameras_index__WEBPACK_IMPORTED_MODULE_0__["FramingBehavior"]; }); /* harmony import */ var _Meshes_index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Meshes/index */ "./Behaviors/Meshes/index.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AttachToBoxBehavior", function() { return _Meshes_index__WEBPACK_IMPORTED_MODULE_1__["AttachToBoxBehavior"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FadeInOutBehavior", function() { return _Meshes_index__WEBPACK_IMPORTED_MODULE_1__["FadeInOutBehavior"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiPointerScaleBehavior", function() { return _Meshes_index__WEBPACK_IMPORTED_MODULE_1__["MultiPointerScaleBehavior"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerDragBehavior", function() { return _Meshes_index__WEBPACK_IMPORTED_MODULE_1__["PointerDragBehavior"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SixDofDragBehavior", function() { return _Meshes_index__WEBPACK_IMPORTED_MODULE_1__["SixDofDragBehavior"]; }); /***/ }), /***/ "./Bones/bone.ts": /*!***********************!*\ !*** ./Bones/bone.ts ***! \***********************/ /*! exports provided: Bone */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Bone", function() { return Bone; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/arrayTools */ "./Misc/arrayTools.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts"); /** * Class used to store bone information * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons */ var Bone = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Bone, _super); /** * Create a new bone * @param name defines the bone name * @param skeleton defines the parent skeleton * @param parentBone defines the parent (can be null if the bone is the root) * @param localMatrix defines the local matrix * @param restPose defines the rest pose matrix * @param baseMatrix defines the base matrix * @param index defines index of the bone in the hiearchy */ function Bone( /** * defines the bone name */ name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) { if (parentBone === void 0) { parentBone = null; } if (localMatrix === void 0) { localMatrix = null; } if (restPose === void 0) { restPose = null; } if (baseMatrix === void 0) { baseMatrix = null; } if (index === void 0) { index = null; } var _this = _super.call(this, name, skeleton.getScene(), false) || this; _this.name = name; /** * Gets the list of child bones */ _this.children = new Array(); /** Gets the animations associated with this bone */ _this.animations = new Array(); /** * @hidden Internal only * Set this value to map this bone to a different index in the transform matrices * Set this value to -1 to exclude the bone from the transform matrices */ _this._index = null; _this._absoluteTransform = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); _this._invertedAbsoluteTransform = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); _this._scalingDeterminant = 1; _this._worldTransform = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); _this._needToDecompose = true; _this._needToCompose = false; /** @hidden */ _this._linkedTransformNode = null; _this._skeleton = skeleton; _this._localMatrix = localMatrix ? localMatrix.clone() : _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(); _this._restPose = restPose ? restPose : _this._localMatrix.clone(); _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone(); _this._index = index; skeleton.bones.push(_this); _this.setParent(parentBone, false); if (baseMatrix || localMatrix) { _this._updateDifferenceMatrix(); } return _this; } Object.defineProperty(Bone.prototype, "_matrix", { /** @hidden */ get: function () { this._compose(); return this._localMatrix; }, /** @hidden */ set: function (value) { this._localMatrix.copyFrom(value); this._needToDecompose = true; }, enumerable: true, configurable: true }); /** * Gets the current object class name. * @return the class name */ Bone.prototype.getClassName = function () { return "Bone"; }; // Members /** * Gets the parent skeleton * @returns a skeleton */ Bone.prototype.getSkeleton = function () { return this._skeleton; }; /** * Gets parent bone * @returns a bone or null if the bone is the root of the bone hierarchy */ Bone.prototype.getParent = function () { return this._parent; }; /** * Returns an array containing the root bones * @returns an array containing the root bones */ Bone.prototype.getChildren = function () { return this.children; }; /** * Sets the parent bone * @param parent defines the parent (can be null if the bone is the root) * @param updateDifferenceMatrix defines if the difference matrix must be updated */ Bone.prototype.setParent = function (parent, updateDifferenceMatrix) { if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; } if (this._parent === parent) { return; } if (this._parent) { var index = this._parent.children.indexOf(this); if (index !== -1) { this._parent.children.splice(index, 1); } } this._parent = parent; if (this._parent) { this._parent.children.push(this); } if (updateDifferenceMatrix) { this._updateDifferenceMatrix(); } this.markAsDirty(); }; /** * Gets the local matrix * @returns a matrix */ Bone.prototype.getLocalMatrix = function () { this._compose(); return this._localMatrix; }; /** * Gets the base matrix (initial matrix which remains unchanged) * @returns a matrix */ Bone.prototype.getBaseMatrix = function () { return this._baseMatrix; }; /** * Gets the rest pose matrix * @returns a matrix */ Bone.prototype.getRestPose = function () { return this._restPose; }; /** * Gets a matrix used to store world matrix (ie. the matrix sent to shaders) */ Bone.prototype.getWorldMatrix = function () { return this._worldTransform; }; /** * Sets the local matrix to rest pose matrix */ Bone.prototype.returnToRest = function () { this.updateMatrix(this._restPose.clone()); }; /** * Gets the inverse of the absolute transform matrix. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state) * @returns a matrix */ Bone.prototype.getInvertedAbsoluteTransform = function () { return this._invertedAbsoluteTransform; }; /** * Gets the absolute transform matrix (ie base matrix * parent world matrix) * @returns a matrix */ Bone.prototype.getAbsoluteTransform = function () { return this._absoluteTransform; }; /** * Links with the given transform node. * The local matrix of this bone is copied from the transform node every frame. * @param transformNode defines the transform node to link to */ Bone.prototype.linkTransformNode = function (transformNode) { if (this._linkedTransformNode) { this._skeleton._numBonesWithLinkedTransformNode--; } this._linkedTransformNode = transformNode; if (this._linkedTransformNode) { this._skeleton._numBonesWithLinkedTransformNode++; } }; Object.defineProperty(Bone.prototype, "position", { // Properties (matches AbstractMesh properties) /** Gets or sets current position (in local space) */ get: function () { this._decompose(); return this._localPosition; }, set: function (newPosition) { this._decompose(); this._localPosition.copyFrom(newPosition); this._markAsDirtyAndCompose(); }, enumerable: true, configurable: true }); Object.defineProperty(Bone.prototype, "rotation", { /** Gets or sets current rotation (in local space) */ get: function () { return this.getRotation(); }, set: function (newRotation) { this.setRotation(newRotation); }, enumerable: true, configurable: true }); Object.defineProperty(Bone.prototype, "rotationQuaternion", { /** Gets or sets current rotation quaternion (in local space) */ get: function () { this._decompose(); return this._localRotation; }, set: function (newRotation) { this.setRotationQuaternion(newRotation); }, enumerable: true, configurable: true }); Object.defineProperty(Bone.prototype, "scaling", { /** Gets or sets current scaling (in local space) */ get: function () { return this.getScale(); }, set: function (newScaling) { this.setScale(newScaling); }, enumerable: true, configurable: true }); Object.defineProperty(Bone.prototype, "animationPropertiesOverride", { /** * Gets the animation properties override */ get: function () { return this._skeleton.animationPropertiesOverride; }, enumerable: true, configurable: true }); // Methods Bone.prototype._decompose = function () { if (!this._needToDecompose) { return; } this._needToDecompose = false; if (!this._localScaling) { this._localScaling = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); this._localRotation = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].Zero(); this._localPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); } this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition); }; Bone.prototype._compose = function () { if (!this._needToCompose) { return; } this._needToCompose = false; _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix); }; /** * Update the base and local matrices * @param matrix defines the new base or local matrix * @param updateDifferenceMatrix defines if the difference matrix must be updated * @param updateLocalMatrix defines if the local matrix should be updated */ Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) { if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; } if (updateLocalMatrix === void 0) { updateLocalMatrix = true; } this._baseMatrix.copyFrom(matrix); if (updateDifferenceMatrix) { this._updateDifferenceMatrix(); } if (updateLocalMatrix) { this._localMatrix.copyFrom(matrix); this._markAsDirtyAndDecompose(); } else { this.markAsDirty(); } }; /** @hidden */ Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) { if (updateChildren === void 0) { updateChildren = true; } if (!rootMatrix) { rootMatrix = this._baseMatrix; } if (this._parent) { rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform); } else { this._absoluteTransform.copyFrom(rootMatrix); } this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform); if (updateChildren) { for (var index = 0; index < this.children.length; index++) { this.children[index]._updateDifferenceMatrix(); } } this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1); }; /** * Flag the bone as dirty (Forcing it to update everything) */ Bone.prototype.markAsDirty = function () { this._currentRenderId++; this._childUpdateId++; this._skeleton._markAsDirty(); }; Bone.prototype._markAsDirtyAndCompose = function () { this.markAsDirty(); this._needToCompose = true; }; Bone.prototype._markAsDirtyAndDecompose = function () { this.markAsDirty(); this._needToDecompose = true; }; /** * Translate the bone in local or world space * @param vec The amount to translate the bone * @param space The space that the translation is in * @param mesh The mesh that this bone is attached to. This is only used in world space */ Bone.prototype.translate = function (vec, space, mesh) { if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } var lm = this.getLocalMatrix(); if (space == _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL) { lm.addAtIndex(12, vec.x); lm.addAtIndex(13, vec.y); lm.addAtIndex(14, vec.z); } else { var wm = null; //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms() if (mesh) { wm = mesh.getWorldMatrix(); } this._skeleton.computeAbsoluteTransforms(); var tmat = Bone._tmpMats[0]; var tvec = Bone._tmpVecs[0]; if (this._parent) { if (mesh && wm) { tmat.copyFrom(this._parent.getAbsoluteTransform()); tmat.multiplyToRef(wm, tmat); } else { tmat.copyFrom(this._parent.getAbsoluteTransform()); } } tmat.setTranslationFromFloats(0, 0, 0); tmat.invert(); _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(vec, tmat, tvec); lm.addAtIndex(12, tvec.x); lm.addAtIndex(13, tvec.y); lm.addAtIndex(14, tvec.z); } this._markAsDirtyAndDecompose(); }; /** * Set the postion of the bone in local or world space * @param position The position to set the bone * @param space The space that the position is in * @param mesh The mesh that this bone is attached to. This is only used in world space */ Bone.prototype.setPosition = function (position, space, mesh) { if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } var lm = this.getLocalMatrix(); if (space == _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL) { lm.setTranslationFromFloats(position.x, position.y, position.z); } else { var wm = null; //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms() if (mesh) { wm = mesh.getWorldMatrix(); } this._skeleton.computeAbsoluteTransforms(); var tmat = Bone._tmpMats[0]; var vec = Bone._tmpVecs[0]; if (this._parent) { if (mesh && wm) { tmat.copyFrom(this._parent.getAbsoluteTransform()); tmat.multiplyToRef(wm, tmat); } else { tmat.copyFrom(this._parent.getAbsoluteTransform()); } } tmat.invert(); _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(position, tmat, vec); lm.setTranslationFromFloats(vec.x, vec.y, vec.z); } this._markAsDirtyAndDecompose(); }; /** * Set the absolute position of the bone (world space) * @param position The position to set the bone * @param mesh The mesh that this bone is attached to */ Bone.prototype.setAbsolutePosition = function (position, mesh) { this.setPosition(position, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].WORLD, mesh); }; /** * Scale the bone on the x, y and z axes (in local space) * @param x The amount to scale the bone on the x axis * @param y The amount to scale the bone on the y axis * @param z The amount to scale the bone on the z axis * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default) */ Bone.prototype.scale = function (x, y, z, scaleChildren) { if (scaleChildren === void 0) { scaleChildren = false; } var locMat = this.getLocalMatrix(); // Apply new scaling on top of current local matrix var scaleMat = Bone._tmpMats[0]; _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].ScalingToRef(x, y, z, scaleMat); scaleMat.multiplyToRef(locMat, locMat); // Invert scaling matrix and apply the inverse to all children scaleMat.invert(); for (var _i = 0, _a = this.children; _i < _a.length; _i++) { var child = _a[_i]; var cm = child.getLocalMatrix(); cm.multiplyToRef(scaleMat, cm); cm.multiplyAtIndex(12, x); cm.multiplyAtIndex(13, y); cm.multiplyAtIndex(14, z); child._markAsDirtyAndDecompose(); } this._markAsDirtyAndDecompose(); if (scaleChildren) { for (var _b = 0, _c = this.children; _b < _c.length; _b++) { var child = _c[_b]; child.scale(x, y, z, scaleChildren); } } }; /** * Set the bone scaling in local space * @param scale defines the scaling vector */ Bone.prototype.setScale = function (scale) { this._decompose(); this._localScaling.copyFrom(scale); this._markAsDirtyAndCompose(); }; /** * Gets the current scaling in local space * @returns the current scaling vector */ Bone.prototype.getScale = function () { this._decompose(); return this._localScaling; }; /** * Gets the current scaling in local space and stores it in a target vector * @param result defines the target vector */ Bone.prototype.getScaleToRef = function (result) { this._decompose(); result.copyFrom(this._localScaling); }; /** * Set the yaw, pitch, and roll of the bone in local or world space * @param yaw The rotation of the bone on the y axis * @param pitch The rotation of the bone on the x axis * @param roll The rotation of the bone on the z axis * @param space The space that the axes of rotation are in * @param mesh The mesh that this bone is attached to. This is only used in world space */ Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) { if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } if (space === _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL) { var quat = Bone._tmpQuat; _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].RotationYawPitchRollToRef(yaw, pitch, roll, quat); this.setRotationQuaternion(quat, space, mesh); return; } var rotMatInv = Bone._tmpMats[0]; if (!this._getNegativeRotationToRef(rotMatInv, mesh)) { return; } var rotMat = Bone._tmpMats[1]; _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].RotationYawPitchRollToRef(yaw, pitch, roll, rotMat); rotMatInv.multiplyToRef(rotMat, rotMat); this._rotateWithMatrix(rotMat, space, mesh); }; /** * Add a rotation to the bone on an axis in local or world space * @param axis The axis to rotate the bone on * @param amount The amount to rotate the bone * @param space The space that the axis is in * @param mesh The mesh that this bone is attached to. This is only used in world space */ Bone.prototype.rotate = function (axis, amount, space, mesh) { if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } var rmat = Bone._tmpMats[0]; rmat.setTranslationFromFloats(0, 0, 0); _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].RotationAxisToRef(axis, amount, rmat); this._rotateWithMatrix(rmat, space, mesh); }; /** * Set the rotation of the bone to a particular axis angle in local or world space * @param axis The axis to rotate the bone on * @param angle The angle that the bone should be rotated to * @param space The space that the axis is in * @param mesh The mesh that this bone is attached to. This is only used in world space */ Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) { if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } if (space === _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL) { var quat = Bone._tmpQuat; _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].RotationAxisToRef(axis, angle, quat); this.setRotationQuaternion(quat, space, mesh); return; } var rotMatInv = Bone._tmpMats[0]; if (!this._getNegativeRotationToRef(rotMatInv, mesh)) { return; } var rotMat = Bone._tmpMats[1]; _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].RotationAxisToRef(axis, angle, rotMat); rotMatInv.multiplyToRef(rotMat, rotMat); this._rotateWithMatrix(rotMat, space, mesh); }; /** * Set the euler rotation of the bone in local of world space * @param rotation The euler rotation that the bone should be set to * @param space The space that the rotation is in * @param mesh The mesh that this bone is attached to. This is only used in world space */ Bone.prototype.setRotation = function (rotation, space, mesh) { if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh); }; /** * Set the quaternion rotation of the bone in local of world space * @param quat The quaternion rotation that the bone should be set to * @param space The space that the rotation is in * @param mesh The mesh that this bone is attached to. This is only used in world space */ Bone.prototype.setRotationQuaternion = function (quat, space, mesh) { if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } if (space === _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL) { this._decompose(); this._localRotation.copyFrom(quat); this._markAsDirtyAndCompose(); return; } var rotMatInv = Bone._tmpMats[0]; if (!this._getNegativeRotationToRef(rotMatInv, mesh)) { return; } var rotMat = Bone._tmpMats[1]; _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].FromQuaternionToRef(quat, rotMat); rotMatInv.multiplyToRef(rotMat, rotMat); this._rotateWithMatrix(rotMat, space, mesh); }; /** * Set the rotation matrix of the bone in local of world space * @param rotMat The rotation matrix that the bone should be set to * @param space The space that the rotation is in * @param mesh The mesh that this bone is attached to. This is only used in world space */ Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) { if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } if (space === _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL) { var quat = Bone._tmpQuat; _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].FromRotationMatrixToRef(rotMat, quat); this.setRotationQuaternion(quat, space, mesh); return; } var rotMatInv = Bone._tmpMats[0]; if (!this._getNegativeRotationToRef(rotMatInv, mesh)) { return; } var rotMat2 = Bone._tmpMats[1]; rotMat2.copyFrom(rotMat); rotMatInv.multiplyToRef(rotMat, rotMat2); this._rotateWithMatrix(rotMat2, space, mesh); }; Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) { if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } var lmat = this.getLocalMatrix(); var lx = lmat.m[12]; var ly = lmat.m[13]; var lz = lmat.m[14]; var parent = this.getParent(); var parentScale = Bone._tmpMats[3]; var parentScaleInv = Bone._tmpMats[4]; if (parent && space == _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].WORLD) { if (mesh) { parentScale.copyFrom(mesh.getWorldMatrix()); parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale); } else { parentScale.copyFrom(parent.getAbsoluteTransform()); } parentScaleInv.copyFrom(parentScale); parentScaleInv.invert(); lmat.multiplyToRef(parentScale, lmat); lmat.multiplyToRef(rmat, lmat); lmat.multiplyToRef(parentScaleInv, lmat); } else { if (space == _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].WORLD && mesh) { parentScale.copyFrom(mesh.getWorldMatrix()); parentScaleInv.copyFrom(parentScale); parentScaleInv.invert(); lmat.multiplyToRef(parentScale, lmat); lmat.multiplyToRef(rmat, lmat); lmat.multiplyToRef(parentScaleInv, lmat); } else { lmat.multiplyToRef(rmat, lmat); } } lmat.setTranslationFromFloats(lx, ly, lz); this.computeAbsoluteTransforms(); this._markAsDirtyAndDecompose(); }; Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) { var scaleMatrix = Bone._tmpMats[2]; rotMatInv.copyFrom(this.getAbsoluteTransform()); if (mesh) { rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv); _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix); } rotMatInv.invert(); if (isNaN(rotMatInv.m[0])) { // Matrix failed to invert. // This can happen if scale is zero for example. return false; } scaleMatrix.multiplyAtIndex(0, this._scalingDeterminant); rotMatInv.multiplyToRef(scaleMatrix, rotMatInv); return true; }; /** * Get the position of the bone in local or world space * @param space The space that the returned position is in * @param mesh The mesh that this bone is attached to. This is only used in world space * @returns The position of the bone */ Bone.prototype.getPosition = function (space, mesh) { if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } if (mesh === void 0) { mesh = null; } var pos = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); this.getPositionToRef(space, mesh, pos); return pos; }; /** * Copy the position of the bone to a vector3 in local or world space * @param space The space that the returned position is in * @param mesh The mesh that this bone is attached to. This is only used in world space * @param result The vector3 to copy the position to */ Bone.prototype.getPositionToRef = function (space, mesh, result) { if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } if (space == _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL) { var lm = this.getLocalMatrix(); result.x = lm.m[12]; result.y = lm.m[13]; result.z = lm.m[14]; } else { var wm = null; //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms() if (mesh) { wm = mesh.getWorldMatrix(); } this._skeleton.computeAbsoluteTransforms(); var tmat = Bone._tmpMats[0]; if (mesh && wm) { tmat.copyFrom(this.getAbsoluteTransform()); tmat.multiplyToRef(wm, tmat); } else { tmat = this.getAbsoluteTransform(); } result.x = tmat.m[12]; result.y = tmat.m[13]; result.z = tmat.m[14]; } }; /** * Get the absolute position of the bone (world space) * @param mesh The mesh that this bone is attached to * @returns The absolute position of the bone */ Bone.prototype.getAbsolutePosition = function (mesh) { if (mesh === void 0) { mesh = null; } var pos = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); this.getPositionToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].WORLD, mesh, pos); return pos; }; /** * Copy the absolute position of the bone (world space) to the result param * @param mesh The mesh that this bone is attached to * @param result The vector3 to copy the absolute position to */ Bone.prototype.getAbsolutePositionToRef = function (mesh, result) { this.getPositionToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].WORLD, mesh, result); }; /** * Compute the absolute transforms of this bone and its children */ Bone.prototype.computeAbsoluteTransforms = function () { this._compose(); if (this._parent) { this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform); } else { this._absoluteTransform.copyFrom(this._localMatrix); var poseMatrix = this._skeleton.getPoseMatrix(); if (poseMatrix) { this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform); } } var children = this.children; var len = children.length; for (var i = 0; i < len; i++) { children[i].computeAbsoluteTransforms(); } }; /** * Get the world direction from an axis that is in the local space of the bone * @param localAxis The local direction that is used to compute the world direction * @param mesh The mesh that this bone is attached to * @returns The world direction */ Bone.prototype.getDirection = function (localAxis, mesh) { if (mesh === void 0) { mesh = null; } var result = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); this.getDirectionToRef(localAxis, mesh, result); return result; }; /** * Copy the world direction to a vector3 from an axis that is in the local space of the bone * @param localAxis The local direction that is used to compute the world direction * @param mesh The mesh that this bone is attached to * @param result The vector3 that the world direction will be copied to */ Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) { if (mesh === void 0) { mesh = null; } var wm = null; //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms() if (mesh) { wm = mesh.getWorldMatrix(); } this._skeleton.computeAbsoluteTransforms(); var mat = Bone._tmpMats[0]; mat.copyFrom(this.getAbsoluteTransform()); if (mesh && wm) { mat.multiplyToRef(wm, mat); } _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformNormalToRef(localAxis, mat, result); result.normalize(); }; /** * Get the euler rotation of the bone in local or world space * @param space The space that the rotation should be in * @param mesh The mesh that this bone is attached to. This is only used in world space * @returns The euler rotation */ Bone.prototype.getRotation = function (space, mesh) { if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } if (mesh === void 0) { mesh = null; } var result = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); this.getRotationToRef(space, mesh, result); return result; }; /** * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space * @param space The space that the rotation should be in * @param mesh The mesh that this bone is attached to. This is only used in world space * @param result The vector3 that the rotation should be copied to */ Bone.prototype.getRotationToRef = function (space, mesh, result) { if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } if (mesh === void 0) { mesh = null; } var quat = Bone._tmpQuat; this.getRotationQuaternionToRef(space, mesh, quat); quat.toEulerAnglesToRef(result); }; /** * Get the quaternion rotation of the bone in either local or world space * @param space The space that the rotation should be in * @param mesh The mesh that this bone is attached to. This is only used in world space * @returns The quaternion rotation */ Bone.prototype.getRotationQuaternion = function (space, mesh) { if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } if (mesh === void 0) { mesh = null; } var result = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].Identity(); this.getRotationQuaternionToRef(space, mesh, result); return result; }; /** * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space * @param space The space that the rotation should be in * @param mesh The mesh that this bone is attached to. This is only used in world space * @param result The quaternion that the rotation should be copied to */ Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) { if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } if (mesh === void 0) { mesh = null; } if (space == _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL) { this._decompose(); result.copyFrom(this._localRotation); } else { var mat = Bone._tmpMats[0]; var amat = this.getAbsoluteTransform(); if (mesh) { amat.multiplyToRef(mesh.getWorldMatrix(), mat); } else { mat.copyFrom(amat); } mat.multiplyAtIndex(0, this._scalingDeterminant); mat.multiplyAtIndex(1, this._scalingDeterminant); mat.multiplyAtIndex(2, this._scalingDeterminant); mat.decompose(undefined, result, undefined); } }; /** * Get the rotation matrix of the bone in local or world space * @param space The space that the rotation should be in * @param mesh The mesh that this bone is attached to. This is only used in world space * @returns The rotation matrix */ Bone.prototype.getRotationMatrix = function (space, mesh) { if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } var result = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(); this.getRotationMatrixToRef(space, mesh, result); return result; }; /** * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space * @param space The space that the rotation should be in * @param mesh The mesh that this bone is attached to. This is only used in world space * @param result The quaternion that the rotation should be copied to */ Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) { if (space === void 0) { space = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } if (space == _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL) { this.getLocalMatrix().getRotationMatrixToRef(result); } else { var mat = Bone._tmpMats[0]; var amat = this.getAbsoluteTransform(); if (mesh) { amat.multiplyToRef(mesh.getWorldMatrix(), mat); } else { mat.copyFrom(amat); } mat.multiplyAtIndex(0, this._scalingDeterminant); mat.multiplyAtIndex(1, this._scalingDeterminant); mat.multiplyAtIndex(2, this._scalingDeterminant); mat.getRotationMatrixToRef(result); } }; /** * Get the world position of a point that is in the local space of the bone * @param position The local position * @param mesh The mesh that this bone is attached to * @returns The world position */ Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) { if (mesh === void 0) { mesh = null; } var result = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); this.getAbsolutePositionFromLocalToRef(position, mesh, result); return result; }; /** * Get the world position of a point that is in the local space of the bone and copy it to the result param * @param position The local position * @param mesh The mesh that this bone is attached to * @param result The vector3 that the world position should be copied to */ Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) { if (mesh === void 0) { mesh = null; } var wm = null; //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms() if (mesh) { wm = mesh.getWorldMatrix(); } this._skeleton.computeAbsoluteTransforms(); var tmat = Bone._tmpMats[0]; if (mesh && wm) { tmat.copyFrom(this.getAbsoluteTransform()); tmat.multiplyToRef(wm, tmat); } else { tmat = this.getAbsoluteTransform(); } _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(position, tmat, result); }; /** * Get the local position of a point that is in world space * @param position The world position * @param mesh The mesh that this bone is attached to * @returns The local position */ Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) { if (mesh === void 0) { mesh = null; } var result = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); this.getLocalPositionFromAbsoluteToRef(position, mesh, result); return result; }; /** * Get the local position of a point that is in world space and copy it to the result param * @param position The world position * @param mesh The mesh that this bone is attached to * @param result The vector3 that the local position should be copied to */ Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) { if (mesh === void 0) { mesh = null; } var wm = null; //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms() if (mesh) { wm = mesh.getWorldMatrix(); } this._skeleton.computeAbsoluteTransforms(); var tmat = Bone._tmpMats[0]; tmat.copyFrom(this.getAbsoluteTransform()); if (mesh && wm) { tmat.multiplyToRef(wm, tmat); } tmat.invert(); _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(position, tmat, result); }; Bone._tmpVecs = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_2__["ArrayTools"].BuildArray(2, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero); Bone._tmpQuat = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].Identity(); Bone._tmpMats = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_2__["ArrayTools"].BuildArray(5, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity); return Bone; }(_node__WEBPACK_IMPORTED_MODULE_3__["Node"])); /***/ }), /***/ "./Bones/boneIKController.ts": /*!***********************************!*\ !*** ./Bones/boneIKController.ts ***! \***********************************/ /*! exports provided: BoneIKController */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoneIKController", function() { return BoneIKController; }); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /** * Class used to apply inverse kinematics to bones * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller */ var BoneIKController = /** @class */ (function () { /** * Creates a new BoneIKController * @param mesh defines the mesh to control * @param bone defines the bone to control * @param options defines options to set up the controller */ function BoneIKController(mesh, bone, options) { /** * Gets or sets the target position */ this.targetPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); /** * Gets or sets the pole target position */ this.poleTargetPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); /** * Gets or sets the pole target local offset */ this.poleTargetLocalOffset = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); /** * Gets or sets the pole angle */ this.poleAngle = 0; /** * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp) */ this.slerpAmount = 1; this._bone1Quat = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Identity(); this._bone1Mat = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Identity(); this._bone2Ang = Math.PI; this._maxAngle = Math.PI; this._rightHandedSystem = false; this._bendAxis = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Right(); this._slerping = false; this._adjustRoll = 0; this._bone2 = bone; this._bone1 = bone.getParent(); if (!this._bone1) { return; } this.mesh = mesh; var bonePos = bone.getPosition(); if (bone.getAbsoluteTransform().determinant() > 0) { this._rightHandedSystem = true; this._bendAxis.x = 0; this._bendAxis.y = 0; this._bendAxis.z = -1; if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) { this._adjustRoll = Math.PI * .5; this._bendAxis.z = 1; } } if (this._bone1.length) { var boneScale1 = this._bone1.getScale(); var boneScale2 = this._bone2.getScale(); this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y; this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y; } else if (this._bone1.children[0]) { mesh.computeWorldMatrix(true); var pos1 = this._bone2.children[0].getAbsolutePosition(mesh); var pos2 = this._bone2.getAbsolutePosition(mesh); var pos3 = this._bone1.getAbsolutePosition(mesh); this._bone1Length = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Distance(pos1, pos2); this._bone2Length = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Distance(pos2, pos3); } this._bone1.getRotationMatrixToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Space"].WORLD, mesh, this._bone1Mat); this.maxAngle = Math.PI; if (options) { if (options.targetMesh) { this.targetMesh = options.targetMesh; this.targetMesh.computeWorldMatrix(true); } if (options.poleTargetMesh) { this.poleTargetMesh = options.poleTargetMesh; this.poleTargetMesh.computeWorldMatrix(true); } else if (options.poleTargetBone) { this.poleTargetBone = options.poleTargetBone; } else if (this._bone1.getParent()) { this.poleTargetBone = this._bone1.getParent(); } if (options.poleTargetLocalOffset) { this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset); } if (options.poleAngle) { this.poleAngle = options.poleAngle; } if (options.bendAxis) { this._bendAxis.copyFrom(options.bendAxis); } if (options.maxAngle) { this.maxAngle = options.maxAngle; } if (options.slerpAmount) { this.slerpAmount = options.slerpAmount; } } } Object.defineProperty(BoneIKController.prototype, "maxAngle", { /** * Gets or sets maximum allowed angle */ get: function () { return this._maxAngle; }, set: function (value) { this._setMaxAngle(value); }, enumerable: true, configurable: true }); BoneIKController.prototype._setMaxAngle = function (ang) { if (ang < 0) { ang = 0; } if (ang > Math.PI || ang == undefined) { ang = Math.PI; } this._maxAngle = ang; var a = this._bone1Length; var b = this._bone2Length; this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang)); }; /** * Force the controller to update the bones */ BoneIKController.prototype.update = function () { var bone1 = this._bone1; if (!bone1) { return; } var target = this.targetPosition; var poleTarget = this.poleTargetPosition; var mat1 = BoneIKController._tmpMats[0]; var mat2 = BoneIKController._tmpMats[1]; if (this.targetMesh) { target.copyFrom(this.targetMesh.getAbsolutePosition()); } if (this.poleTargetBone) { this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget); } else if (this.poleTargetMesh) { _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget); } var bonePos = BoneIKController._tmpVecs[0]; var zaxis = BoneIKController._tmpVecs[1]; var xaxis = BoneIKController._tmpVecs[2]; var yaxis = BoneIKController._tmpVecs[3]; var upAxis = BoneIKController._tmpVecs[4]; var _tmpQuat = BoneIKController._tmpQuat; bone1.getAbsolutePositionToRef(this.mesh, bonePos); poleTarget.subtractToRef(bonePos, upAxis); if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) { upAxis.y = 1; } else { upAxis.normalize(); } target.subtractToRef(bonePos, yaxis); yaxis.normalize(); _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].CrossToRef(yaxis, upAxis, zaxis); zaxis.normalize(); _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].CrossToRef(yaxis, zaxis, xaxis); xaxis.normalize(); _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1); var a = this._bone1Length; var b = this._bone2Length; var c = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Distance(bonePos, target); if (this._maxReach > 0) { c = Math.min(this._maxReach, c); } var acosa = (b * b + c * c - a * a) / (2 * b * c); var acosb = (c * c + a * a - b * b) / (2 * c * a); if (acosa > 1) { acosa = 1; } if (acosb > 1) { acosb = 1; } if (acosa < -1) { acosa = -1; } if (acosb < -1) { acosb = -1; } var angA = Math.acos(acosa); var angB = Math.acos(acosb); var angC = -angA - angB; if (this._rightHandedSystem) { _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2); mat2.multiplyToRef(mat1, mat1); _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].RotationAxisToRef(this._bendAxis, angB, mat2); mat2.multiplyToRef(mat1, mat1); } else { var _tmpVec = BoneIKController._tmpVecs[5]; _tmpVec.copyFrom(this._bendAxis); _tmpVec.x *= -1; _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].RotationAxisToRef(_tmpVec, -angB, mat2); mat2.multiplyToRef(mat1, mat1); } if (this.poleAngle) { _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].RotationAxisToRef(yaxis, this.poleAngle, mat2); mat1.multiplyToRef(mat2, mat1); } if (this._bone1) { if (this.slerpAmount < 1) { if (!this._slerping) { _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat); } _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromRotationMatrixToRef(mat1, _tmpQuat); _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat); angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount; this._bone1.setRotationQuaternion(this._bone1Quat, _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Space"].WORLD, this.mesh); this._slerping = true; } else { this._bone1.setRotationMatrix(mat1, _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Space"].WORLD, this.mesh); this._bone1Mat.copyFrom(mat1); this._slerping = false; } } this._bone2.setAxisAngle(this._bendAxis, angC, _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Space"].LOCAL); this._bone2Ang = angC; }; BoneIKController._tmpVecs = [_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero()]; BoneIKController._tmpQuat = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Identity(); BoneIKController._tmpMats = [_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Identity(), _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Identity()]; return BoneIKController; }()); /***/ }), /***/ "./Bones/boneLookController.ts": /*!*************************************!*\ !*** ./Bones/boneLookController.ts ***! \*************************************/ /*! exports provided: BoneLookController */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoneLookController", function() { return BoneLookController; }); /* harmony import */ var _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/arrayTools */ "./Misc/arrayTools.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /** * Class used to make a bone look toward a point in space * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller */ var BoneLookController = /** @class */ (function () { /** * Create a BoneLookController * @param mesh the mesh that the bone belongs to * @param bone the bone that will be looking to the target * @param target the target Vector3 to look at * @param options optional settings: * * maxYaw: the maximum angle the bone will yaw to * * minYaw: the minimum angle the bone will yaw to * * maxPitch: the maximum angle the bone will pitch to * * minPitch: the minimum angle the bone will yaw to * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target. * * upAxis: the up axis of the coordinate system * * upAxisSpace: the space that the up axis is in - Space.BONE, Space.LOCAL (default), or Space.WORLD. * * yawAxis: set yawAxis if the bone does not yaw on the y axis * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis * * adjustYaw: used to make an adjustment to the yaw of the bone * * adjustPitch: used to make an adjustment to the pitch of the bone * * adjustRoll: used to make an adjustment to the roll of the bone **/ function BoneLookController(mesh, bone, target, options) { /** * The up axis of the coordinate system that is used when the bone is rotated */ this.upAxis = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Up(); /** * The space that the up axis is in - Space.BONE, Space.LOCAL (default), or Space.WORLD */ this.upAxisSpace = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; /** * Used to make an adjustment to the yaw of the bone */ this.adjustYaw = 0; /** * Used to make an adjustment to the pitch of the bone */ this.adjustPitch = 0; /** * Used to make an adjustment to the roll of the bone */ this.adjustRoll = 0; /** * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp) */ this.slerpAmount = 1; this._boneQuat = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].Identity(); this._slerping = false; this._firstFrameSkipped = false; this._fowardAxis = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Forward(); this.mesh = mesh; this.bone = bone; this.target = target; if (options) { if (options.adjustYaw) { this.adjustYaw = options.adjustYaw; } if (options.adjustPitch) { this.adjustPitch = options.adjustPitch; } if (options.adjustRoll) { this.adjustRoll = options.adjustRoll; } if (options.maxYaw != null) { this.maxYaw = options.maxYaw; } else { this.maxYaw = Math.PI; } if (options.minYaw != null) { this.minYaw = options.minYaw; } else { this.minYaw = -Math.PI; } if (options.maxPitch != null) { this.maxPitch = options.maxPitch; } else { this.maxPitch = Math.PI; } if (options.minPitch != null) { this.minPitch = options.minPitch; } else { this.minPitch = -Math.PI; } if (options.slerpAmount != null) { this.slerpAmount = options.slerpAmount; } if (options.upAxis != null) { this.upAxis = options.upAxis; } if (options.upAxisSpace != null) { this.upAxisSpace = options.upAxisSpace; } if (options.yawAxis != null || options.pitchAxis != null) { var newYawAxis = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Axis"].Y; var newPitchAxis = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Axis"].X; if (options.yawAxis != null) { newYawAxis = options.yawAxis.clone(); newYawAxis.normalize(); } if (options.pitchAxis != null) { newPitchAxis = options.pitchAxis.clone(); newPitchAxis.normalize(); } var newRollAxis = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(newPitchAxis, newYawAxis); this._transformYawPitch = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(); _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch); this._transformYawPitchInv = this._transformYawPitch.clone(); this._transformYawPitch.invert(); } } if (!bone.getParent() && this.upAxisSpace == _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].BONE) { this.upAxisSpace = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL; } } Object.defineProperty(BoneLookController.prototype, "minYaw", { /** * Gets or sets the minimum yaw angle that the bone can look to */ get: function () { return this._minYaw; }, set: function (value) { this._minYaw = value; this._minYawSin = Math.sin(value); this._minYawCos = Math.cos(value); if (this._maxYaw != null) { this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw; this._yawRange = this._maxYaw - this._minYaw; } }, enumerable: true, configurable: true }); Object.defineProperty(BoneLookController.prototype, "maxYaw", { /** * Gets or sets the maximum yaw angle that the bone can look to */ get: function () { return this._maxYaw; }, set: function (value) { this._maxYaw = value; this._maxYawSin = Math.sin(value); this._maxYawCos = Math.cos(value); if (this._minYaw != null) { this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw; this._yawRange = this._maxYaw - this._minYaw; } }, enumerable: true, configurable: true }); Object.defineProperty(BoneLookController.prototype, "minPitch", { /** * Gets or sets the minimum pitch angle that the bone can look to */ get: function () { return this._minPitch; }, set: function (value) { this._minPitch = value; this._minPitchTan = Math.tan(value); }, enumerable: true, configurable: true }); Object.defineProperty(BoneLookController.prototype, "maxPitch", { /** * Gets or sets the maximum pitch angle that the bone can look to */ get: function () { return this._maxPitch; }, set: function (value) { this._maxPitch = value; this._maxPitchTan = Math.tan(value); }, enumerable: true, configurable: true }); /** * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()) */ BoneLookController.prototype.update = function () { //skip the first frame when slerping so that the mesh rotation is correct if (this.slerpAmount < 1 && !this._firstFrameSkipped) { this._firstFrameSkipped = true; return; } var bone = this.bone; var bonePos = BoneLookController._tmpVecs[0]; bone.getAbsolutePositionToRef(this.mesh, bonePos); var target = this.target; var _tmpMat1 = BoneLookController._tmpMats[0]; var _tmpMat2 = BoneLookController._tmpMats[1]; var mesh = this.mesh; var parentBone = bone.getParent(); var upAxis = BoneLookController._tmpVecs[1]; upAxis.copyFrom(this.upAxis); if (this.upAxisSpace == _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].BONE && parentBone) { if (this._transformYawPitch) { _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis); } parentBone.getDirectionToRef(upAxis, this.mesh, upAxis); } else if (this.upAxisSpace == _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL) { mesh.getDirectionToRef(upAxis, upAxis); if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) { upAxis.normalize(); } } var checkYaw = false; var checkPitch = false; if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) { checkYaw = true; } if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) { checkPitch = true; } if (checkYaw || checkPitch) { var spaceMat = BoneLookController._tmpMats[2]; var spaceMatInv = BoneLookController._tmpMats[3]; if (this.upAxisSpace == _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].BONE && upAxis.y == 1 && parentBone) { parentBone.getRotationMatrixToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].WORLD, this.mesh, spaceMat); } else if (this.upAxisSpace == _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL && upAxis.y == 1 && !parentBone) { spaceMat.copyFrom(mesh.getWorldMatrix()); } else { var forwardAxis = BoneLookController._tmpVecs[2]; forwardAxis.copyFrom(this._fowardAxis); if (this._transformYawPitch) { _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis); } if (parentBone) { parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis); } else { mesh.getDirectionToRef(forwardAxis, forwardAxis); } var rightAxis = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(upAxis, forwardAxis); rightAxis.normalize(); var forwardAxis = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(rightAxis, upAxis); _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat); } spaceMat.invertToRef(spaceMatInv); var xzlen = null; if (checkPitch) { var localTarget = BoneLookController._tmpVecs[3]; target.subtractToRef(bonePos, localTarget); _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget); xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z); var pitch = Math.atan2(localTarget.y, xzlen); var newPitch = pitch; if (pitch > this._maxPitch) { localTarget.y = this._maxPitchTan * xzlen; newPitch = this._maxPitch; } else if (pitch < this._minPitch) { localTarget.y = this._minPitchTan * xzlen; newPitch = this._minPitch; } if (pitch != newPitch) { _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(localTarget, spaceMat, localTarget); localTarget.addInPlace(bonePos); target = localTarget; } } if (checkYaw) { var localTarget = BoneLookController._tmpVecs[4]; target.subtractToRef(bonePos, localTarget); _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget); var yaw = Math.atan2(localTarget.x, localTarget.z); var newYaw = yaw; if (yaw > this._maxYaw || yaw < this._minYaw) { if (xzlen == null) { xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z); } if (this._yawRange > Math.PI) { if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) { localTarget.z = this._maxYawCos * xzlen; localTarget.x = this._maxYawSin * xzlen; newYaw = this._maxYaw; } else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) { localTarget.z = this._minYawCos * xzlen; localTarget.x = this._minYawSin * xzlen; newYaw = this._minYaw; } } else { if (yaw > this._maxYaw) { localTarget.z = this._maxYawCos * xzlen; localTarget.x = this._maxYawSin * xzlen; newYaw = this._maxYaw; } else if (yaw < this._minYaw) { localTarget.z = this._minYawCos * xzlen; localTarget.x = this._minYawSin * xzlen; newYaw = this._minYaw; } } } if (this._slerping && this._yawRange > Math.PI) { //are we going to be crossing into the min/max region? var boneFwd = BoneLookController._tmpVecs[8]; boneFwd.copyFrom(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Axis"].Z); if (this._transformYawPitch) { _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd); } var boneRotMat = BoneLookController._tmpMats[4]; this._boneQuat.toRotationMatrix(boneRotMat); this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat); _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd); _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd); var boneYaw = Math.atan2(boneFwd.x, boneFwd.z); var angBtwTar = this._getAngleBetween(boneYaw, yaw); var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint); if (angBtwTar > angBtwMidYaw) { if (xzlen == null) { xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z); } var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw); var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw); if (angBtwMin < angBtwMax) { newYaw = boneYaw + Math.PI * .75; localTarget.z = Math.cos(newYaw) * xzlen; localTarget.x = Math.sin(newYaw) * xzlen; } else { newYaw = boneYaw - Math.PI * .75; localTarget.z = Math.cos(newYaw) * xzlen; localTarget.x = Math.sin(newYaw) * xzlen; } } } if (yaw != newYaw) { _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(localTarget, spaceMat, localTarget); localTarget.addInPlace(bonePos); target = localTarget; } } } var zaxis = BoneLookController._tmpVecs[5]; var xaxis = BoneLookController._tmpVecs[6]; var yaxis = BoneLookController._tmpVecs[7]; var _tmpQuat = BoneLookController._tmpQuat; target.subtractToRef(bonePos, zaxis); zaxis.normalize(); _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].CrossToRef(upAxis, zaxis, xaxis); xaxis.normalize(); _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].CrossToRef(zaxis, xaxis, yaxis); yaxis.normalize(); _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1); if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) { return; } if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) { return; } if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) { return; } if (this.adjustYaw || this.adjustPitch || this.adjustRoll) { _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2); _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1); } if (this.slerpAmount < 1) { if (!this._slerping) { this.bone.getRotationQuaternionToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].WORLD, this.mesh, this._boneQuat); } if (this._transformYawPitch) { this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1); } _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].FromRotationMatrixToRef(_tmpMat1, _tmpQuat); _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat); this.bone.setRotationQuaternion(this._boneQuat, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].WORLD, this.mesh); this._slerping = true; } else { if (this._transformYawPitch) { this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1); } this.bone.setRotationMatrix(_tmpMat1, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Space"].WORLD, this.mesh); this._slerping = false; } }; BoneLookController.prototype._getAngleDiff = function (ang1, ang2) { var angDiff = ang2 - ang1; angDiff %= Math.PI * 2; if (angDiff > Math.PI) { angDiff -= Math.PI * 2; } else if (angDiff < -Math.PI) { angDiff += Math.PI * 2; } return angDiff; }; BoneLookController.prototype._getAngleBetween = function (ang1, ang2) { ang1 %= (2 * Math.PI); ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1; ang2 %= (2 * Math.PI); ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2; var ab = 0; if (ang1 < ang2) { ab = ang2 - ang1; } else { ab = ang1 - ang2; } if (ab > Math.PI) { ab = Math.PI * 2 - ab; } return ab; }; BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) { ang %= (2 * Math.PI); ang = (ang < 0) ? ang + (2 * Math.PI) : ang; ang1 %= (2 * Math.PI); ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1; ang2 %= (2 * Math.PI); ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2; if (ang1 < ang2) { if (ang > ang1 && ang < ang2) { return true; } } else { if (ang > ang2 && ang < ang1) { return true; } } return false; }; BoneLookController._tmpVecs = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(10, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero); BoneLookController._tmpQuat = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].Identity(); BoneLookController._tmpMats = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(5, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity); return BoneLookController; }()); /***/ }), /***/ "./Bones/index.ts": /*!************************!*\ !*** ./Bones/index.ts ***! \************************/ /*! exports provided: Bone, BoneIKController, BoneLookController, Skeleton */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _bone__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bone */ "./Bones/bone.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Bone", function() { return _bone__WEBPACK_IMPORTED_MODULE_0__["Bone"]; }); /* harmony import */ var _boneIKController__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./boneIKController */ "./Bones/boneIKController.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoneIKController", function() { return _boneIKController__WEBPACK_IMPORTED_MODULE_1__["BoneIKController"]; }); /* harmony import */ var _boneLookController__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./boneLookController */ "./Bones/boneLookController.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoneLookController", function() { return _boneLookController__WEBPACK_IMPORTED_MODULE_2__["BoneLookController"]; }); /* harmony import */ var _skeleton__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./skeleton */ "./Bones/skeleton.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Skeleton", function() { return _skeleton__WEBPACK_IMPORTED_MODULE_3__["Skeleton"]; }); /***/ }), /***/ "./Bones/skeleton.ts": /*!***************************!*\ !*** ./Bones/skeleton.ts ***! \***************************/ /*! exports provided: Skeleton */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Skeleton", function() { return Skeleton; }); /* harmony import */ var _bone__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bone */ "./Bones/bone.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Materials_Textures_rawTexture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Materials/Textures/rawTexture */ "./Materials/Textures/rawTexture.ts"); /* harmony import */ var _Animations_animation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Animations/animation */ "./Animations/animation.ts"); /* harmony import */ var _Animations_animationRange__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Animations/animationRange */ "./Animations/animationRange.ts"); /* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Misc_deepCopier__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Misc/deepCopier */ "./Misc/deepCopier.ts"); /** * Class used to handle skinning animations * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons */ var Skeleton = /** @class */ (function () { /** * Creates a new skeleton * @param name defines the skeleton name * @param id defines the skeleton Id * @param scene defines the hosting scene */ function Skeleton( /** defines the skeleton name */ name, /** defines the skeleton Id */ id, scene) { this.name = name; this.id = id; /** * Defines the list of child bones */ this.bones = new Array(); /** * Defines a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value) */ this.needInitialSkinMatrix = false; /** * Defines a mesh that override the matrix used to get the world matrix (null by default). */ this.overrideMesh = null; this._isDirty = true; this._meshesWithPoseMatrix = new Array(); this._identity = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Identity(); this._ranges = {}; this._lastAbsoluteTransformsUpdateId = -1; this._canUseTextureForBones = false; this._uniqueId = 0; /** @hidden */ this._numBonesWithLinkedTransformNode = 0; /** * Specifies if the skeleton should be serialized */ this.doNotSerialize = false; this._useTextureToStoreBoneMatrices = true; this._animationPropertiesOverride = null; // Events /** * An observable triggered before computing the skeleton's matrices */ this.onBeforeComputeObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); this.bones = []; this._scene = scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_6__["EngineStore"].LastCreatedScene; this._uniqueId = this._scene.getUniqueId(); this._scene.addSkeleton(this); //make sure it will recalculate the matrix next time prepare is called. this._isDirty = true; var engineCaps = this._scene.getEngine().getCaps(); this._canUseTextureForBones = engineCaps.textureFloat && engineCaps.maxVertexTextureImageUnits > 0; } Object.defineProperty(Skeleton.prototype, "useTextureToStoreBoneMatrices", { /** * Gets or sets a boolean indicating that bone matrices should be stored as a texture instead of using shader uniforms (default is true). * Please note that this option is not available when needInitialSkinMatrix === true or if the hardware does not support it */ get: function () { return this._useTextureToStoreBoneMatrices; }, set: function (value) { this._useTextureToStoreBoneMatrices = value; this._markAsDirty(); }, enumerable: true, configurable: true }); Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", { /** * Gets or sets the animation properties override */ get: function () { if (!this._animationPropertiesOverride) { return this._scene.animationPropertiesOverride; } return this._animationPropertiesOverride; }, set: function (value) { this._animationPropertiesOverride = value; }, enumerable: true, configurable: true }); Object.defineProperty(Skeleton.prototype, "isUsingTextureForMatrices", { /** * Gets a boolean indicating that the skeleton effectively stores matrices into a texture */ get: function () { return this.useTextureToStoreBoneMatrices && this._canUseTextureForBones && !this.needInitialSkinMatrix; }, enumerable: true, configurable: true }); Object.defineProperty(Skeleton.prototype, "uniqueId", { /** * Gets the unique ID of this skeleton */ get: function () { return this._uniqueId; }, enumerable: true, configurable: true }); /** * Gets the current object class name. * @return the class name */ Skeleton.prototype.getClassName = function () { return "Skeleton"; }; /** * Returns an array containing the root bones * @returns an array containing the root bones */ Skeleton.prototype.getChildren = function () { return this.bones.filter(function (b) { return !b.getParent(); }); }; // Members /** * Gets the list of transform matrices to send to shaders (one matrix per bone) * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true) * @returns a Float32Array containing matrices data */ Skeleton.prototype.getTransformMatrices = function (mesh) { if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) { return mesh._bonesTransformMatrices; } if (!this._transformMatrices) { this.prepare(); } return this._transformMatrices; }; /** * Gets the list of transform matrices to send to shaders inside a texture (one matrix per bone) * @returns a raw texture containing the data */ Skeleton.prototype.getTransformMatrixTexture = function () { return this._transformMatrixTexture; }; /** * Gets the current hosting scene * @returns a scene object */ Skeleton.prototype.getScene = function () { return this._scene; }; // Methods /** * Gets a string representing the current skeleton data * @param fullDetails defines a boolean indicating if we want a verbose version * @returns a string representing the current skeleton data */ Skeleton.prototype.toString = function (fullDetails) { var ret = "Name: " + this.name + ", nBones: " + this.bones.length; ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none"); if (fullDetails) { ret += ", Ranges: {"; var first = true; for (var name_1 in this._ranges) { if (first) { ret += ", "; first = false; } ret += name_1; } ret += "}"; } return ret; }; /** * Get bone's index searching by name * @param name defines bone's name to search for * @return the indice of the bone. Returns -1 if not found */ Skeleton.prototype.getBoneIndexByName = function (name) { for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) { if (this.bones[boneIndex].name === name) { return boneIndex; } } return -1; }; /** * Creater a new animation range * @param name defines the name of the range * @param from defines the start key * @param to defines the end key */ Skeleton.prototype.createAnimationRange = function (name, from, to) { // check name not already in use if (!this._ranges[name]) { this._ranges[name] = new _Animations_animationRange__WEBPACK_IMPORTED_MODULE_5__["AnimationRange"](name, from, to); for (var i = 0, nBones = this.bones.length; i < nBones; i++) { if (this.bones[i].animations[0]) { this.bones[i].animations[0].createRange(name, from, to); } } } }; /** * Delete a specific animation range * @param name defines the name of the range * @param deleteFrames defines if frames must be removed as well */ Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) { if (deleteFrames === void 0) { deleteFrames = true; } for (var i = 0, nBones = this.bones.length; i < nBones; i++) { if (this.bones[i].animations[0]) { this.bones[i].animations[0].deleteRange(name, deleteFrames); } } this._ranges[name] = null; // said much faster than 'delete this._range[name]' }; /** * Gets a specific animation range * @param name defines the name of the range to look for * @returns the requested animation range or null if not found */ Skeleton.prototype.getAnimationRange = function (name) { return this._ranges[name]; }; /** * Gets the list of all animation ranges defined on this skeleton * @returns an array */ Skeleton.prototype.getAnimationRanges = function () { var animationRanges = []; var name; for (name in this._ranges) { animationRanges.push(this._ranges[name]); } return animationRanges; }; /** * Copy animation range from a source skeleton. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences * @param source defines the source skeleton * @param name defines the name of the range to copy * @param rescaleAsRequired defines if rescaling must be applied if required * @returns true if operation was successful */ Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) { if (rescaleAsRequired === void 0) { rescaleAsRequired = false; } if (this._ranges[name] || !source.getAnimationRange(name)) { return false; } var ret = true; var frameOffset = this._getHighestAnimationFrame() + 1; // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required var boneDict = {}; var sourceBones = source.bones; var nBones; var i; for (i = 0, nBones = sourceBones.length; i < nBones; i++) { boneDict[sourceBones[i].name] = sourceBones[i]; } if (this.bones.length !== sourceBones.length) { _Misc_logger__WEBPACK_IMPORTED_MODULE_8__["Logger"].Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length); ret = false; } var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null; for (i = 0, nBones = this.bones.length; i < nBones; i++) { var boneName = this.bones[i].name; var sourceBone = boneDict[boneName]; if (sourceBone) { ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio); } else { _Misc_logger__WEBPACK_IMPORTED_MODULE_8__["Logger"].Warn("copyAnimationRange: not same rig, missing source bone " + boneName); ret = false; } } // do not call createAnimationRange(), since it also is done to bones, which was already done var range = source.getAnimationRange(name); if (range) { this._ranges[name] = new _Animations_animationRange__WEBPACK_IMPORTED_MODULE_5__["AnimationRange"](name, range.from + frameOffset, range.to + frameOffset); } return ret; }; /** * Forces the skeleton to go to rest pose */ Skeleton.prototype.returnToRest = function () { for (var index = 0; index < this.bones.length; index++) { this.bones[index].returnToRest(); } }; Skeleton.prototype._getHighestAnimationFrame = function () { var ret = 0; for (var i = 0, nBones = this.bones.length; i < nBones; i++) { if (this.bones[i].animations[0]) { var highest = this.bones[i].animations[0].getHighestFrame(); if (ret < highest) { ret = highest; } } } return ret; }; /** * Begin a specific animation range * @param name defines the name of the range to start * @param loop defines if looping must be turned on (false by default) * @param speedRatio defines the speed ratio to apply (1 by default) * @param onAnimationEnd defines a callback which will be called when animation will end * @returns a new animatable */ Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) { var range = this.getAnimationRange(name); if (!range) { return null; } return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd); }; /** @hidden */ Skeleton.prototype._markAsDirty = function () { this._isDirty = true; }; /** @hidden */ Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) { this._meshesWithPoseMatrix.push(mesh); }; /** @hidden */ Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) { var index = this._meshesWithPoseMatrix.indexOf(mesh); if (index > -1) { this._meshesWithPoseMatrix.splice(index, 1); } }; Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) { this.onBeforeComputeObservable.notifyObservers(this); for (var index = 0; index < this.bones.length; index++) { var bone = this.bones[index]; var parentBone = bone.getParent(); if (parentBone) { bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix()); } else { if (initialSkinMatrix) { bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix()); } else { bone.getWorldMatrix().copyFrom(bone.getLocalMatrix()); } } if (bone._index !== -1) { var mappedIndex = bone._index === null ? index : bone._index; bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16); } } this._identity.copyToArray(targetMatrix, this.bones.length * 16); }; /** * Build all resources required to render a skeleton */ Skeleton.prototype.prepare = function () { // Update the local matrix of bones with linked transform nodes. if (this._numBonesWithLinkedTransformNode > 0) { for (var _i = 0, _a = this.bones; _i < _a.length; _i++) { var bone_1 = _a[_i]; if (bone_1._linkedTransformNode) { // Computing the world matrix also computes the local matrix. bone_1._linkedTransformNode.computeWorldMatrix(); bone_1._matrix = bone_1._linkedTransformNode._localMatrix; bone_1.markAsDirty(); } } } if (!this._isDirty) { return; } if (this.needInitialSkinMatrix) { for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) { var mesh = this._meshesWithPoseMatrix[index]; var poseMatrix = mesh.getPoseMatrix(); if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) { mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1)); } if (this._synchronizedWithMesh !== mesh) { this._synchronizedWithMesh = mesh; // Prepare bones for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) { var bone = this.bones[boneIndex]; if (!bone.getParent()) { var matrix = bone.getBaseMatrix(); matrix.multiplyToRef(poseMatrix, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Tmp"].Matrix[1]); bone._updateDifferenceMatrix(_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Tmp"].Matrix[1]); } } } this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix); } } else { if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) { this._transformMatrices = new Float32Array(16 * (this.bones.length + 1)); if (this.isUsingTextureForMatrices) { if (this._transformMatrixTexture) { this._transformMatrixTexture.dispose(); } this._transformMatrixTexture = _Materials_Textures_rawTexture__WEBPACK_IMPORTED_MODULE_3__["RawTexture"].CreateRGBATexture(this._transformMatrices, (this.bones.length + 1) * 4, 1, this._scene, false, false, _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE, _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_FLOAT); } } this._computeTransformMatrices(this._transformMatrices, null); if (this.isUsingTextureForMatrices && this._transformMatrixTexture) { this._transformMatrixTexture.update(this._transformMatrices); } } this._isDirty = false; this._scene._activeBones.addCount(this.bones.length, false); }; /** * Gets the list of animatables currently running for this skeleton * @returns an array of animatables */ Skeleton.prototype.getAnimatables = function () { if (!this._animatables || this._animatables.length !== this.bones.length) { this._animatables = []; for (var index = 0; index < this.bones.length; index++) { this._animatables.push(this.bones[index]); } } return this._animatables; }; /** * Clone the current skeleton * @param name defines the name of the new skeleton * @param id defines the id of the enw skeleton * @returns the new skeleton */ Skeleton.prototype.clone = function (name, id) { var result = new Skeleton(name, id || name, this._scene); result.needInitialSkinMatrix = this.needInitialSkinMatrix; for (var index = 0; index < this.bones.length; index++) { var source = this.bones[index]; var parentBone = null; var parent_1 = source.getParent(); if (parent_1) { var parentIndex = this.bones.indexOf(parent_1); parentBone = result.bones[parentIndex]; } var bone = new _bone__WEBPACK_IMPORTED_MODULE_0__["Bone"](source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone()); _Misc_deepCopier__WEBPACK_IMPORTED_MODULE_9__["DeepCopier"].DeepCopy(source.animations, bone.animations); } if (this._ranges) { result._ranges = {}; for (var rangeName in this._ranges) { var range = this._ranges[rangeName]; if (range) { result._ranges[rangeName] = range.clone(); } } } this._isDirty = true; return result; }; /** * Enable animation blending for this skeleton * @param blendingSpeed defines the blending speed to apply * @see http://doc.babylonjs.com/babylon101/animations#animation-blending */ Skeleton.prototype.enableBlending = function (blendingSpeed) { if (blendingSpeed === void 0) { blendingSpeed = 0.01; } this.bones.forEach(function (bone) { bone.animations.forEach(function (animation) { animation.enableBlending = true; animation.blendingSpeed = blendingSpeed; }); }); }; /** * Releases all resources associated with the current skeleton */ Skeleton.prototype.dispose = function () { this._meshesWithPoseMatrix = []; // Animations this.getScene().stopAnimation(this); // Remove from scene this.getScene().removeSkeleton(this); if (this._transformMatrixTexture) { this._transformMatrixTexture.dispose(); this._transformMatrixTexture = null; } }; /** * Serialize the skeleton in a JSON object * @returns a JSON object */ Skeleton.prototype.serialize = function () { var serializationObject = {}; serializationObject.name = this.name; serializationObject.id = this.id; if (this.dimensionsAtRest) { serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray(); } serializationObject.bones = []; serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix; for (var index = 0; index < this.bones.length; index++) { var bone = this.bones[index]; var parent_2 = bone.getParent(); var serializedBone = { parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1, name: bone.name, matrix: bone.getBaseMatrix().toArray(), rest: bone.getRestPose().toArray() }; serializationObject.bones.push(serializedBone); if (bone.length) { serializedBone.length = bone.length; } if (bone.metadata) { serializedBone.metadata = bone.metadata; } if (bone.animations && bone.animations.length > 0) { serializedBone.animation = bone.animations[0].serialize(); } serializationObject.ranges = []; for (var name in this._ranges) { var source = this._ranges[name]; if (!source) { continue; } var range = {}; range.name = name; range.from = source.from; range.to = source.to; serializationObject.ranges.push(range); } } return serializationObject; }; /** * Creates a new skeleton from serialized data * @param parsedSkeleton defines the serialized data * @param scene defines the hosting scene * @returns a new skeleton */ Skeleton.Parse = function (parsedSkeleton, scene) { var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene); if (parsedSkeleton.dimensionsAtRest) { skeleton.dimensionsAtRest = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].FromArray(parsedSkeleton.dimensionsAtRest); } skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix; var index; for (index = 0; index < parsedSkeleton.bones.length; index++) { var parsedBone = parsedSkeleton.bones[index]; var parentBone = null; if (parsedBone.parentBoneIndex > -1) { parentBone = skeleton.bones[parsedBone.parentBoneIndex]; } var rest = parsedBone.rest ? _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].FromArray(parsedBone.rest) : null; var bone = new _bone__WEBPACK_IMPORTED_MODULE_0__["Bone"](parsedBone.name, skeleton, parentBone, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].FromArray(parsedBone.matrix), rest); if (parsedBone.id !== undefined && parsedBone.id !== null) { bone.id = parsedBone.id; } if (parsedBone.length) { bone.length = parsedBone.length; } if (parsedBone.metadata) { bone.metadata = parsedBone.metadata; } if (parsedBone.animation) { bone.animations.push(_Animations_animation__WEBPACK_IMPORTED_MODULE_4__["Animation"].Parse(parsedBone.animation)); } } // placed after bones, so createAnimationRange can cascade down if (parsedSkeleton.ranges) { for (index = 0; index < parsedSkeleton.ranges.length; index++) { var data = parsedSkeleton.ranges[index]; skeleton.createAnimationRange(data.name, data.from, data.to); } } return skeleton; }; /** * Compute all node absolute transforms * @param forceUpdate defines if computation must be done even if cache is up to date */ Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) { if (forceUpdate === void 0) { forceUpdate = false; } var renderId = this._scene.getRenderId(); if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) { this.bones[0].computeAbsoluteTransforms(); this._lastAbsoluteTransformsUpdateId = renderId; } }; /** * Gets the root pose matrix * @returns a matrix */ Skeleton.prototype.getPoseMatrix = function () { var poseMatrix = null; if (this._meshesWithPoseMatrix.length > 0) { poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix(); } return poseMatrix; }; /** * Sorts bones per internal index */ Skeleton.prototype.sortBones = function () { var bones = new Array(); var visited = new Array(this.bones.length); for (var index = 0; index < this.bones.length; index++) { this._sortBones(index, bones, visited); } this.bones = bones; }; Skeleton.prototype._sortBones = function (index, bones, visited) { if (visited[index]) { return; } visited[index] = true; var bone = this.bones[index]; if (bone._index === undefined) { bone._index = index; } var parentBone = bone.getParent(); if (parentBone) { this._sortBones(this.bones.indexOf(parentBone), bones, visited); } bones.push(bone); }; return Skeleton; }()); /***/ }), /***/ "./Cameras/Inputs/BaseCameraPointersInput.ts": /*!***************************************************!*\ !*** ./Cameras/Inputs/BaseCameraPointersInput.ts ***! \***************************************************/ /*! exports provided: BaseCameraPointersInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BaseCameraPointersInput", function() { return BaseCameraPointersInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); /** * Base class for Camera Pointer Inputs. * See FollowCameraPointersInput in src/Cameras/Inputs/followCameraPointersInput.ts * for example usage. */ var BaseCameraPointersInput = /** @class */ (function () { function BaseCameraPointersInput() { /** * Defines the buttons associated with the input to handle camera move. */ this.buttons = [0, 1, 2]; } /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ BaseCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; var engine = this.camera.getEngine(); var previousPinchSquaredDistance = 0; var previousMultiTouchPanPosition = null; this.pointA = null; this.pointB = null; this._altKey = false; this._ctrlKey = false; this._metaKey = false; this._shiftKey = false; this._buttonsPressed = 0; this._pointerInput = function (p, s) { var evt = p.event; var isTouch = evt.pointerType === "touch"; if (engine.isInVRExclusivePointerMode) { return; } if (p.type !== _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) { return; } var srcElement = (evt.srcElement || evt.target); _this._altKey = evt.altKey; _this._ctrlKey = evt.ctrlKey; _this._metaKey = evt.metaKey; _this._shiftKey = evt.shiftKey; _this._buttonsPressed = evt.buttons; if (engine.isPointerLock) { var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0; var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0; _this.onTouch(null, offsetX, offsetY); _this.pointA = null; _this.pointB = null; } else if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERDOWN && srcElement) { try { srcElement.setPointerCapture(evt.pointerId); } catch (e) { //Nothing to do with the error. Execution will continue. } if (_this.pointA === null) { _this.pointA = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType }; } else if (_this.pointB === null) { _this.pointB = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType }; } _this.onButtonDown(evt); if (!noPreventDefault) { evt.preventDefault(); element.focus(); } } else if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERDOUBLETAP) { _this.onDoubleTap(evt.pointerType); } else if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERUP && srcElement) { try { srcElement.releasePointerCapture(evt.pointerId); } catch (e) { //Nothing to do with the error. } if (!isTouch) { _this.pointB = null; // Mouse and pen are mono pointer } //would be better to use pointers.remove(evt.pointerId) for multitouch gestures, //but emptying completely pointers collection is required to fix a bug on iPhone : //when changing orientation while pinching camera, //one pointer stay pressed forever if we don't release all pointers //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected if (engine._badOS) { _this.pointA = _this.pointB = null; } else { //only remove the impacted pointer in case of multitouch allowing on most //platforms switching from rotate to zoom and pan seamlessly. if (_this.pointB && _this.pointA && _this.pointA.pointerId == evt.pointerId) { _this.pointA = _this.pointB; _this.pointB = null; } else if (_this.pointA && _this.pointB && _this.pointB.pointerId == evt.pointerId) { _this.pointB = null; } else { _this.pointA = _this.pointB = null; } } if (previousPinchSquaredDistance !== 0 || previousMultiTouchPanPosition) { // Previous pinch data is populated but a button has been lifted // so pinch has ended. _this.onMultiTouch(_this.pointA, _this.pointB, previousPinchSquaredDistance, 0, // pinchSquaredDistance previousMultiTouchPanPosition, null // multiTouchPanPosition ); previousPinchSquaredDistance = 0; previousMultiTouchPanPosition = null; } _this.onButtonUp(evt); if (!noPreventDefault) { evt.preventDefault(); } } else if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERMOVE) { if (!noPreventDefault) { evt.preventDefault(); } // One button down if (_this.pointA && _this.pointB === null) { var offsetX = evt.clientX - _this.pointA.x; var offsetY = evt.clientY - _this.pointA.y; _this.onTouch(_this.pointA, offsetX, offsetY); _this.pointA.x = evt.clientX; _this.pointA.y = evt.clientY; } // Two buttons down: pinch else if (_this.pointA && _this.pointB) { var ed = (_this.pointA.pointerId === evt.pointerId) ? _this.pointA : _this.pointB; ed.x = evt.clientX; ed.y = evt.clientY; var distX = _this.pointA.x - _this.pointB.x; var distY = _this.pointA.y - _this.pointB.y; var pinchSquaredDistance = (distX * distX) + (distY * distY); var multiTouchPanPosition = { x: (_this.pointA.x + _this.pointB.x) / 2, y: (_this.pointA.y + _this.pointB.y) / 2, pointerId: evt.pointerId, type: p.type }; _this.onMultiTouch(_this.pointA, _this.pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition); previousMultiTouchPanPosition = multiTouchPanPosition; previousPinchSquaredDistance = pinchSquaredDistance; } } }; this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERDOWN | _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERUP | _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERMOVE); this._onLostFocus = function () { _this.pointA = _this.pointB = null; previousPinchSquaredDistance = 0; previousMultiTouchPanPosition = null; _this.onLostFocus(); }; element.addEventListener("contextmenu", this.onContextMenu.bind(this), false); _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].RegisterTopRootEvents([ { name: "blur", handler: this._onLostFocus } ]); }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ BaseCameraPointersInput.prototype.detachControl = function (element) { if (this._onLostFocus) { _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].UnregisterTopRootEvents([ { name: "blur", handler: this._onLostFocus } ]); } if (element && this._observer) { this.camera.getScene().onPointerObservable.remove(this._observer); this._observer = null; if (this.onContextMenu) { element.removeEventListener("contextmenu", this.onContextMenu); } this._onLostFocus = null; } this._altKey = false; this._ctrlKey = false; this._metaKey = false; this._shiftKey = false; this._buttonsPressed = 0; }; /** * Gets the class name of the current input. * @returns the class name */ BaseCameraPointersInput.prototype.getClassName = function () { return "BaseCameraPointersInput"; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ BaseCameraPointersInput.prototype.getSimpleName = function () { return "pointers"; }; /** * Called on pointer POINTERDOUBLETAP event. * Override this method to provide functionality on POINTERDOUBLETAP event. */ BaseCameraPointersInput.prototype.onDoubleTap = function (type) { }; /** * Called on pointer POINTERMOVE event if only a single touch is active. * Override this method to provide functionality. */ BaseCameraPointersInput.prototype.onTouch = function (point, offsetX, offsetY) { }; /** * Called on pointer POINTERMOVE event if multiple touches are active. * Override this method to provide functionality. */ BaseCameraPointersInput.prototype.onMultiTouch = function (pointA, pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) { }; /** * Called on JS contextmenu event. * Override this method to provide functionality. */ BaseCameraPointersInput.prototype.onContextMenu = function (evt) { evt.preventDefault(); }; /** * Called each time a new POINTERDOWN event occurs. Ie, for each button * press. * Override this method to provide functionality. */ BaseCameraPointersInput.prototype.onButtonDown = function (evt) { }; /** * Called each time a new POINTERUP event occurs. Ie, for each button * release. * Override this method to provide functionality. */ BaseCameraPointersInput.prototype.onButtonUp = function (evt) { }; /** * Called when window becomes inactive. * Override this method to provide functionality. */ BaseCameraPointersInput.prototype.onLostFocus = function () { }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BaseCameraPointersInput.prototype, "buttons", void 0); return BaseCameraPointersInput; }()); /***/ }), /***/ "./Cameras/Inputs/arcRotateCameraGamepadInput.ts": /*!*******************************************************!*\ !*** ./Cameras/Inputs/arcRotateCameraGamepadInput.ts ***! \*******************************************************/ /*! exports provided: ArcRotateCameraGamepadInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraGamepadInput", function() { return ArcRotateCameraGamepadInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Gamepads/gamepad */ "./Gamepads/gamepad.ts"); /** * Manage the gamepad inputs to control an arc rotate camera. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs */ var ArcRotateCameraGamepadInput = /** @class */ (function () { function ArcRotateCameraGamepadInput() { /** * Defines the gamepad rotation sensiblity. * This is the threshold from when rotation starts to be accounted for to prevent jittering. */ this.gamepadRotationSensibility = 80; /** * Defines the gamepad move sensiblity. * This is the threshold from when moving starts to be accounted for for to prevent jittering. */ this.gamepadMoveSensibility = 40; } /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; var manager = this.camera.getScene().gamepadManager; this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) { if (gamepad.type !== _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_3__["Gamepad"].POSE_ENABLED) { // prioritize XBOX gamepads. if (!_this.gamepad || gamepad.type === _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_3__["Gamepad"].XBOX) { _this.gamepad = gamepad; } } }); this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) { if (_this.gamepad === gamepad) { _this.gamepad = null; } }); this.gamepad = manager.getGamepadByType(_Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_3__["Gamepad"].XBOX); }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ ArcRotateCameraGamepadInput.prototype.detachControl = function (element) { this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver); this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver); this.gamepad = null; }; /** * Update the current camera state depending on the inputs that have been used this frame. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. */ ArcRotateCameraGamepadInput.prototype.checkInputs = function () { if (this.gamepad) { var camera = this.camera; var RSValues = this.gamepad.rightStick; if (RSValues) { if (RSValues.x != 0) { var normalizedRX = RSValues.x / this.gamepadRotationSensibility; if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) { camera.inertialAlphaOffset += normalizedRX; } } if (RSValues.y != 0) { var normalizedRY = RSValues.y / this.gamepadRotationSensibility; if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) { camera.inertialBetaOffset += normalizedRY; } } } var LSValues = this.gamepad.leftStick; if (LSValues && LSValues.y != 0) { var normalizedLY = LSValues.y / this.gamepadMoveSensibility; if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) { this.camera.inertialRadiusOffset -= normalizedLY; } } } }; /** * Gets the class name of the current intput. * @returns the class name */ ArcRotateCameraGamepadInput.prototype.getClassName = function () { return "ArcRotateCameraGamepadInput"; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ ArcRotateCameraGamepadInput.prototype.getSimpleName = function () { return "gamepad"; }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0); return ArcRotateCameraGamepadInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput; /***/ }), /***/ "./Cameras/Inputs/arcRotateCameraKeyboardMoveInput.ts": /*!************************************************************!*\ !*** ./Cameras/Inputs/arcRotateCameraKeyboardMoveInput.ts ***! \************************************************************/ /*! exports provided: ArcRotateCameraKeyboardMoveInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraKeyboardMoveInput", function() { return ArcRotateCameraKeyboardMoveInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/keyboardEvents */ "./Events/keyboardEvents.ts"); /** * Manage the keyboard inputs to control the movement of an arc rotate camera. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs */ var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () { function ArcRotateCameraKeyboardMoveInput() { /** * Defines the list of key codes associated with the up action (increase alpha) */ this.keysUp = [38]; /** * Defines the list of key codes associated with the down action (decrease alpha) */ this.keysDown = [40]; /** * Defines the list of key codes associated with the left action (increase beta) */ this.keysLeft = [37]; /** * Defines the list of key codes associated with the right action (decrease beta) */ this.keysRight = [39]; /** * Defines the list of key codes associated with the reset action. * Those keys reset the camera to its last stored state (with the method camera.storeState()) */ this.keysReset = [220]; /** * Defines the panning sensibility of the inputs. * (How fast is the camera paning) */ this.panningSensibility = 50.0; /** * Defines the zooming sensibility of the inputs. * (How fast is the camera zooming) */ this.zoomingSensibility = 25.0; /** * Defines wether maintaining the alt key down switch the movement mode from * orientation to zoom. */ this.useAltToZoom = true; /** * Rotation speed of the camera */ this.angularSpeed = 0.01; this._keys = new Array(); } /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; if (this._onCanvasBlurObserver) { return; } this._scene = this.camera.getScene(); this._engine = this._scene.getEngine(); this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () { _this._keys = []; }); this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) { var evt = info.event; if (!evt.metaKey) { if (info.type === _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_3__["KeyboardEventTypes"].KEYDOWN) { _this._ctrlPressed = evt.ctrlKey; _this._altPressed = evt.altKey; if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1 || _this.keysReset.indexOf(evt.keyCode) !== -1) { var index = _this._keys.indexOf(evt.keyCode); if (index === -1) { _this._keys.push(evt.keyCode); } if (evt.preventDefault) { if (!noPreventDefault) { evt.preventDefault(); } } } } else { if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1 || _this.keysReset.indexOf(evt.keyCode) !== -1) { var index = _this._keys.indexOf(evt.keyCode); if (index >= 0) { _this._keys.splice(index, 1); } if (evt.preventDefault) { if (!noPreventDefault) { evt.preventDefault(); } } } } } }); }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) { if (this._scene) { if (this._onKeyboardObserver) { this._scene.onKeyboardObservable.remove(this._onKeyboardObserver); } if (this._onCanvasBlurObserver) { this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver); } this._onKeyboardObserver = null; this._onCanvasBlurObserver = null; } this._keys = []; }; /** * Update the current camera state depending on the inputs that have been used this frame. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. */ ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () { if (this._onKeyboardObserver) { var camera = this.camera; for (var index = 0; index < this._keys.length; index++) { var keyCode = this._keys[index]; if (this.keysLeft.indexOf(keyCode) !== -1) { if (this._ctrlPressed && this.camera._useCtrlForPanning) { camera.inertialPanningX -= 1 / this.panningSensibility; } else { camera.inertialAlphaOffset -= this.angularSpeed; } } else if (this.keysUp.indexOf(keyCode) !== -1) { if (this._ctrlPressed && this.camera._useCtrlForPanning) { camera.inertialPanningY += 1 / this.panningSensibility; } else if (this._altPressed && this.useAltToZoom) { camera.inertialRadiusOffset += 1 / this.zoomingSensibility; } else { camera.inertialBetaOffset -= this.angularSpeed; } } else if (this.keysRight.indexOf(keyCode) !== -1) { if (this._ctrlPressed && this.camera._useCtrlForPanning) { camera.inertialPanningX += 1 / this.panningSensibility; } else { camera.inertialAlphaOffset += this.angularSpeed; } } else if (this.keysDown.indexOf(keyCode) !== -1) { if (this._ctrlPressed && this.camera._useCtrlForPanning) { camera.inertialPanningY -= 1 / this.panningSensibility; } else if (this._altPressed && this.useAltToZoom) { camera.inertialRadiusOffset -= 1 / this.zoomingSensibility; } else { camera.inertialBetaOffset += this.angularSpeed; } } else if (this.keysReset.indexOf(keyCode) !== -1) { if (camera.useInputToRestoreState) { camera.restoreState(); } } } } }; /** * Gets the class name of the current intput. * @returns the class name */ ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () { return "ArcRotateCameraKeyboardMoveInput"; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () { return "keyboard"; }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0); return ArcRotateCameraKeyboardMoveInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput; /***/ }), /***/ "./Cameras/Inputs/arcRotateCameraMouseWheelInput.ts": /*!**********************************************************!*\ !*** ./Cameras/Inputs/arcRotateCameraMouseWheelInput.ts ***! \**********************************************************/ /*! exports provided: ArcRotateCameraMouseWheelInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraMouseWheelInput", function() { return ArcRotateCameraMouseWheelInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); /** * Manage the mouse wheel inputs to control an arc rotate camera. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs */ var ArcRotateCameraMouseWheelInput = /** @class */ (function () { function ArcRotateCameraMouseWheelInput() { /** * Gets or Set the mouse wheel precision or how fast is the camera zooming. */ this.wheelPrecision = 3.0; /** * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0. * It defines the percentage of current camera.radius to use as delta when wheel is used. */ this.wheelDeltaPercentage = 0; } /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; this._wheel = function (p, s) { //sanity check - this should be a PointerWheel event. if (p.type !== _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERWHEEL) { return; } var event = p.event; var delta = 0; var mouseWheelLegacyEvent = event; if (mouseWheelLegacyEvent.wheelDelta) { if (_this.wheelDeltaPercentage) { var wheelDelta = (mouseWheelLegacyEvent.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius; if (mouseWheelLegacyEvent.wheelDelta > 0) { delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage); } else { delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage); } } else { delta = mouseWheelLegacyEvent.wheelDelta / (_this.wheelPrecision * 40); } } else { var deltaValue = event.deltaY || event.detail; delta = -deltaValue / _this.wheelPrecision; } if (delta) { _this.camera.inertialRadiusOffset += delta; } if (event.preventDefault) { if (!noPreventDefault) { event.preventDefault(); } } }; this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERWHEEL); }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) { if (this._observer && element) { this.camera.getScene().onPointerObservable.remove(this._observer); this._observer = null; this._wheel = null; } }; /** * Gets the class name of the current intput. * @returns the class name */ ArcRotateCameraMouseWheelInput.prototype.getClassName = function () { return "ArcRotateCameraMouseWheelInput"; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () { return "mousewheel"; }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0); return ArcRotateCameraMouseWheelInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput; /***/ }), /***/ "./Cameras/Inputs/arcRotateCameraPointersInput.ts": /*!********************************************************!*\ !*** ./Cameras/Inputs/arcRotateCameraPointersInput.ts ***! \********************************************************/ /*! exports provided: ArcRotateCameraPointersInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraPointersInput", function() { return ArcRotateCameraPointersInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Cameras_Inputs_BaseCameraPointersInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Cameras/Inputs/BaseCameraPointersInput */ "./Cameras/Inputs/BaseCameraPointersInput.ts"); /** * Manage the pointers inputs to control an arc rotate camera. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs */ var ArcRotateCameraPointersInput = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ArcRotateCameraPointersInput, _super); function ArcRotateCameraPointersInput() { var _this = _super !== null && _super.apply(this, arguments) || this; /** * Defines the buttons associated with the input to handle camera move. */ _this.buttons = [0, 1, 2]; /** * Defines the pointer angular sensibility along the X axis or how fast is * the camera rotating. */ _this.angularSensibilityX = 1000.0; /** * Defines the pointer angular sensibility along the Y axis or how fast is * the camera rotating. */ _this.angularSensibilityY = 1000.0; /** * Defines the pointer pinch precision or how fast is the camera zooming. */ _this.pinchPrecision = 12.0; /** * pinchDeltaPercentage will be used instead of pinchPrecision if different * from 0. * It defines the percentage of current camera.radius to use as delta when * pinch zoom is used. */ _this.pinchDeltaPercentage = 0; /** * Defines the pointer panning sensibility or how fast is the camera moving. */ _this.panningSensibility = 1000.0; /** * Defines whether panning (2 fingers swipe) is enabled through multitouch. */ _this.multiTouchPanning = true; /** * Defines whether panning is enabled for both pan (2 fingers swipe) and * zoom (pinch) through multitouch. */ _this.multiTouchPanAndZoom = true; /** * Revers pinch action direction. */ _this.pinchInwards = true; _this._isPanClick = false; _this._twoFingerActivityCount = 0; _this._isPinching = false; return _this; } /** * Gets the class name of the current input. * @returns the class name */ ArcRotateCameraPointersInput.prototype.getClassName = function () { return "ArcRotateCameraPointersInput"; }; /** * Called on pointer POINTERMOVE event if only a single touch is active. */ ArcRotateCameraPointersInput.prototype.onTouch = function (point, offsetX, offsetY) { if (this.panningSensibility !== 0 && ((this._ctrlKey && this.camera._useCtrlForPanning) || this._isPanClick)) { this.camera.inertialPanningX += -offsetX / this.panningSensibility; this.camera.inertialPanningY += offsetY / this.panningSensibility; } else { this.camera.inertialAlphaOffset -= offsetX / this.angularSensibilityX; this.camera.inertialBetaOffset -= offsetY / this.angularSensibilityY; } }; /** * Called on pointer POINTERDOUBLETAP event. */ ArcRotateCameraPointersInput.prototype.onDoubleTap = function (type) { if (this.camera.useInputToRestoreState) { this.camera.restoreState(); } }; /** * Called on pointer POINTERMOVE event if multiple touches are active. */ ArcRotateCameraPointersInput.prototype.onMultiTouch = function (pointA, pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) { if (previousPinchSquaredDistance === 0 && previousMultiTouchPanPosition === null) { // First time this method is called for new pinch. // Next time this is called there will be a // previousPinchSquaredDistance and pinchSquaredDistance to compare. return; } if (pinchSquaredDistance === 0 && multiTouchPanPosition === null) { // Last time this method is called at the end of a pinch. return; } var direction = this.pinchInwards ? 1 : -1; if (this.multiTouchPanAndZoom) { if (this.pinchDeltaPercentage) { this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) * 0.001 * this.camera.radius * this.pinchDeltaPercentage; } else { this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) / (this.pinchPrecision * direction * (this.angularSensibilityX + this.angularSensibilityY) / 2); } if (this.panningSensibility !== 0 && previousMultiTouchPanPosition && multiTouchPanPosition) { var moveDeltaX = multiTouchPanPosition.x - previousMultiTouchPanPosition.x; var moveDeltaY = multiTouchPanPosition.y - previousMultiTouchPanPosition.y; this.camera.inertialPanningX += -moveDeltaX / this.panningSensibility; this.camera.inertialPanningY += moveDeltaY / this.panningSensibility; } } else { this._twoFingerActivityCount++; var previousPinchDistance = Math.sqrt(previousPinchSquaredDistance); var pinchDistance = Math.sqrt(pinchSquaredDistance); if (this._isPinching || (this._twoFingerActivityCount < 20 && Math.abs(pinchDistance - previousPinchDistance) > this.camera.pinchToPanMaxDistance)) { // Since pinch has not been active long, assume we intend to zoom. if (this.pinchDeltaPercentage) { this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) * 0.001 * this.camera.radius * this.pinchDeltaPercentage; } else { this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) / (this.pinchPrecision * direction * (this.angularSensibilityX + this.angularSensibilityY) / 2); } // Since we are pinching, remain pinching on next iteration. this._isPinching = true; } else { // Pause between pinch starting and moving implies not a zoom event. // Pan instead. if (this.panningSensibility !== 0 && this.multiTouchPanning && multiTouchPanPosition && previousMultiTouchPanPosition) { var moveDeltaX = multiTouchPanPosition.x - previousMultiTouchPanPosition.x; var moveDeltaY = multiTouchPanPosition.y - previousMultiTouchPanPosition.y; this.camera.inertialPanningX += -moveDeltaX / this.panningSensibility; this.camera.inertialPanningY += moveDeltaY / this.panningSensibility; } } } }; /** * Called each time a new POINTERDOWN event occurs. Ie, for each button * press. */ ArcRotateCameraPointersInput.prototype.onButtonDown = function (evt) { this._isPanClick = evt.button === this.camera._panningMouseButton; }; /** * Called each time a new POINTERUP event occurs. Ie, for each button * release. */ ArcRotateCameraPointersInput.prototype.onButtonUp = function (evt) { this._twoFingerActivityCount = 0; this._isPinching = false; }; /** * Called when window becomes inactive. */ ArcRotateCameraPointersInput.prototype.onLostFocus = function () { this._isPanClick = false; this._twoFingerActivityCount = 0; this._isPinching = false; }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraPointersInput.prototype, "buttons", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0); return ArcRotateCameraPointersInput; }(_Cameras_Inputs_BaseCameraPointersInput__WEBPACK_IMPORTED_MODULE_3__["BaseCameraPointersInput"])); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput; /***/ }), /***/ "./Cameras/Inputs/arcRotateCameraVRDeviceOrientationInput.ts": /*!*******************************************************************!*\ !*** ./Cameras/Inputs/arcRotateCameraVRDeviceOrientationInput.ts ***! \*******************************************************************/ /*! exports provided: ArcRotateCameraVRDeviceOrientationInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraVRDeviceOrientationInput", function() { return ArcRotateCameraVRDeviceOrientationInput; }); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Cameras_arcRotateCameraInputsManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/arcRotateCameraInputsManager */ "./Cameras/arcRotateCameraInputsManager.ts"); /** * Add orientation input support to the input manager. * @returns the current input manager */ _Cameras_arcRotateCameraInputsManager__WEBPACK_IMPORTED_MODULE_1__["ArcRotateCameraInputsManager"].prototype.addVRDeviceOrientation = function () { this.add(new ArcRotateCameraVRDeviceOrientationInput()); return this; }; /** * Manage the device orientation inputs (gyroscope) to control an arc rotate camera. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs */ var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () { /** * Instantiate a new ArcRotateCameraVRDeviceOrientationInput. */ function ArcRotateCameraVRDeviceOrientationInput() { /** * Defines a correction factor applied on the alpha value retrieved from the orientation events. */ this.alphaCorrection = 1; /** * Defines a correction factor applied on the gamma value retrieved from the orientation events. */ this.gammaCorrection = 1; this._alpha = 0; this._gamma = 0; this._dirty = false; this._deviceOrientationHandler = this._onOrientationEvent.bind(this); } /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) { this.camera.attachControl(element, noPreventDefault); window.addEventListener("deviceorientation", this._deviceOrientationHandler); }; /** @hidden */ ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) { if (evt.alpha !== null) { this._alpha = (+evt.alpha | 0) * this.alphaCorrection; } if (evt.gamma !== null) { this._gamma = (+evt.gamma | 0) * this.gammaCorrection; } this._dirty = true; }; /** * Update the current camera state depending on the inputs that have been used this frame. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. */ ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () { if (this._dirty) { this._dirty = false; if (this._gamma < 0) { this._gamma = 180 + this._gamma; } this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2; this.camera.beta = (this._gamma / 180.0 * Math.PI); } }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) { window.removeEventListener("deviceorientation", this._deviceOrientationHandler); }; /** * Gets the class name of the current intput. * @returns the class name */ ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () { return "ArcRotateCameraVRDeviceOrientationInput"; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () { return "VRDeviceOrientation"; }; return ArcRotateCameraVRDeviceOrientationInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_0__["CameraInputTypes"]["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput; /***/ }), /***/ "./Cameras/Inputs/flyCameraKeyboardInput.ts": /*!**************************************************!*\ !*** ./Cameras/Inputs/flyCameraKeyboardInput.ts ***! \**************************************************/ /*! exports provided: FlyCameraKeyboardInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FlyCameraKeyboardInput", function() { return FlyCameraKeyboardInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/keyboardEvents */ "./Events/keyboardEvents.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /** * Listen to keyboard events to control the camera. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FlyCameraKeyboardInput = /** @class */ (function () { function FlyCameraKeyboardInput() { /** * The list of keyboard keys used to control the forward move of the camera. */ this.keysForward = [87]; /** * The list of keyboard keys used to control the backward move of the camera. */ this.keysBackward = [83]; /** * The list of keyboard keys used to control the forward move of the camera. */ this.keysUp = [69]; /** * The list of keyboard keys used to control the backward move of the camera. */ this.keysDown = [81]; /** * The list of keyboard keys used to control the right strafe move of the camera. */ this.keysRight = [68]; /** * The list of keyboard keys used to control the left strafe move of the camera. */ this.keysLeft = [65]; this._keys = new Array(); } /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ FlyCameraKeyboardInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; if (this._onCanvasBlurObserver) { return; } this._scene = this.camera.getScene(); this._engine = this._scene.getEngine(); this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () { _this._keys = []; }); this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) { var evt = info.event; if (info.type === _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_3__["KeyboardEventTypes"].KEYDOWN) { if (_this.keysForward.indexOf(evt.keyCode) !== -1 || _this.keysBackward.indexOf(evt.keyCode) !== -1 || _this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) { var index = _this._keys.indexOf(evt.keyCode); if (index === -1) { _this._keys.push(evt.keyCode); } if (!noPreventDefault) { evt.preventDefault(); } } } else { if (_this.keysForward.indexOf(evt.keyCode) !== -1 || _this.keysBackward.indexOf(evt.keyCode) !== -1 || _this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) { var index = _this._keys.indexOf(evt.keyCode); if (index >= 0) { _this._keys.splice(index, 1); } if (!noPreventDefault) { evt.preventDefault(); } } } }); }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ FlyCameraKeyboardInput.prototype.detachControl = function (element) { if (this._scene) { if (this._onKeyboardObserver) { this._scene.onKeyboardObservable.remove(this._onKeyboardObserver); } if (this._onCanvasBlurObserver) { this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver); } this._onKeyboardObserver = null; this._onCanvasBlurObserver = null; } this._keys = []; }; /** * Gets the class name of the current intput. * @returns the class name */ FlyCameraKeyboardInput.prototype.getClassName = function () { return "FlyCameraKeyboardInput"; }; /** @hidden */ FlyCameraKeyboardInput.prototype._onLostFocus = function (e) { this._keys = []; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ FlyCameraKeyboardInput.prototype.getSimpleName = function () { return "keyboard"; }; /** * Update the current camera state depending on the inputs that have been used this frame. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. */ FlyCameraKeyboardInput.prototype.checkInputs = function () { if (this._onKeyboardObserver) { var camera = this.camera; // Keyboard for (var index = 0; index < this._keys.length; index++) { var keyCode = this._keys[index]; var speed = camera._computeLocalCameraSpeed(); if (this.keysForward.indexOf(keyCode) !== -1) { camera._localDirection.copyFromFloats(0, 0, speed); } else if (this.keysBackward.indexOf(keyCode) !== -1) { camera._localDirection.copyFromFloats(0, 0, -speed); } else if (this.keysUp.indexOf(keyCode) !== -1) { camera._localDirection.copyFromFloats(0, speed, 0); } else if (this.keysDown.indexOf(keyCode) !== -1) { camera._localDirection.copyFromFloats(0, -speed, 0); } else if (this.keysRight.indexOf(keyCode) !== -1) { camera._localDirection.copyFromFloats(speed, 0, 0); } else if (this.keysLeft.indexOf(keyCode) !== -1) { camera._localDirection.copyFromFloats(-speed, 0, 0); } if (camera.getScene().useRightHandedSystem) { camera._localDirection.z *= -1; } camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix); _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection); camera.cameraDirection.addInPlace(camera._transformedDirection); } } }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FlyCameraKeyboardInput.prototype, "keysForward", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FlyCameraKeyboardInput.prototype, "keysBackward", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FlyCameraKeyboardInput.prototype, "keysUp", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FlyCameraKeyboardInput.prototype, "keysDown", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FlyCameraKeyboardInput.prototype, "keysRight", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FlyCameraKeyboardInput.prototype, "keysLeft", void 0); return FlyCameraKeyboardInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["FlyCameraKeyboardInput"] = FlyCameraKeyboardInput; /***/ }), /***/ "./Cameras/Inputs/flyCameraMouseInput.ts": /*!***********************************************!*\ !*** ./Cameras/Inputs/flyCameraMouseInput.ts ***! \***********************************************/ /*! exports provided: FlyCameraMouseInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FlyCameraMouseInput", function() { return FlyCameraMouseInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /** * Listen to mouse events to control the camera. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FlyCameraMouseInput = /** @class */ (function () { /** * Listen to mouse events to control the camera. * @param touchEnabled Define if touch is enabled. (Default is true.) * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs */ function FlyCameraMouseInput(touchEnabled) { if (touchEnabled === void 0) { touchEnabled = true; } /** * Defines the buttons associated with the input to handle camera rotation. */ this.buttons = [0, 1, 2]; /** * Assign buttons for Yaw control. */ this.buttonsYaw = [-1, 0, 1]; /** * Assign buttons for Pitch control. */ this.buttonsPitch = [-1, 0, 1]; /** * Assign buttons for Roll control. */ this.buttonsRoll = [2]; /** * Detect if any button is being pressed while mouse is moved. * -1 = Mouse locked. * 0 = Left button. * 1 = Middle Button. * 2 = Right Button. */ this.activeButton = -1; /** * Defines the pointer's angular sensibility, to control the camera rotation speed. * Higher values reduce its sensitivity. */ this.angularSensibility = 1000.0; this.previousPosition = null; } /** * Attach the mouse control to the HTML DOM element. * @param element Defines the element that listens to the input events. * @param noPreventDefault Defines whether events caught by the controls should call preventdefault(). */ FlyCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; this.element = element; this.noPreventDefault = noPreventDefault; this._observer = this.camera.getScene().onPointerObservable.add(function (p, s) { _this._pointerInput(p, s); }, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERDOWN | _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERUP | _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERMOVE); // Correct Roll by rate, if enabled. this._rollObserver = this.camera.getScene().onBeforeRenderObservable.add(function () { if (_this.camera.rollCorrect) { _this.camera.restoreRoll(_this.camera.rollCorrect); } }); // Helper function to keep 'this'. this._mousemoveCallback = function (e) { _this._onMouseMove(e); }; element.addEventListener("mousemove", this._mousemoveCallback, false); }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ FlyCameraMouseInput.prototype.detachControl = function (element) { if (this._observer && element) { this.camera.getScene().onPointerObservable.remove(this._observer); this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver); if (this._mousemoveCallback) { element.removeEventListener("mousemove", this._mousemoveCallback); } this._observer = null; this._rollObserver = null; this.previousPosition = null; this.noPreventDefault = undefined; } }; /** * Gets the class name of the current input. * @returns the class name. */ FlyCameraMouseInput.prototype.getClassName = function () { return "FlyCameraMouseInput"; }; /** * Get the friendly name associated with the input class. * @returns the input's friendly name. */ FlyCameraMouseInput.prototype.getSimpleName = function () { return "mouse"; }; // Track mouse movement, when the pointer is not locked. FlyCameraMouseInput.prototype._pointerInput = function (p, s) { var e = p.event; var camera = this.camera; var engine = camera.getEngine(); if (engine.isInVRExclusivePointerMode) { return; } if (!this.touchEnabled && e.pointerType === "touch") { return; } // Mouse is moved but an unknown mouse button is pressed. if (p.type !== _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERMOVE && this.buttons.indexOf(e.button) === -1) { return; } var srcElement = (e.srcElement || e.target); // Mouse down. if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERDOWN && srcElement) { try { srcElement.setPointerCapture(e.pointerId); } catch (e) { // Nothing to do with the error. Execution continues. } this.previousPosition = { x: e.clientX, y: e.clientY }; this.activeButton = e.button; if (!this.noPreventDefault) { e.preventDefault(); this.element.focus(); } } else // Mouse up. if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERUP && srcElement) { try { srcElement.releasePointerCapture(e.pointerId); } catch (e) { // Nothing to do with the error. Execution continues. } this.activeButton = -1; this.previousPosition = null; if (!this.noPreventDefault) { e.preventDefault(); } } else // Mouse move. if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERMOVE) { if (!this.previousPosition || engine.isPointerLock) { return; } var offsetX = e.clientX - this.previousPosition.x; var offsetY = e.clientY - this.previousPosition.y; this.rotateCamera(offsetX, offsetY); this.previousPosition = { x: e.clientX, y: e.clientY }; if (!this.noPreventDefault) { e.preventDefault(); } } }; // Track mouse movement, when pointer is locked. FlyCameraMouseInput.prototype._onMouseMove = function (e) { var camera = this.camera; var engine = camera.getEngine(); if (!engine.isPointerLock || engine.isInVRExclusivePointerMode) { return; } var offsetX = e.movementX || e.mozMovementX || e.webkitMovementX || e.msMovementX || 0; var offsetY = e.movementY || e.mozMovementY || e.webkitMovementY || e.msMovementY || 0; this.rotateCamera(offsetX, offsetY); this.previousPosition = null; if (!this.noPreventDefault) { e.preventDefault(); } }; /** * Rotate camera by mouse offset. */ FlyCameraMouseInput.prototype.rotateCamera = function (offsetX, offsetY) { var _this = this; var camera = this.camera; var scene = this.camera.getScene(); if (scene.useRightHandedSystem) { offsetX *= -1; } if (camera.parent && camera.parent._getWorldMatrixDeterminant() < 0) { offsetX *= -1; } var x = offsetX / this.angularSensibility; var y = offsetY / this.angularSensibility; // Initialize to current rotation. var currentRotation = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, camera.rotation.z); var rotationChange; // Pitch. if (this.buttonsPitch.some(function (v) { return v === _this.activeButton; })) { // Apply change in Radians to vector Angle. rotationChange = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].RotationAxis(_Maths_math__WEBPACK_IMPORTED_MODULE_4__["Axis"].X, y); // Apply Pitch to quaternion. currentRotation.multiplyInPlace(rotationChange); } // Yaw. if (this.buttonsYaw.some(function (v) { return v === _this.activeButton; })) { // Apply change in Radians to vector Angle. rotationChange = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].RotationAxis(_Maths_math__WEBPACK_IMPORTED_MODULE_4__["Axis"].Y, x); // Apply Yaw to quaternion. currentRotation.multiplyInPlace(rotationChange); // Add Roll, if banked turning is enabled, within Roll limit. var limit = (camera.bankedTurnLimit) + camera._trackRoll; // Defaults to 90° plus manual roll. if (camera.bankedTurn && -limit < camera.rotation.z && camera.rotation.z < limit) { var bankingDelta = camera.bankedTurnMultiplier * -x; // Apply change in Radians to vector Angle. rotationChange = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].RotationAxis(_Maths_math__WEBPACK_IMPORTED_MODULE_4__["Axis"].Z, bankingDelta); // Apply Yaw to quaternion. currentRotation.multiplyInPlace(rotationChange); } } // Roll. if (this.buttonsRoll.some(function (v) { return v === _this.activeButton; })) { // Apply change in Radians to vector Angle. rotationChange = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].RotationAxis(_Maths_math__WEBPACK_IMPORTED_MODULE_4__["Axis"].Z, -x); // Track Rolling. camera._trackRoll -= x; // Apply Pitch to quaternion. currentRotation.multiplyInPlace(rotationChange); } // Apply rotationQuaternion to Euler camera.rotation. currentRotation.toEulerAnglesToRef(camera.rotation); }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FlyCameraMouseInput.prototype, "buttons", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FlyCameraMouseInput.prototype, "angularSensibility", void 0); return FlyCameraMouseInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["FlyCameraMouseInput"] = FlyCameraMouseInput; /***/ }), /***/ "./Cameras/Inputs/followCameraKeyboardMoveInput.ts": /*!*********************************************************!*\ !*** ./Cameras/Inputs/followCameraKeyboardMoveInput.ts ***! \*********************************************************/ /*! exports provided: FollowCameraKeyboardMoveInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FollowCameraKeyboardMoveInput", function() { return FollowCameraKeyboardMoveInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/keyboardEvents */ "./Events/keyboardEvents.ts"); /** * Manage the keyboard inputs to control the movement of a follow camera. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FollowCameraKeyboardMoveInput = /** @class */ (function () { function FollowCameraKeyboardMoveInput() { /** * Defines the list of key codes associated with the up action (increase heightOffset) */ this.keysHeightOffsetIncr = [38]; /** * Defines the list of key codes associated with the down action (decrease heightOffset) */ this.keysHeightOffsetDecr = [40]; /** * Defines whether the Alt modifier key is required to move up/down (alter heightOffset) */ this.keysHeightOffsetModifierAlt = false; /** * Defines whether the Ctrl modifier key is required to move up/down (alter heightOffset) */ this.keysHeightOffsetModifierCtrl = false; /** * Defines whether the Shift modifier key is required to move up/down (alter heightOffset) */ this.keysHeightOffsetModifierShift = false; /** * Defines the list of key codes associated with the left action (increase rotationOffset) */ this.keysRotationOffsetIncr = [37]; /** * Defines the list of key codes associated with the right action (decrease rotationOffset) */ this.keysRotationOffsetDecr = [39]; /** * Defines whether the Alt modifier key is required to move left/right (alter rotationOffset) */ this.keysRotationOffsetModifierAlt = false; /** * Defines whether the Ctrl modifier key is required to move left/right (alter rotationOffset) */ this.keysRotationOffsetModifierCtrl = false; /** * Defines whether the Shift modifier key is required to move left/right (alter rotationOffset) */ this.keysRotationOffsetModifierShift = false; /** * Defines the list of key codes associated with the zoom-in action (decrease radius) */ this.keysRadiusIncr = [40]; /** * Defines the list of key codes associated with the zoom-out action (increase radius) */ this.keysRadiusDecr = [38]; /** * Defines whether the Alt modifier key is required to zoom in/out (alter radius value) */ this.keysRadiusModifierAlt = true; /** * Defines whether the Ctrl modifier key is required to zoom in/out (alter radius value) */ this.keysRadiusModifierCtrl = false; /** * Defines whether the Shift modifier key is required to zoom in/out (alter radius value) */ this.keysRadiusModifierShift = false; /** * Defines the rate of change of heightOffset. */ this.heightSensibility = 1; /** * Defines the rate of change of rotationOffset. */ this.rotationSensibility = 1; /** * Defines the rate of change of radius. */ this.radiusSensibility = 1; this._keys = new Array(); } /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ FollowCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; if (this._onCanvasBlurObserver) { return; } this._scene = this.camera.getScene(); this._engine = this._scene.getEngine(); this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () { _this._keys = []; }); this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) { var evt = info.event; if (!evt.metaKey) { if (info.type === _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_3__["KeyboardEventTypes"].KEYDOWN) { _this._ctrlPressed = evt.ctrlKey; _this._altPressed = evt.altKey; _this._shiftPressed = evt.shiftKey; if (_this.keysHeightOffsetIncr.indexOf(evt.keyCode) !== -1 || _this.keysHeightOffsetDecr.indexOf(evt.keyCode) !== -1 || _this.keysRotationOffsetIncr.indexOf(evt.keyCode) !== -1 || _this.keysRotationOffsetDecr.indexOf(evt.keyCode) !== -1 || _this.keysRadiusIncr.indexOf(evt.keyCode) !== -1 || _this.keysRadiusDecr.indexOf(evt.keyCode) !== -1) { var index = _this._keys.indexOf(evt.keyCode); if (index === -1) { _this._keys.push(evt.keyCode); } if (evt.preventDefault) { if (!noPreventDefault) { evt.preventDefault(); } } } } else { if (_this.keysHeightOffsetIncr.indexOf(evt.keyCode) !== -1 || _this.keysHeightOffsetDecr.indexOf(evt.keyCode) !== -1 || _this.keysRotationOffsetIncr.indexOf(evt.keyCode) !== -1 || _this.keysRotationOffsetDecr.indexOf(evt.keyCode) !== -1 || _this.keysRadiusIncr.indexOf(evt.keyCode) !== -1 || _this.keysRadiusDecr.indexOf(evt.keyCode) !== -1) { var index = _this._keys.indexOf(evt.keyCode); if (index >= 0) { _this._keys.splice(index, 1); } if (evt.preventDefault) { if (!noPreventDefault) { evt.preventDefault(); } } } } } }); }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ FollowCameraKeyboardMoveInput.prototype.detachControl = function (element) { if (this._scene) { if (this._onKeyboardObserver) { this._scene.onKeyboardObservable.remove(this._onKeyboardObserver); } if (this._onCanvasBlurObserver) { this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver); } this._onKeyboardObserver = null; this._onCanvasBlurObserver = null; } this._keys = []; }; /** * Update the current camera state depending on the inputs that have been used this frame. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. */ FollowCameraKeyboardMoveInput.prototype.checkInputs = function () { var _this = this; if (this._onKeyboardObserver) { this._keys.forEach(function (keyCode) { if (_this.keysHeightOffsetIncr.indexOf(keyCode) !== -1 && _this._modifierHeightOffset()) { _this.camera.heightOffset += _this.heightSensibility; } else if (_this.keysHeightOffsetDecr.indexOf(keyCode) !== -1 && _this._modifierHeightOffset()) { _this.camera.heightOffset -= _this.heightSensibility; } else if (_this.keysRotationOffsetIncr.indexOf(keyCode) !== -1 && _this._modifierRotationOffset()) { _this.camera.rotationOffset += _this.rotationSensibility; _this.camera.rotationOffset %= 360; } else if (_this.keysRotationOffsetDecr.indexOf(keyCode) !== -1 && _this._modifierRotationOffset()) { _this.camera.rotationOffset -= _this.rotationSensibility; _this.camera.rotationOffset %= 360; } else if (_this.keysRadiusIncr.indexOf(keyCode) !== -1 && _this._modifierRadius()) { _this.camera.radius += _this.radiusSensibility; } else if (_this.keysRadiusDecr.indexOf(keyCode) !== -1 && _this._modifierRadius()) { _this.camera.radius -= _this.radiusSensibility; } }); } }; /** * Gets the class name of the current input. * @returns the class name */ FollowCameraKeyboardMoveInput.prototype.getClassName = function () { return "FollowCameraKeyboardMoveInput"; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ FollowCameraKeyboardMoveInput.prototype.getSimpleName = function () { return "keyboard"; }; /** * Check if the pressed modifier keys (Alt/Ctrl/Shift) match those configured to * allow modification of the heightOffset value. */ FollowCameraKeyboardMoveInput.prototype._modifierHeightOffset = function () { return (this.keysHeightOffsetModifierAlt === this._altPressed && this.keysHeightOffsetModifierCtrl === this._ctrlPressed && this.keysHeightOffsetModifierShift === this._shiftPressed); }; /** * Check if the pressed modifier keys (Alt/Ctrl/Shift) match those configured to * allow modification of the rotationOffset value. */ FollowCameraKeyboardMoveInput.prototype._modifierRotationOffset = function () { return (this.keysRotationOffsetModifierAlt === this._altPressed && this.keysRotationOffsetModifierCtrl === this._ctrlPressed && this.keysRotationOffsetModifierShift === this._shiftPressed); }; /** * Check if the pressed modifier keys (Alt/Ctrl/Shift) match those configured to * allow modification of the radius value. */ FollowCameraKeyboardMoveInput.prototype._modifierRadius = function () { return (this.keysRadiusModifierAlt === this._altPressed && this.keysRadiusModifierCtrl === this._ctrlPressed && this.keysRadiusModifierShift === this._shiftPressed); }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetIncr", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetDecr", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetModifierAlt", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetModifierCtrl", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetModifierShift", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetIncr", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetDecr", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetModifierAlt", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetModifierCtrl", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetModifierShift", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysRadiusIncr", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysRadiusDecr", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysRadiusModifierAlt", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysRadiusModifierCtrl", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysRadiusModifierShift", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "heightSensibility", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "rotationSensibility", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "radiusSensibility", void 0); return FollowCameraKeyboardMoveInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__["CameraInputTypes"]["FollowCameraKeyboardMoveInput"] = FollowCameraKeyboardMoveInput; /***/ }), /***/ "./Cameras/Inputs/followCameraMouseWheelInput.ts": /*!*******************************************************!*\ !*** ./Cameras/Inputs/followCameraMouseWheelInput.ts ***! \*******************************************************/ /*! exports provided: FollowCameraMouseWheelInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FollowCameraMouseWheelInput", function() { return FollowCameraMouseWheelInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); /** * Manage the mouse wheel inputs to control a follow camera. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FollowCameraMouseWheelInput = /** @class */ (function () { function FollowCameraMouseWheelInput() { /** * Moue wheel controls zoom. (Mouse wheel modifies camera.radius value.) */ this.axisControlRadius = true; /** * Moue wheel controls height. (Mouse wheel modifies camera.heightOffset value.) */ this.axisControlHeight = false; /** * Moue wheel controls angle. (Mouse wheel modifies camera.rotationOffset value.) */ this.axisControlRotation = false; /** * Gets or Set the mouse wheel precision or how fast is the camera moves in * relation to mouseWheel events. */ this.wheelPrecision = 3.0; /** * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0. * It defines the percentage of current camera.radius to use as delta when wheel is used. */ this.wheelDeltaPercentage = 0; } /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ FollowCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; this._wheel = function (p, s) { // sanity check - this should be a PointerWheel event. if (p.type !== _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERWHEEL) { return; } var event = p.event; var delta = 0; // Chrome, Safari: event.deltaY // IE: event.wheelDelta // Firefox: event.detail (inverted) var wheelDelta = Math.max(-1, Math.min(1, (event.deltaY || event.wheelDelta || -event.detail))); if (_this.wheelDeltaPercentage) { console.assert((_this.axisControlRadius + _this.axisControlHeight + _this.axisControlRotation) <= 1, "wheelDeltaPercentage only usable when mouse wheel " + "controlls ONE axis. " + "Currently enabled: " + "axisControlRadius: " + _this.axisControlRadius + ", axisControlHeightOffset: " + _this.axisControlHeight + ", axisControlRotationOffset: " + _this.axisControlRotation); if (_this.axisControlRadius) { delta = wheelDelta * 0.01 * _this.wheelDeltaPercentage * _this.camera.radius; } else if (_this.axisControlHeight) { delta = wheelDelta * 0.01 * _this.wheelDeltaPercentage * _this.camera.heightOffset; } else if (_this.axisControlRotation) { delta = wheelDelta * 0.01 * _this.wheelDeltaPercentage * _this.camera.rotationOffset; } } else { delta = wheelDelta * _this.wheelPrecision; } if (delta) { if (_this.axisControlRadius) { _this.camera.radius += delta; } else if (_this.axisControlHeight) { _this.camera.heightOffset -= delta; } else if (_this.axisControlRotation) { _this.camera.rotationOffset -= delta; } } if (event.preventDefault) { if (!noPreventDefault) { event.preventDefault(); } } }; this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERWHEEL); }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ FollowCameraMouseWheelInput.prototype.detachControl = function (element) { if (this._observer && element) { this.camera.getScene().onPointerObservable.remove(this._observer); this._observer = null; this._wheel = null; } }; /** * Gets the class name of the current intput. * @returns the class name */ FollowCameraMouseWheelInput.prototype.getClassName = function () { return "ArcRotateCameraMouseWheelInput"; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ FollowCameraMouseWheelInput.prototype.getSimpleName = function () { return "mousewheel"; }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraMouseWheelInput.prototype, "axisControlRadius", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraMouseWheelInput.prototype, "axisControlHeight", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraMouseWheelInput.prototype, "axisControlRotation", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraMouseWheelInput.prototype, "wheelPrecision", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0); return FollowCameraMouseWheelInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["FollowCameraMouseWheelInput"] = FollowCameraMouseWheelInput; /***/ }), /***/ "./Cameras/Inputs/followCameraPointersInput.ts": /*!*****************************************************!*\ !*** ./Cameras/Inputs/followCameraPointersInput.ts ***! \*****************************************************/ /*! exports provided: FollowCameraPointersInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FollowCameraPointersInput", function() { return FollowCameraPointersInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Cameras_Inputs_BaseCameraPointersInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Cameras/Inputs/BaseCameraPointersInput */ "./Cameras/Inputs/BaseCameraPointersInput.ts"); /** * Manage the pointers inputs to control an follow camera. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FollowCameraPointersInput = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FollowCameraPointersInput, _super); function FollowCameraPointersInput() { var _this = _super !== null && _super.apply(this, arguments) || this; /** * Defines the pointer angular sensibility along the X axis or how fast is * the camera rotating. * A negative number will reverse the axis direction. */ _this.angularSensibilityX = 1; /** * Defines the pointer angular sensibility along the Y axis or how fast is * the camera rotating. * A negative number will reverse the axis direction. */ _this.angularSensibilityY = 1; /** * Defines the pointer pinch precision or how fast is the camera zooming. * A negative number will reverse the axis direction. */ _this.pinchPrecision = 10000.0; /** * pinchDeltaPercentage will be used instead of pinchPrecision if different * from 0. * It defines the percentage of current camera.radius to use as delta when * pinch zoom is used. */ _this.pinchDeltaPercentage = 0; /** * Pointer X axis controls zoom. (X axis modifies camera.radius value.) */ _this.axisXControlRadius = false; /** * Pointer X axis controls height. (X axis modifies camera.heightOffset value.) */ _this.axisXControlHeight = false; /** * Pointer X axis controls angle. (X axis modifies camera.rotationOffset value.) */ _this.axisXControlRotation = true; /** * Pointer Y axis controls zoom. (Y axis modifies camera.radius value.) */ _this.axisYControlRadius = false; /** * Pointer Y axis controls height. (Y axis modifies camera.heightOffset value.) */ _this.axisYControlHeight = true; /** * Pointer Y axis controls angle. (Y axis modifies camera.rotationOffset value.) */ _this.axisYControlRotation = false; /** * Pinch controls zoom. (Pinch modifies camera.radius value.) */ _this.axisPinchControlRadius = true; /** * Pinch controls height. (Pinch modifies camera.heightOffset value.) */ _this.axisPinchControlHeight = false; /** * Pinch controls angle. (Pinch modifies camera.rotationOffset value.) */ _this.axisPinchControlRotation = false; /** * Log error messages if basic misconfiguration has occurred. */ _this.warningEnable = true; /* Check for obvious misconfiguration. */ _this._warningCounter = 0; return _this; } /** * Gets the class name of the current input. * @returns the class name */ FollowCameraPointersInput.prototype.getClassName = function () { return "FollowCameraPointersInput"; }; FollowCameraPointersInput.prototype.onTouch = function (pointA, offsetX, offsetY) { this._warning(); if (this.axisXControlRotation) { this.camera.rotationOffset += offsetX / this.angularSensibilityX; } else if (this.axisYControlRotation) { this.camera.rotationOffset += offsetY / this.angularSensibilityX; } if (this.axisXControlHeight) { this.camera.heightOffset += offsetX / this.angularSensibilityY; } else if (this.axisYControlHeight) { this.camera.heightOffset += offsetY / this.angularSensibilityY; } if (this.axisXControlRadius) { this.camera.radius -= offsetX / this.angularSensibilityY; } else if (this.axisYControlRadius) { this.camera.radius -= offsetY / this.angularSensibilityY; } }; FollowCameraPointersInput.prototype.onMultiTouch = function (pointA, pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) { if (previousPinchSquaredDistance === 0 && previousMultiTouchPanPosition === null) { // First time this method is called for new pinch. // Next time this is called there will be a // previousPinchSquaredDistance and pinchSquaredDistance to compare. return; } if (pinchSquaredDistance === 0 && multiTouchPanPosition === null) { // Last time this method is called at the end of a pinch. return; } var pinchDelta = (pinchSquaredDistance - previousPinchSquaredDistance) / (this.pinchPrecision * (this.angularSensibilityX + this.angularSensibilityY) / 2); if (this.pinchDeltaPercentage) { pinchDelta *= 0.01 * this.pinchDeltaPercentage; if (this.axisPinchControlRotation) { this.camera.rotationOffset += pinchDelta * this.camera.rotationOffset; } if (this.axisPinchControlHeight) { this.camera.heightOffset += pinchDelta * this.camera.heightOffset; } if (this.axisPinchControlRadius) { this.camera.radius -= pinchDelta * this.camera.radius; } } else { if (this.axisPinchControlRotation) { this.camera.rotationOffset += pinchDelta; } if (this.axisPinchControlHeight) { this.camera.heightOffset += pinchDelta; } if (this.axisPinchControlRadius) { this.camera.radius -= pinchDelta; } } }; FollowCameraPointersInput.prototype._warning = function () { if (!this.warningEnable || this._warningCounter++ % 100 !== 0) { return; } var warn = "It probably only makes sense to control ONE camera " + "property with each pointer axis. Set 'warningEnable = false' " + "if you are sure. Currently enabled: "; console.assert((this.axisXControlRotation + this.axisXControlHeight + this.axisXControlRadius) <= 1, warn + "axisXControlRotation: " + this.axisXControlRotation + ", axisXControlHeight: " + this.axisXControlHeight + ", axisXControlRadius: " + this.axisXControlRadius); console.assert((this.axisYControlRotation + this.axisYControlHeight + this.axisYControlRadius) <= 1, warn + "axisYControlRotation: " + this.axisYControlRotation + ", axisYControlHeight: " + this.axisYControlHeight + ", axisYControlRadius: " + this.axisYControlRadius); console.assert((this.axisPinchControlRotation + this.axisPinchControlHeight + this.axisPinchControlRadius) <= 1, warn + "axisPinchControlRotation: " + this.axisPinchControlRotation + ", axisPinchControlHeight: " + this.axisPinchControlHeight + ", axisPinchControlRadius: " + this.axisPinchControlRadius); }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "angularSensibilityX", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "angularSensibilityY", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "pinchPrecision", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "pinchDeltaPercentage", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "axisXControlRadius", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "axisXControlHeight", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "axisXControlRotation", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "axisYControlRadius", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "axisYControlHeight", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "axisYControlRotation", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "axisPinchControlRadius", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "axisPinchControlHeight", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "axisPinchControlRotation", void 0); return FollowCameraPointersInput; }(_Cameras_Inputs_BaseCameraPointersInput__WEBPACK_IMPORTED_MODULE_3__["BaseCameraPointersInput"])); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["FollowCameraPointersInput"] = FollowCameraPointersInput; /***/ }), /***/ "./Cameras/Inputs/freeCameraDeviceOrientationInput.ts": /*!************************************************************!*\ !*** ./Cameras/Inputs/freeCameraDeviceOrientationInput.ts ***! \************************************************************/ /*! exports provided: FreeCameraDeviceOrientationInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FreeCameraDeviceOrientationInput", function() { return FreeCameraDeviceOrientationInput; }); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _Cameras_freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Cameras/freeCameraInputsManager */ "./Cameras/freeCameraInputsManager.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /** * Add orientation input support to the input manager. * @returns the current input manager */ _Cameras_freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_3__["FreeCameraInputsManager"].prototype.addDeviceOrientation = function () { if (!this._deviceOrientationInput) { this._deviceOrientationInput = new FreeCameraDeviceOrientationInput(); this.add(this._deviceOrientationInput); } return this; }; /** * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera. * Screen rotation is taken into account. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FreeCameraDeviceOrientationInput = /** @class */ (function () { /** * Instantiates a new input * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs */ function FreeCameraDeviceOrientationInput() { var _this = this; this._screenOrientationAngle = 0; this._screenQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"](); this._alpha = 0; this._beta = 0; this._gamma = 0; /** * @hidden */ this._onDeviceOrientationChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_4__["Observable"](); this._orientationChanged = function () { _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && (window.screen.orientation)['angle'] ? (window.screen.orientation).angle : 0)); _this._screenOrientationAngle = -_Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].ToRadians(_this._screenOrientationAngle / 2); _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle)); }; this._deviceOrientation = function (evt) { _this._alpha = evt.alpha !== null ? evt.alpha : 0; _this._beta = evt.beta !== null ? evt.beta : 0; _this._gamma = evt.gamma !== null ? evt.gamma : 0; if (evt.alpha !== null) { _this._onDeviceOrientationChangedObservable.notifyObservers(); } }; this._constantTranform = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"](-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5)); this._orientationChanged(); } Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", { /** * Define the camera controlled by the input. */ get: function () { return this._camera; }, set: function (camera) { var _this = this; this._camera = camera; if (this._camera != null && !this._camera.rotationQuaternion) { this._camera.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"](); } if (this._camera) { this._camera.onDisposeObservable.add(function () { _this._onDeviceOrientationChangedObservable.clear(); }); } }, enumerable: true, configurable: true }); /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) { window.addEventListener("orientationchange", this._orientationChanged); window.addEventListener("deviceorientation", this._deviceOrientation); //In certain cases, the attach control is called AFTER orientation was changed, //So this is needed. this._orientationChanged(); }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) { window.removeEventListener("orientationchange", this._orientationChanged); window.removeEventListener("deviceorientation", this._deviceOrientation); this._alpha = 0; }; /** * Update the current camera state depending on the inputs that have been used this frame. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. */ FreeCameraDeviceOrientationInput.prototype.checkInputs = function () { //if no device orientation provided, don't update the rotation. //Only testing against alpha under the assumption thatnorientation will never be so exact when set. if (!this._alpha) { return; } _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].RotationYawPitchRollToRef(_Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].ToRadians(this._alpha), _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].ToRadians(this._beta), -_Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].ToRadians(this._gamma), this.camera.rotationQuaternion); this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion); this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform); //Mirror on XY Plane this._camera.rotationQuaternion.z *= -1; this._camera.rotationQuaternion.w *= -1; }; /** * Gets the class name of the current intput. * @returns the class name */ FreeCameraDeviceOrientationInput.prototype.getClassName = function () { return "FreeCameraDeviceOrientationInput"; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () { return "deviceOrientation"; }; return FreeCameraDeviceOrientationInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_0__["CameraInputTypes"]["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput; /***/ }), /***/ "./Cameras/Inputs/freeCameraGamepadInput.ts": /*!**************************************************!*\ !*** ./Cameras/Inputs/freeCameraGamepadInput.ts ***! \**************************************************/ /*! exports provided: FreeCameraGamepadInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FreeCameraGamepadInput", function() { return FreeCameraGamepadInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Gamepads/gamepad */ "./Gamepads/gamepad.ts"); /** * Manage the gamepad inputs to control a free camera. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FreeCameraGamepadInput = /** @class */ (function () { function FreeCameraGamepadInput() { /** * Defines the gamepad rotation sensiblity. * This is the threshold from when rotation starts to be accounted for to prevent jittering. */ this.gamepadAngularSensibility = 200; /** * Defines the gamepad move sensiblity. * This is the threshold from when moving starts to be accounted for for to prevent jittering. */ this.gamepadMoveSensibility = 40; this._cameraTransform = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Identity(); this._deltaTransform = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); this._vector3 = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); this._vector2 = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector2"].Zero(); } /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; var manager = this.camera.getScene().gamepadManager; this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) { if (gamepad.type !== _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_4__["Gamepad"].POSE_ENABLED) { // prioritize XBOX gamepads. if (!_this.gamepad || gamepad.type === _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_4__["Gamepad"].XBOX) { _this.gamepad = gamepad; } } }); this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) { if (_this.gamepad === gamepad) { _this.gamepad = null; } }); this.gamepad = manager.getGamepadByType(_Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_4__["Gamepad"].XBOX); }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ FreeCameraGamepadInput.prototype.detachControl = function (element) { this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver); this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver); this.gamepad = null; }; /** * Update the current camera state depending on the inputs that have been used this frame. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. */ FreeCameraGamepadInput.prototype.checkInputs = function () { if (this.gamepad && this.gamepad.leftStick) { var camera = this.camera; var LSValues = this.gamepad.leftStick; var normalizedLX = LSValues.x / this.gamepadMoveSensibility; var normalizedLY = LSValues.y / this.gamepadMoveSensibility; LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0; LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0; var RSValues = this.gamepad.rightStick; if (RSValues) { var normalizedRX = RSValues.x / this.gamepadAngularSensibility; var normalizedRY = RSValues.y / this.gamepadAngularSensibility; RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0; RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0; } else { RSValues = { x: 0, y: 0 }; } if (!camera.rotationQuaternion) { _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform); } else { camera.rotationQuaternion.toRotationMatrix(this._cameraTransform); } var speed = camera._computeLocalCameraSpeed() * 50.0; this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed); _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform); camera.cameraDirection.addInPlace(this._deltaTransform); this._vector2.copyFromFloats(RSValues.y, RSValues.x); camera.cameraRotation.addInPlace(this._vector2); } }; /** * Gets the class name of the current intput. * @returns the class name */ FreeCameraGamepadInput.prototype.getClassName = function () { return "FreeCameraGamepadInput"; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ FreeCameraGamepadInput.prototype.getSimpleName = function () { return "gamepad"; }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0); return FreeCameraGamepadInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["FreeCameraGamepadInput"] = FreeCameraGamepadInput; /***/ }), /***/ "./Cameras/Inputs/freeCameraKeyboardMoveInput.ts": /*!*******************************************************!*\ !*** ./Cameras/Inputs/freeCameraKeyboardMoveInput.ts ***! \*******************************************************/ /*! exports provided: FreeCameraKeyboardMoveInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FreeCameraKeyboardMoveInput", function() { return FreeCameraKeyboardMoveInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/keyboardEvents */ "./Events/keyboardEvents.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /** * Manage the keyboard inputs to control the movement of a free camera. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FreeCameraKeyboardMoveInput = /** @class */ (function () { function FreeCameraKeyboardMoveInput() { /** * Gets or Set the list of keyboard keys used to control the forward move of the camera. */ this.keysUp = [38]; /** * Gets or Set the list of keyboard keys used to control the backward move of the camera. */ this.keysDown = [40]; /** * Gets or Set the list of keyboard keys used to control the left strafe move of the camera. */ this.keysLeft = [37]; /** * Gets or Set the list of keyboard keys used to control the right strafe move of the camera. */ this.keysRight = [39]; this._keys = new Array(); } /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; if (this._onCanvasBlurObserver) { return; } this._scene = this.camera.getScene(); this._engine = this._scene.getEngine(); this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () { _this._keys = []; }); this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) { var evt = info.event; if (!evt.metaKey) { if (info.type === _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_3__["KeyboardEventTypes"].KEYDOWN) { if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) { var index = _this._keys.indexOf(evt.keyCode); if (index === -1) { _this._keys.push(evt.keyCode); } if (!noPreventDefault) { evt.preventDefault(); } } } else { if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) { var index = _this._keys.indexOf(evt.keyCode); if (index >= 0) { _this._keys.splice(index, 1); } if (!noPreventDefault) { evt.preventDefault(); } } } } }); }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) { if (this._scene) { if (this._onKeyboardObserver) { this._scene.onKeyboardObservable.remove(this._onKeyboardObserver); } if (this._onCanvasBlurObserver) { this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver); } this._onKeyboardObserver = null; this._onCanvasBlurObserver = null; } this._keys = []; }; /** * Update the current camera state depending on the inputs that have been used this frame. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. */ FreeCameraKeyboardMoveInput.prototype.checkInputs = function () { if (this._onKeyboardObserver) { var camera = this.camera; // Keyboard for (var index = 0; index < this._keys.length; index++) { var keyCode = this._keys[index]; var speed = camera._computeLocalCameraSpeed(); if (this.keysLeft.indexOf(keyCode) !== -1) { camera._localDirection.copyFromFloats(-speed, 0, 0); } else if (this.keysUp.indexOf(keyCode) !== -1) { camera._localDirection.copyFromFloats(0, 0, speed); } else if (this.keysRight.indexOf(keyCode) !== -1) { camera._localDirection.copyFromFloats(speed, 0, 0); } else if (this.keysDown.indexOf(keyCode) !== -1) { camera._localDirection.copyFromFloats(0, 0, -speed); } if (camera.getScene().useRightHandedSystem) { camera._localDirection.z *= -1; } camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix); _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection); camera.cameraDirection.addInPlace(camera._transformedDirection); } } }; /** * Gets the class name of the current intput. * @returns the class name */ FreeCameraKeyboardMoveInput.prototype.getClassName = function () { return "FreeCameraKeyboardMoveInput"; }; /** @hidden */ FreeCameraKeyboardMoveInput.prototype._onLostFocus = function () { this._keys = []; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () { return "keyboard"; }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0); return FreeCameraKeyboardMoveInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput; /***/ }), /***/ "./Cameras/Inputs/freeCameraMouseInput.ts": /*!************************************************!*\ !*** ./Cameras/Inputs/freeCameraMouseInput.ts ***! \************************************************/ /*! exports provided: FreeCameraMouseInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FreeCameraMouseInput", function() { return FreeCameraMouseInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); /** * Manage the mouse inputs to control the movement of a free camera. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FreeCameraMouseInput = /** @class */ (function () { /** * Manage the mouse inputs to control the movement of a free camera. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs * @param touchEnabled Defines if touch is enabled or not */ function FreeCameraMouseInput( /** * Define if touch is enabled in the mouse input */ touchEnabled) { if (touchEnabled === void 0) { touchEnabled = true; } this.touchEnabled = touchEnabled; /** * Defines the buttons associated with the input to handle camera move. */ this.buttons = [0, 1, 2]; /** * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating. */ this.angularSensibility = 2000.0; this.previousPosition = null; /** * Observable for when a pointer move event occurs containing the move offset */ this.onPointerMovedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * @hidden * If the camera should be rotated automatically based on pointer movement */ this._allowCameraRotation = true; } /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; var engine = this.camera.getEngine(); if (!this._pointerInput) { this._pointerInput = function (p) { var evt = p.event; if (engine.isInVRExclusivePointerMode) { return; } if (!_this.touchEnabled && evt.pointerType === "touch") { return; } if (p.type !== _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) { return; } var srcElement = (evt.srcElement || evt.target); if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERDOWN && srcElement) { try { srcElement.setPointerCapture(evt.pointerId); } catch (e) { //Nothing to do with the error. Execution will continue. } _this.previousPosition = { x: evt.clientX, y: evt.clientY }; if (!noPreventDefault) { evt.preventDefault(); element.focus(); } } else if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERUP && srcElement) { try { srcElement.releasePointerCapture(evt.pointerId); } catch (e) { //Nothing to do with the error. } _this.previousPosition = null; if (!noPreventDefault) { evt.preventDefault(); } } else if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERMOVE) { if (!_this.previousPosition || engine.isPointerLock) { return; } var offsetX = evt.clientX - _this.previousPosition.x; var offsetY = evt.clientY - _this.previousPosition.y; if (_this.camera.getScene().useRightHandedSystem) { offsetX *= -1; } if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) { offsetX *= -1; } if (_this._allowCameraRotation) { _this.camera.cameraRotation.y += offsetX / _this.angularSensibility; _this.camera.cameraRotation.x += offsetY / _this.angularSensibility; } _this.onPointerMovedObservable.notifyObservers({ offsetX: offsetX, offsetY: offsetY }); _this.previousPosition = { x: evt.clientX, y: evt.clientY }; if (!noPreventDefault) { evt.preventDefault(); } } }; } this._onMouseMove = function (evt) { if (!engine.isPointerLock) { return; } if (engine.isInVRExclusivePointerMode) { return; } var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0; if (_this.camera.getScene().useRightHandedSystem) { offsetX *= -1; } if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) { offsetX *= -1; } _this.camera.cameraRotation.y += offsetX / _this.angularSensibility; var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0; _this.camera.cameraRotation.x += offsetY / _this.angularSensibility; _this.previousPosition = null; if (!noPreventDefault) { evt.preventDefault(); } }; this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERDOWN | _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERUP | _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERMOVE); element.addEventListener("mousemove", this._onMouseMove, false); element.addEventListener("contextmenu", this.onContextMenu.bind(this), false); }; /** * Called on JS contextmenu event. * Override this method to provide functionality. */ FreeCameraMouseInput.prototype.onContextMenu = function (evt) { evt.preventDefault(); }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ FreeCameraMouseInput.prototype.detachControl = function (element) { if (this._observer && element) { this.camera.getScene().onPointerObservable.remove(this._observer); if (this._onMouseMove) { element.removeEventListener("mousemove", this._onMouseMove); } if (this.onContextMenu) { element.removeEventListener("contextmenu", this.onContextMenu); } if (this.onPointerMovedObservable) { this.onPointerMovedObservable.clear(); } this._observer = null; this._onMouseMove = null; this.previousPosition = null; } }; /** * Gets the class name of the current intput. * @returns the class name */ FreeCameraMouseInput.prototype.getClassName = function () { return "FreeCameraMouseInput"; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ FreeCameraMouseInput.prototype.getSimpleName = function () { return "mouse"; }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FreeCameraMouseInput.prototype, "buttons", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FreeCameraMouseInput.prototype, "angularSensibility", void 0); return FreeCameraMouseInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_3__["CameraInputTypes"]["FreeCameraMouseInput"] = FreeCameraMouseInput; /***/ }), /***/ "./Cameras/Inputs/freeCameraTouchInput.ts": /*!************************************************!*\ !*** ./Cameras/Inputs/freeCameraTouchInput.ts ***! \************************************************/ /*! exports provided: FreeCameraTouchInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FreeCameraTouchInput", function() { return FreeCameraTouchInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /** * Manage the touch inputs to control the movement of a free camera. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FreeCameraTouchInput = /** @class */ (function () { function FreeCameraTouchInput() { /** * Defines the touch sensibility for rotation. * The higher the faster. */ this.touchAngularSensibility = 200000.0; /** * Defines the touch sensibility for move. * The higher the faster. */ this.touchMoveSensibility = 250.0; this._offsetX = null; this._offsetY = null; this._pointerPressed = new Array(); } /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; var previousPosition = null; if (this._pointerInput === undefined) { this._onLostFocus = function () { _this._offsetX = null; _this._offsetY = null; }; this._pointerInput = function (p) { var evt = p.event; if (evt.pointerType === "mouse") { return; } if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERDOWN) { if (!noPreventDefault) { evt.preventDefault(); } _this._pointerPressed.push(evt.pointerId); if (_this._pointerPressed.length !== 1) { return; } previousPosition = { x: evt.clientX, y: evt.clientY }; } else if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERUP) { if (!noPreventDefault) { evt.preventDefault(); } var index = _this._pointerPressed.indexOf(evt.pointerId); if (index === -1) { return; } _this._pointerPressed.splice(index, 1); if (index != 0) { return; } previousPosition = null; _this._offsetX = null; _this._offsetY = null; } else if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERMOVE) { if (!noPreventDefault) { evt.preventDefault(); } if (!previousPosition) { return; } var index = _this._pointerPressed.indexOf(evt.pointerId); if (index != 0) { return; } _this._offsetX = evt.clientX - previousPosition.x; _this._offsetY = -(evt.clientY - previousPosition.y); } }; } this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERDOWN | _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERUP | _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERMOVE); if (this._onLostFocus) { element.addEventListener("blur", this._onLostFocus); } }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ FreeCameraTouchInput.prototype.detachControl = function (element) { if (this._pointerInput && element) { if (this._observer) { this.camera.getScene().onPointerObservable.remove(this._observer); this._observer = null; } if (this._onLostFocus) { element.removeEventListener("blur", this._onLostFocus); this._onLostFocus = null; } this._pointerPressed = []; this._offsetX = null; this._offsetY = null; } }; /** * Update the current camera state depending on the inputs that have been used this frame. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. */ FreeCameraTouchInput.prototype.checkInputs = function () { if (this._offsetX && this._offsetY) { var camera = this.camera; camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility; if (this._pointerPressed.length > 1) { camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility; } else { var speed = camera._computeLocalCameraSpeed(); var direction = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"](0, 0, speed * this._offsetY / this.touchMoveSensibility); _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix); camera.cameraDirection.addInPlace(_Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].TransformCoordinates(direction, camera._cameraRotationMatrix)); } } }; /** * Gets the class name of the current intput. * @returns the class name */ FreeCameraTouchInput.prototype.getClassName = function () { return "FreeCameraTouchInput"; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ FreeCameraTouchInput.prototype.getSimpleName = function () { return "touch"; }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0); return FreeCameraTouchInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["FreeCameraTouchInput"] = FreeCameraTouchInput; /***/ }), /***/ "./Cameras/Inputs/freeCameraVirtualJoystickInput.ts": /*!**********************************************************!*\ !*** ./Cameras/Inputs/freeCameraVirtualJoystickInput.ts ***! \**********************************************************/ /*! exports provided: FreeCameraVirtualJoystickInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FreeCameraVirtualJoystickInput", function() { return FreeCameraVirtualJoystickInput; }); /* harmony import */ var _Misc_virtualJoystick__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Misc/virtualJoystick */ "./Misc/virtualJoystick.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Cameras_freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Cameras/freeCameraInputsManager */ "./Cameras/freeCameraInputsManager.ts"); /** * Add virtual joystick input support to the input manager. * @returns the current input manager */ _Cameras_freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_3__["FreeCameraInputsManager"].prototype.addVirtualJoystick = function () { this.add(new FreeCameraVirtualJoystickInput()); return this; }; /** * Manage the Virtual Joystick inputs to control the movement of a free camera. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FreeCameraVirtualJoystickInput = /** @class */ (function () { function FreeCameraVirtualJoystickInput() { } /** * Gets the left stick of the virtual joystick. * @returns The virtual Joystick */ FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () { return this._leftjoystick; }; /** * Gets the right stick of the virtual joystick. * @returns The virtual Joystick */ FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () { return this._rightjoystick; }; /** * Update the current camera state depending on the inputs that have been used this frame. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. */ FreeCameraVirtualJoystickInput.prototype.checkInputs = function () { if (this._leftjoystick) { var camera = this.camera; var speed = camera._computeLocalCameraSpeed() * 50; var cameraTransform = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0); var deltaTransform = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinates(new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform); camera.cameraDirection = camera.cameraDirection.add(deltaTransform); camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition); if (!this._leftjoystick.pressed) { this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9); } if (!this._rightjoystick.pressed) { this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9); } } }; /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) { this._leftjoystick = new _Misc_virtualJoystick__WEBPACK_IMPORTED_MODULE_0__["VirtualJoystick"](true); this._leftjoystick.setAxisForUpDown(_Misc_virtualJoystick__WEBPACK_IMPORTED_MODULE_0__["JoystickAxis"].Z); this._leftjoystick.setAxisForLeftRight(_Misc_virtualJoystick__WEBPACK_IMPORTED_MODULE_0__["JoystickAxis"].X); this._leftjoystick.setJoystickSensibility(0.15); this._rightjoystick = new _Misc_virtualJoystick__WEBPACK_IMPORTED_MODULE_0__["VirtualJoystick"](false); this._rightjoystick.setAxisForUpDown(_Misc_virtualJoystick__WEBPACK_IMPORTED_MODULE_0__["JoystickAxis"].X); this._rightjoystick.setAxisForLeftRight(_Misc_virtualJoystick__WEBPACK_IMPORTED_MODULE_0__["JoystickAxis"].Y); this._rightjoystick.reverseUpDown = true; this._rightjoystick.setJoystickSensibility(0.05); this._rightjoystick.setJoystickColor("yellow"); }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) { this._leftjoystick.releaseCanvas(); this._rightjoystick.releaseCanvas(); }; /** * Gets the class name of the current intput. * @returns the class name */ FreeCameraVirtualJoystickInput.prototype.getClassName = function () { return "FreeCameraVirtualJoystickInput"; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () { return "virtualJoystick"; }; return FreeCameraVirtualJoystickInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__["CameraInputTypes"]["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput; /***/ }), /***/ "./Cameras/Inputs/index.ts": /*!*********************************!*\ !*** ./Cameras/Inputs/index.ts ***! \*********************************/ /*! exports provided: ArcRotateCameraGamepadInput, ArcRotateCameraKeyboardMoveInput, ArcRotateCameraMouseWheelInput, ArcRotateCameraPointersInput, ArcRotateCameraVRDeviceOrientationInput, FlyCameraKeyboardInput, FlyCameraMouseInput, FollowCameraKeyboardMoveInput, FollowCameraMouseWheelInput, FollowCameraPointersInput, FreeCameraDeviceOrientationInput, FreeCameraGamepadInput, FreeCameraKeyboardMoveInput, FreeCameraMouseInput, FreeCameraTouchInput, FreeCameraVirtualJoystickInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _arcRotateCameraGamepadInput__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./arcRotateCameraGamepadInput */ "./Cameras/Inputs/arcRotateCameraGamepadInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraGamepadInput", function() { return _arcRotateCameraGamepadInput__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraGamepadInput"]; }); /* harmony import */ var _arcRotateCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./arcRotateCameraKeyboardMoveInput */ "./Cameras/Inputs/arcRotateCameraKeyboardMoveInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraKeyboardMoveInput", function() { return _arcRotateCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_1__["ArcRotateCameraKeyboardMoveInput"]; }); /* harmony import */ var _arcRotateCameraMouseWheelInput__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./arcRotateCameraMouseWheelInput */ "./Cameras/Inputs/arcRotateCameraMouseWheelInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraMouseWheelInput", function() { return _arcRotateCameraMouseWheelInput__WEBPACK_IMPORTED_MODULE_2__["ArcRotateCameraMouseWheelInput"]; }); /* harmony import */ var _arcRotateCameraPointersInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./arcRotateCameraPointersInput */ "./Cameras/Inputs/arcRotateCameraPointersInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraPointersInput", function() { return _arcRotateCameraPointersInput__WEBPACK_IMPORTED_MODULE_3__["ArcRotateCameraPointersInput"]; }); /* harmony import */ var _arcRotateCameraVRDeviceOrientationInput__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./arcRotateCameraVRDeviceOrientationInput */ "./Cameras/Inputs/arcRotateCameraVRDeviceOrientationInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraVRDeviceOrientationInput", function() { return _arcRotateCameraVRDeviceOrientationInput__WEBPACK_IMPORTED_MODULE_4__["ArcRotateCameraVRDeviceOrientationInput"]; }); /* harmony import */ var _flyCameraKeyboardInput__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./flyCameraKeyboardInput */ "./Cameras/Inputs/flyCameraKeyboardInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCameraKeyboardInput", function() { return _flyCameraKeyboardInput__WEBPACK_IMPORTED_MODULE_5__["FlyCameraKeyboardInput"]; }); /* harmony import */ var _flyCameraMouseInput__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./flyCameraMouseInput */ "./Cameras/Inputs/flyCameraMouseInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCameraMouseInput", function() { return _flyCameraMouseInput__WEBPACK_IMPORTED_MODULE_6__["FlyCameraMouseInput"]; }); /* harmony import */ var _followCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./followCameraKeyboardMoveInput */ "./Cameras/Inputs/followCameraKeyboardMoveInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraKeyboardMoveInput", function() { return _followCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_7__["FollowCameraKeyboardMoveInput"]; }); /* harmony import */ var _followCameraMouseWheelInput__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./followCameraMouseWheelInput */ "./Cameras/Inputs/followCameraMouseWheelInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraMouseWheelInput", function() { return _followCameraMouseWheelInput__WEBPACK_IMPORTED_MODULE_8__["FollowCameraMouseWheelInput"]; }); /* harmony import */ var _followCameraPointersInput__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./followCameraPointersInput */ "./Cameras/Inputs/followCameraPointersInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraPointersInput", function() { return _followCameraPointersInput__WEBPACK_IMPORTED_MODULE_9__["FollowCameraPointersInput"]; }); /* harmony import */ var _freeCameraDeviceOrientationInput__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./freeCameraDeviceOrientationInput */ "./Cameras/Inputs/freeCameraDeviceOrientationInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraDeviceOrientationInput", function() { return _freeCameraDeviceOrientationInput__WEBPACK_IMPORTED_MODULE_10__["FreeCameraDeviceOrientationInput"]; }); /* harmony import */ var _freeCameraGamepadInput__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./freeCameraGamepadInput */ "./Cameras/Inputs/freeCameraGamepadInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraGamepadInput", function() { return _freeCameraGamepadInput__WEBPACK_IMPORTED_MODULE_11__["FreeCameraGamepadInput"]; }); /* harmony import */ var _freeCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./freeCameraKeyboardMoveInput */ "./Cameras/Inputs/freeCameraKeyboardMoveInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraKeyboardMoveInput", function() { return _freeCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_12__["FreeCameraKeyboardMoveInput"]; }); /* harmony import */ var _freeCameraMouseInput__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./freeCameraMouseInput */ "./Cameras/Inputs/freeCameraMouseInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraMouseInput", function() { return _freeCameraMouseInput__WEBPACK_IMPORTED_MODULE_13__["FreeCameraMouseInput"]; }); /* harmony import */ var _freeCameraTouchInput__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./freeCameraTouchInput */ "./Cameras/Inputs/freeCameraTouchInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraTouchInput", function() { return _freeCameraTouchInput__WEBPACK_IMPORTED_MODULE_14__["FreeCameraTouchInput"]; }); /* harmony import */ var _freeCameraVirtualJoystickInput__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./freeCameraVirtualJoystickInput */ "./Cameras/Inputs/freeCameraVirtualJoystickInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraVirtualJoystickInput", function() { return _freeCameraVirtualJoystickInput__WEBPACK_IMPORTED_MODULE_15__["FreeCameraVirtualJoystickInput"]; }); /***/ }), /***/ "./Cameras/RigModes/stereoscopicAnaglyphRigMode.ts": /*!*********************************************************!*\ !*** ./Cameras/RigModes/stereoscopicAnaglyphRigMode.ts ***! \*********************************************************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../camera */ "./Cameras/camera.ts"); /* harmony import */ var _PostProcesses_passPostProcess__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../PostProcesses/passPostProcess */ "./PostProcesses/passPostProcess.ts"); /* harmony import */ var _PostProcesses_anaglyphPostProcess__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../PostProcesses/anaglyphPostProcess */ "./PostProcesses/anaglyphPostProcess.ts"); _camera__WEBPACK_IMPORTED_MODULE_0__["Camera"]._setStereoscopicAnaglyphRigMode = function (camera) { camera._rigCameras[0]._rigPostProcess = new _PostProcesses_passPostProcess__WEBPACK_IMPORTED_MODULE_1__["PassPostProcess"](camera.name + "_passthru", 1.0, camera._rigCameras[0]); camera._rigCameras[1]._rigPostProcess = new _PostProcesses_anaglyphPostProcess__WEBPACK_IMPORTED_MODULE_2__["AnaglyphPostProcess"](camera.name + "_anaglyph", 1.0, camera._rigCameras); }; /***/ }), /***/ "./Cameras/RigModes/stereoscopicRigMode.ts": /*!*************************************************!*\ !*** ./Cameras/RigModes/stereoscopicRigMode.ts ***! \*************************************************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../camera */ "./Cameras/camera.ts"); /* harmony import */ var _PostProcesses_passPostProcess__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../PostProcesses/passPostProcess */ "./PostProcesses/passPostProcess.ts"); /* harmony import */ var _PostProcesses_stereoscopicInterlacePostProcess__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../PostProcesses/stereoscopicInterlacePostProcess */ "./PostProcesses/stereoscopicInterlacePostProcess.ts"); _camera__WEBPACK_IMPORTED_MODULE_0__["Camera"]._setStereoscopicRigMode = function (camera) { var isStereoscopicHoriz = camera.cameraRigMode === _camera__WEBPACK_IMPORTED_MODULE_0__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || camera.cameraRigMode === _camera__WEBPACK_IMPORTED_MODULE_0__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED; camera._rigCameras[0]._rigPostProcess = new _PostProcesses_passPostProcess__WEBPACK_IMPORTED_MODULE_1__["PassPostProcess"](camera.name + "_passthru", 1.0, camera._rigCameras[0]); camera._rigCameras[1]._rigPostProcess = new _PostProcesses_stereoscopicInterlacePostProcess__WEBPACK_IMPORTED_MODULE_2__["StereoscopicInterlacePostProcess"](camera.name + "_stereoInterlace", camera._rigCameras, isStereoscopicHoriz); }; /***/ }), /***/ "./Cameras/RigModes/vrRigMode.ts": /*!***************************************!*\ !*** ./Cameras/RigModes/vrRigMode.ts ***! \***************************************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../camera */ "./Cameras/camera.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _PostProcesses_vrDistortionCorrectionPostProcess__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../PostProcesses/vrDistortionCorrectionPostProcess */ "./PostProcesses/vrDistortionCorrectionPostProcess.ts"); /* harmony import */ var _PostProcesses_vrMultiviewToSingleviewPostProcess__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../PostProcesses/vrMultiviewToSingleviewPostProcess */ "./PostProcesses/vrMultiviewToSingleviewPostProcess.ts"); /* harmony import */ var _VR_vrCameraMetrics__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../VR/vrCameraMetrics */ "./Cameras/VR/vrCameraMetrics.ts"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); _camera__WEBPACK_IMPORTED_MODULE_0__["Camera"]._setVRRigMode = function (camera, rigParams) { var metrics = rigParams.vrCameraMetrics || _VR_vrCameraMetrics__WEBPACK_IMPORTED_MODULE_4__["VRCameraMetrics"].GetDefault(); camera._rigCameras[0]._cameraRigParams.vrMetrics = metrics; camera._rigCameras[0].viewport = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Viewport"](0, 0, 0.5, 1.0); camera._rigCameras[0]._cameraRigParams.vrWorkMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); camera._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix; camera._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix; camera._rigCameras[0].getProjectionMatrix = camera._rigCameras[0]._getVRProjectionMatrix; camera._rigCameras[1]._cameraRigParams.vrMetrics = metrics; camera._rigCameras[1].viewport = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Viewport"](0.5, 0, 0.5, 1.0); camera._rigCameras[1]._cameraRigParams.vrWorkMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); camera._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix; camera._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix; camera._rigCameras[1].getProjectionMatrix = camera._rigCameras[1]._getVRProjectionMatrix; // For multiview on a webVR camera // First multiview will be rendered to camera._multiviewTexture // Then this postprocess will run on each eye to copy the right texture to each eye if (metrics.multiviewEnabled) { if (!camera.getScene().getEngine().getCaps().multiview) { _Misc_logger__WEBPACK_IMPORTED_MODULE_5__["Logger"].Warn("Multiview is not supported, falling back to standard rendering"); metrics.multiviewEnabled = false; } else { camera._useMultiviewToSingleView = true; camera._rigPostProcess = new _PostProcesses_vrMultiviewToSingleviewPostProcess__WEBPACK_IMPORTED_MODULE_3__["VRMultiviewToSingleviewPostProcess"]("VRMultiviewToSingleview", camera, metrics.postProcessScaleFactor); } } if (metrics.compensateDistortion) { camera._rigCameras[0]._rigPostProcess = new _PostProcesses_vrDistortionCorrectionPostProcess__WEBPACK_IMPORTED_MODULE_2__["VRDistortionCorrectionPostProcess"]("VR_Distort_Compensation_Left", camera._rigCameras[0], false, metrics); camera._rigCameras[1]._rigPostProcess = new _PostProcesses_vrDistortionCorrectionPostProcess__WEBPACK_IMPORTED_MODULE_2__["VRDistortionCorrectionPostProcess"]("VR_Distort_Compensation_Right", camera._rigCameras[1], true, metrics); } }; /***/ }), /***/ "./Cameras/RigModes/webVRRigMode.ts": /*!******************************************!*\ !*** ./Cameras/RigModes/webVRRigMode.ts ***! \******************************************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../camera */ "./Cameras/camera.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); _camera__WEBPACK_IMPORTED_MODULE_0__["Camera"]._setWebVRRigMode = function (camera, rigParams) { if (rigParams.vrDisplay) { var leftEye = rigParams.vrDisplay.getEyeParameters('left'); var rightEye = rigParams.vrDisplay.getEyeParameters('right'); //Left eye camera._rigCameras[0].viewport = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Viewport"](0, 0, 0.5, 1.0); camera._rigCameras[0].setCameraRigParameter("left", true); //leaving this for future reference camera._rigCameras[0].setCameraRigParameter("specs", rigParams.specs); camera._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye); camera._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData); camera._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera); camera._rigCameras[0]._cameraRigParams.vrWorkMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); camera._rigCameras[0].getProjectionMatrix = camera._getWebVRProjectionMatrix; camera._rigCameras[0].parent = camera; camera._rigCameras[0]._getViewMatrix = camera._getWebVRViewMatrix; //Right eye camera._rigCameras[1].viewport = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Viewport"](0.5, 0, 0.5, 1.0); camera._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye); camera._rigCameras[1].setCameraRigParameter("specs", rigParams.specs); camera._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData); camera._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera); camera._rigCameras[1]._cameraRigParams.vrWorkMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); camera._rigCameras[1].getProjectionMatrix = camera._getWebVRProjectionMatrix; camera._rigCameras[1].parent = camera; camera._rigCameras[1]._getViewMatrix = camera._getWebVRViewMatrix; } }; /***/ }), /***/ "./Cameras/Stereoscopic/anaglyphArcRotateCamera.ts": /*!*********************************************************!*\ !*** ./Cameras/Stereoscopic/anaglyphArcRotateCamera.ts ***! \*********************************************************/ /*! exports provided: AnaglyphArcRotateCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnaglyphArcRotateCamera", function() { return AnaglyphArcRotateCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/arcRotateCamera */ "./Cameras/arcRotateCamera.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); /* harmony import */ var _RigModes_stereoscopicAnaglyphRigMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../RigModes/stereoscopicAnaglyphRigMode */ "./Cameras/RigModes/stereoscopicAnaglyphRigMode.ts"); // Side effect import to define the stereoscopic mode. _node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) { return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), options.interaxial_distance, scene); }; }); /** * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera) * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras */ var AnaglyphArcRotateCamera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AnaglyphArcRotateCamera, _super); /** * Creates a new AnaglyphArcRotateCamera * @param name defines camera name * @param alpha defines alpha angle (in radians) * @param beta defines beta angle (in radians) * @param radius defines radius * @param target defines camera target * @param interaxialDistance defines distance between each color axis * @param scene defines the hosting scene */ function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) { var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this; _this.interaxialDistance = interaxialDistance; _this.setCameraRigMode(_Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance }); return _this; } /** * Gets camera class name * @returns AnaglyphArcRotateCamera */ AnaglyphArcRotateCamera.prototype.getClassName = function () { return "AnaglyphArcRotateCamera"; }; return AnaglyphArcRotateCamera; }(_Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_2__["ArcRotateCamera"])); /***/ }), /***/ "./Cameras/Stereoscopic/anaglyphFreeCamera.ts": /*!****************************************************!*\ !*** ./Cameras/Stereoscopic/anaglyphFreeCamera.ts ***! \****************************************************/ /*! exports provided: AnaglyphFreeCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnaglyphFreeCamera", function() { return AnaglyphFreeCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/freeCamera */ "./Cameras/freeCamera.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); /* harmony import */ var _RigModes_stereoscopicAnaglyphRigMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../RigModes/stereoscopicAnaglyphRigMode */ "./Cameras/RigModes/stereoscopicAnaglyphRigMode.ts"); // Side effect import to define the stereoscopic mode. _node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) { return function () { return new AnaglyphFreeCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), options.interaxial_distance, scene); }; }); /** * Camera used to simulate anaglyphic rendering (based on FreeCamera) * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras */ var AnaglyphFreeCamera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AnaglyphFreeCamera, _super); /** * Creates a new AnaglyphFreeCamera * @param name defines camera name * @param position defines initial position * @param interaxialDistance defines distance between each color axis * @param scene defines the hosting scene */ function AnaglyphFreeCamera(name, position, interaxialDistance, scene) { var _this = _super.call(this, name, position, scene) || this; _this.interaxialDistance = interaxialDistance; _this.setCameraRigMode(_Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance }); return _this; } /** * Gets camera class name * @returns AnaglyphFreeCamera */ AnaglyphFreeCamera.prototype.getClassName = function () { return "AnaglyphFreeCamera"; }; return AnaglyphFreeCamera; }(_Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_2__["FreeCamera"])); /***/ }), /***/ "./Cameras/Stereoscopic/anaglyphGamepadCamera.ts": /*!*******************************************************!*\ !*** ./Cameras/Stereoscopic/anaglyphGamepadCamera.ts ***! \*******************************************************/ /*! exports provided: AnaglyphGamepadCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnaglyphGamepadCamera", function() { return AnaglyphGamepadCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Cameras_gamepadCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/gamepadCamera */ "./Cameras/gamepadCamera.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); /* harmony import */ var _RigModes_stereoscopicAnaglyphRigMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../RigModes/stereoscopicAnaglyphRigMode */ "./Cameras/RigModes/stereoscopicAnaglyphRigMode.ts"); // Side effect import to define the stereoscopic mode. _node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) { return function () { return new AnaglyphGamepadCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), options.interaxial_distance, scene); }; }); /** * Camera used to simulate anaglyphic rendering (based on GamepadCamera) * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras */ var AnaglyphGamepadCamera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AnaglyphGamepadCamera, _super); /** * Creates a new AnaglyphGamepadCamera * @param name defines camera name * @param position defines initial position * @param interaxialDistance defines distance between each color axis * @param scene defines the hosting scene */ function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) { var _this = _super.call(this, name, position, scene) || this; _this.interaxialDistance = interaxialDistance; _this.setCameraRigMode(_Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance }); return _this; } /** * Gets camera class name * @returns AnaglyphGamepadCamera */ AnaglyphGamepadCamera.prototype.getClassName = function () { return "AnaglyphGamepadCamera"; }; return AnaglyphGamepadCamera; }(_Cameras_gamepadCamera__WEBPACK_IMPORTED_MODULE_2__["GamepadCamera"])); /***/ }), /***/ "./Cameras/Stereoscopic/anaglyphUniversalCamera.ts": /*!*********************************************************!*\ !*** ./Cameras/Stereoscopic/anaglyphUniversalCamera.ts ***! \*********************************************************/ /*! exports provided: AnaglyphUniversalCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnaglyphUniversalCamera", function() { return AnaglyphUniversalCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Cameras_universalCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/universalCamera */ "./Cameras/universalCamera.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); /* harmony import */ var _RigModes_stereoscopicAnaglyphRigMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../RigModes/stereoscopicAnaglyphRigMode */ "./Cameras/RigModes/stereoscopicAnaglyphRigMode.ts"); // Side effect import to define the stereoscopic mode. _node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) { return function () { return new AnaglyphUniversalCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), options.interaxial_distance, scene); }; }); /** * Camera used to simulate anaglyphic rendering (based on UniversalCamera) * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras */ var AnaglyphUniversalCamera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AnaglyphUniversalCamera, _super); /** * Creates a new AnaglyphUniversalCamera * @param name defines camera name * @param position defines initial position * @param interaxialDistance defines distance between each color axis * @param scene defines the hosting scene */ function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) { var _this = _super.call(this, name, position, scene) || this; _this.interaxialDistance = interaxialDistance; _this.setCameraRigMode(_Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance }); return _this; } /** * Gets camera class name * @returns AnaglyphUniversalCamera */ AnaglyphUniversalCamera.prototype.getClassName = function () { return "AnaglyphUniversalCamera"; }; return AnaglyphUniversalCamera; }(_Cameras_universalCamera__WEBPACK_IMPORTED_MODULE_2__["UniversalCamera"])); /***/ }), /***/ "./Cameras/Stereoscopic/index.ts": /*!***************************************!*\ !*** ./Cameras/Stereoscopic/index.ts ***! \***************************************/ /*! exports provided: AnaglyphArcRotateCamera, AnaglyphFreeCamera, AnaglyphGamepadCamera, AnaglyphUniversalCamera, StereoscopicArcRotateCamera, StereoscopicFreeCamera, StereoscopicGamepadCamera, StereoscopicUniversalCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _anaglyphArcRotateCamera__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./anaglyphArcRotateCamera */ "./Cameras/Stereoscopic/anaglyphArcRotateCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphArcRotateCamera", function() { return _anaglyphArcRotateCamera__WEBPACK_IMPORTED_MODULE_0__["AnaglyphArcRotateCamera"]; }); /* harmony import */ var _anaglyphFreeCamera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./anaglyphFreeCamera */ "./Cameras/Stereoscopic/anaglyphFreeCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphFreeCamera", function() { return _anaglyphFreeCamera__WEBPACK_IMPORTED_MODULE_1__["AnaglyphFreeCamera"]; }); /* harmony import */ var _anaglyphGamepadCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./anaglyphGamepadCamera */ "./Cameras/Stereoscopic/anaglyphGamepadCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphGamepadCamera", function() { return _anaglyphGamepadCamera__WEBPACK_IMPORTED_MODULE_2__["AnaglyphGamepadCamera"]; }); /* harmony import */ var _anaglyphUniversalCamera__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./anaglyphUniversalCamera */ "./Cameras/Stereoscopic/anaglyphUniversalCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphUniversalCamera", function() { return _anaglyphUniversalCamera__WEBPACK_IMPORTED_MODULE_3__["AnaglyphUniversalCamera"]; }); /* harmony import */ var _stereoscopicArcRotateCamera__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./stereoscopicArcRotateCamera */ "./Cameras/Stereoscopic/stereoscopicArcRotateCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicArcRotateCamera", function() { return _stereoscopicArcRotateCamera__WEBPACK_IMPORTED_MODULE_4__["StereoscopicArcRotateCamera"]; }); /* harmony import */ var _stereoscopicFreeCamera__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./stereoscopicFreeCamera */ "./Cameras/Stereoscopic/stereoscopicFreeCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicFreeCamera", function() { return _stereoscopicFreeCamera__WEBPACK_IMPORTED_MODULE_5__["StereoscopicFreeCamera"]; }); /* harmony import */ var _stereoscopicGamepadCamera__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./stereoscopicGamepadCamera */ "./Cameras/Stereoscopic/stereoscopicGamepadCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicGamepadCamera", function() { return _stereoscopicGamepadCamera__WEBPACK_IMPORTED_MODULE_6__["StereoscopicGamepadCamera"]; }); /* harmony import */ var _stereoscopicUniversalCamera__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./stereoscopicUniversalCamera */ "./Cameras/Stereoscopic/stereoscopicUniversalCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicUniversalCamera", function() { return _stereoscopicUniversalCamera__WEBPACK_IMPORTED_MODULE_7__["StereoscopicUniversalCamera"]; }); /***/ }), /***/ "./Cameras/Stereoscopic/stereoscopicArcRotateCamera.ts": /*!*************************************************************!*\ !*** ./Cameras/Stereoscopic/stereoscopicArcRotateCamera.ts ***! \*************************************************************/ /*! exports provided: StereoscopicArcRotateCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StereoscopicArcRotateCamera", function() { return StereoscopicArcRotateCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/arcRotateCamera */ "./Cameras/arcRotateCamera.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); /* harmony import */ var _RigModes_stereoscopicRigMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../RigModes/stereoscopicRigMode */ "./Cameras/RigModes/stereoscopicRigMode.ts"); // Side effect import to define the stereoscopic mode. _node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) { return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); }; }); /** * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera) * @see http://doc.babylonjs.com/features/cameras */ var StereoscopicArcRotateCamera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](StereoscopicArcRotateCamera, _super); /** * Creates a new StereoscopicArcRotateCamera * @param name defines camera name * @param alpha defines alpha angle (in radians) * @param beta defines beta angle (in radians) * @param radius defines radius * @param target defines camera target * @param interaxialDistance defines distance between each color axis * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under * @param scene defines the hosting scene */ function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) { var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this; _this.interaxialDistance = interaxialDistance; _this.isStereoscopicSideBySide = isStereoscopicSideBySide; _this.setCameraRigMode(isStereoscopicSideBySide ? _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance }); return _this; } /** * Gets camera class name * @returns StereoscopicArcRotateCamera */ StereoscopicArcRotateCamera.prototype.getClassName = function () { return "StereoscopicArcRotateCamera"; }; return StereoscopicArcRotateCamera; }(_Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_2__["ArcRotateCamera"])); /***/ }), /***/ "./Cameras/Stereoscopic/stereoscopicFreeCamera.ts": /*!********************************************************!*\ !*** ./Cameras/Stereoscopic/stereoscopicFreeCamera.ts ***! \********************************************************/ /*! exports provided: StereoscopicFreeCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StereoscopicFreeCamera", function() { return StereoscopicFreeCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/freeCamera */ "./Cameras/freeCamera.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); /* harmony import */ var _RigModes_stereoscopicRigMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../RigModes/stereoscopicRigMode */ "./Cameras/RigModes/stereoscopicRigMode.ts"); // Side effect import to define the stereoscopic mode. _node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) { return function () { return new StereoscopicFreeCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); }; }); /** * Camera used to simulate stereoscopic rendering (based on FreeCamera) * @see http://doc.babylonjs.com/features/cameras */ var StereoscopicFreeCamera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](StereoscopicFreeCamera, _super); /** * Creates a new StereoscopicFreeCamera * @param name defines camera name * @param position defines initial position * @param interaxialDistance defines distance between each color axis * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under * @param scene defines the hosting scene */ function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) { var _this = _super.call(this, name, position, scene) || this; _this.interaxialDistance = interaxialDistance; _this.isStereoscopicSideBySide = isStereoscopicSideBySide; _this.setCameraRigMode(isStereoscopicSideBySide ? _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance }); return _this; } /** * Gets camera class name * @returns StereoscopicFreeCamera */ StereoscopicFreeCamera.prototype.getClassName = function () { return "StereoscopicFreeCamera"; }; return StereoscopicFreeCamera; }(_Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_2__["FreeCamera"])); /***/ }), /***/ "./Cameras/Stereoscopic/stereoscopicGamepadCamera.ts": /*!***********************************************************!*\ !*** ./Cameras/Stereoscopic/stereoscopicGamepadCamera.ts ***! \***********************************************************/ /*! exports provided: StereoscopicGamepadCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StereoscopicGamepadCamera", function() { return StereoscopicGamepadCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Cameras_gamepadCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/gamepadCamera */ "./Cameras/gamepadCamera.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); /* harmony import */ var _RigModes_stereoscopicRigMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../RigModes/stereoscopicRigMode */ "./Cameras/RigModes/stereoscopicRigMode.ts"); // Side effect import to define the stereoscopic mode. _node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) { return function () { return new StereoscopicGamepadCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); }; }); /** * Camera used to simulate stereoscopic rendering (based on GamepadCamera) * @see http://doc.babylonjs.com/features/cameras */ var StereoscopicGamepadCamera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](StereoscopicGamepadCamera, _super); /** * Creates a new StereoscopicGamepadCamera * @param name defines camera name * @param position defines initial position * @param interaxialDistance defines distance between each color axis * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under * @param scene defines the hosting scene */ function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) { var _this = _super.call(this, name, position, scene) || this; _this.interaxialDistance = interaxialDistance; _this.isStereoscopicSideBySide = isStereoscopicSideBySide; _this.setCameraRigMode(isStereoscopicSideBySide ? _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance }); return _this; } /** * Gets camera class name * @returns StereoscopicGamepadCamera */ StereoscopicGamepadCamera.prototype.getClassName = function () { return "StereoscopicGamepadCamera"; }; return StereoscopicGamepadCamera; }(_Cameras_gamepadCamera__WEBPACK_IMPORTED_MODULE_2__["GamepadCamera"])); /***/ }), /***/ "./Cameras/Stereoscopic/stereoscopicUniversalCamera.ts": /*!*************************************************************!*\ !*** ./Cameras/Stereoscopic/stereoscopicUniversalCamera.ts ***! \*************************************************************/ /*! exports provided: StereoscopicUniversalCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StereoscopicUniversalCamera", function() { return StereoscopicUniversalCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Cameras_universalCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/universalCamera */ "./Cameras/universalCamera.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); /* harmony import */ var _RigModes_stereoscopicRigMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../RigModes/stereoscopicRigMode */ "./Cameras/RigModes/stereoscopicRigMode.ts"); // Side effect import to define the stereoscopic mode. _node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) { return function () { return new StereoscopicUniversalCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); }; }); /** * Camera used to simulate stereoscopic rendering (based on UniversalCamera) * @see http://doc.babylonjs.com/features/cameras */ var StereoscopicUniversalCamera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](StereoscopicUniversalCamera, _super); /** * Creates a new StereoscopicUniversalCamera * @param name defines camera name * @param position defines initial position * @param interaxialDistance defines distance between each color axis * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under * @param scene defines the hosting scene */ function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) { var _this = _super.call(this, name, position, scene) || this; _this.interaxialDistance = interaxialDistance; _this.isStereoscopicSideBySide = isStereoscopicSideBySide; _this.setCameraRigMode(isStereoscopicSideBySide ? _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance }); return _this; } /** * Gets camera class name * @returns StereoscopicUniversalCamera */ StereoscopicUniversalCamera.prototype.getClassName = function () { return "StereoscopicUniversalCamera"; }; return StereoscopicUniversalCamera; }(_Cameras_universalCamera__WEBPACK_IMPORTED_MODULE_2__["UniversalCamera"])); /***/ }), /***/ "./Cameras/VR/index.ts": /*!*****************************!*\ !*** ./Cameras/VR/index.ts ***! \*****************************/ /*! exports provided: VRCameraMetrics, VRDeviceOrientationArcRotateCamera, VRDeviceOrientationFreeCamera, VRDeviceOrientationGamepadCamera, OnAfterEnteringVRObservableEvent, VRExperienceHelper, WebVRFreeCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _vrCameraMetrics__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vrCameraMetrics */ "./Cameras/VR/vrCameraMetrics.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRCameraMetrics", function() { return _vrCameraMetrics__WEBPACK_IMPORTED_MODULE_0__["VRCameraMetrics"]; }); /* harmony import */ var _vrDeviceOrientationArcRotateCamera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vrDeviceOrientationArcRotateCamera */ "./Cameras/VR/vrDeviceOrientationArcRotateCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationArcRotateCamera", function() { return _vrDeviceOrientationArcRotateCamera__WEBPACK_IMPORTED_MODULE_1__["VRDeviceOrientationArcRotateCamera"]; }); /* harmony import */ var _vrDeviceOrientationFreeCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./vrDeviceOrientationFreeCamera */ "./Cameras/VR/vrDeviceOrientationFreeCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationFreeCamera", function() { return _vrDeviceOrientationFreeCamera__WEBPACK_IMPORTED_MODULE_2__["VRDeviceOrientationFreeCamera"]; }); /* harmony import */ var _vrDeviceOrientationGamepadCamera__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./vrDeviceOrientationGamepadCamera */ "./Cameras/VR/vrDeviceOrientationGamepadCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationGamepadCamera", function() { return _vrDeviceOrientationGamepadCamera__WEBPACK_IMPORTED_MODULE_3__["VRDeviceOrientationGamepadCamera"]; }); /* harmony import */ var _vrExperienceHelper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./vrExperienceHelper */ "./Cameras/VR/vrExperienceHelper.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OnAfterEnteringVRObservableEvent", function() { return _vrExperienceHelper__WEBPACK_IMPORTED_MODULE_4__["OnAfterEnteringVRObservableEvent"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRExperienceHelper", function() { return _vrExperienceHelper__WEBPACK_IMPORTED_MODULE_4__["VRExperienceHelper"]; }); /* harmony import */ var _webVRCamera__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./webVRCamera */ "./Cameras/VR/webVRCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebVRFreeCamera", function() { return _webVRCamera__WEBPACK_IMPORTED_MODULE_5__["WebVRFreeCamera"]; }); /***/ }), /***/ "./Cameras/VR/vrCameraMetrics.ts": /*!***************************************!*\ !*** ./Cameras/VR/vrCameraMetrics.ts ***! \***************************************/ /*! exports provided: VRCameraMetrics */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VRCameraMetrics", function() { return VRCameraMetrics; }); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /** * This represents all the required metrics to create a VR camera. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera */ var VRCameraMetrics = /** @class */ (function () { function VRCameraMetrics() { /** * Define if the current vr camera should compensate the distortion of the lense or not. */ this.compensateDistortion = true; /** * Defines if multiview should be enabled when rendering (Default: false) */ this.multiviewEnabled = false; } Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", { /** * Gets the rendering aspect ratio based on the provided resolutions. */ get: function () { return this.hResolution / (2 * this.vResolution); }, enumerable: true, configurable: true }); Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", { /** * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes. */ get: function () { return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance))); }, enumerable: true, configurable: true }); Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", { /** * @hidden */ get: function () { var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2); var h = (4 * meters) / this.hScreenSize; return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Translation(h, 0, 0); }, enumerable: true, configurable: true }); Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", { /** * @hidden */ get: function () { var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2); var h = (4 * meters) / this.hScreenSize; return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Translation(-h, 0, 0); }, enumerable: true, configurable: true }); Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", { /** * @hidden */ get: function () { return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Translation(0.5 * this.interpupillaryDistance, 0, 0); }, enumerable: true, configurable: true }); Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", { /** * @hidden */ get: function () { return _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Translation(-0.5 * this.interpupillaryDistance, 0, 0); }, enumerable: true, configurable: true }); /** * Get the default VRMetrics based on the most generic setup. * @returns the default vr metrics */ VRCameraMetrics.GetDefault = function () { var result = new VRCameraMetrics(); result.hResolution = 1280; result.vResolution = 800; result.hScreenSize = 0.149759993; result.vScreenSize = 0.0935999975; result.vScreenCenter = 0.0467999987; result.eyeToScreenDistance = 0.0410000011; result.lensSeparationDistance = 0.0635000020; result.interpupillaryDistance = 0.0640000030; result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0]; result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0]; result.postProcessScaleFactor = 1.714605507808412; result.lensCenterOffset = 0.151976421; return result; }; return VRCameraMetrics; }()); /***/ }), /***/ "./Cameras/VR/vrDeviceOrientationArcRotateCamera.ts": /*!**********************************************************!*\ !*** ./Cameras/VR/vrDeviceOrientationArcRotateCamera.ts ***! \**********************************************************/ /*! exports provided: VRDeviceOrientationArcRotateCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationArcRotateCamera", function() { return VRDeviceOrientationArcRotateCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/arcRotateCamera */ "./Cameras/arcRotateCamera.ts"); /* harmony import */ var _vrCameraMetrics__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./vrCameraMetrics */ "./Cameras/VR/vrCameraMetrics.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../node */ "./node.ts"); /* harmony import */ var _Inputs_arcRotateCameraVRDeviceOrientationInput__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Inputs/arcRotateCameraVRDeviceOrientationInput */ "./Cameras/Inputs/arcRotateCameraVRDeviceOrientationInput.ts"); /* harmony import */ var _RigModes_vrRigMode__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../RigModes/vrRigMode */ "./Cameras/RigModes/vrRigMode.ts"); // Side effect import to define the stereoscopic mode. _node__WEBPACK_IMPORTED_MODULE_5__["Node"].AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) { return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(), scene); }; }); /** * Camera used to simulate VR rendering (based on ArcRotateCamera) * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras */ var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](VRDeviceOrientationArcRotateCamera, _super); /** * Creates a new VRDeviceOrientationArcRotateCamera * @param name defines camera name * @param alpha defines the camera rotation along the logitudinal axis * @param beta defines the camera rotation along the latitudinal axis * @param radius defines the camera distance from its target * @param target defines the camera target * @param scene defines the scene the camera belongs to * @param compensateDistortion defines if the camera needs to compensate the lens distorsion * @param vrCameraMetrics defines the vr metrics associated to the camera */ function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) { if (compensateDistortion === void 0) { compensateDistortion = true; } if (vrCameraMetrics === void 0) { vrCameraMetrics = _vrCameraMetrics__WEBPACK_IMPORTED_MODULE_3__["VRCameraMetrics"].GetDefault(); } var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this; vrCameraMetrics.compensateDistortion = compensateDistortion; _this.setCameraRigMode(_Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics }); _this.inputs.addVRDeviceOrientation(); return _this; } /** * Gets camera class name * @returns VRDeviceOrientationArcRotateCamera */ VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () { return "VRDeviceOrientationArcRotateCamera"; }; return VRDeviceOrientationArcRotateCamera; }(_Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_2__["ArcRotateCamera"])); /***/ }), /***/ "./Cameras/VR/vrDeviceOrientationFreeCamera.ts": /*!*****************************************************!*\ !*** ./Cameras/VR/vrDeviceOrientationFreeCamera.ts ***! \*****************************************************/ /*! exports provided: VRDeviceOrientationFreeCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationFreeCamera", function() { return VRDeviceOrientationFreeCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Cameras_deviceOrientationCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/deviceOrientationCamera */ "./Cameras/deviceOrientationCamera.ts"); /* harmony import */ var _vrCameraMetrics__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./vrCameraMetrics */ "./Cameras/VR/vrCameraMetrics.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../node */ "./node.ts"); /* harmony import */ var _RigModes_vrRigMode__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../RigModes/vrRigMode */ "./Cameras/RigModes/vrRigMode.ts"); // Side effect import to define the stereoscopic mode. _node__WEBPACK_IMPORTED_MODULE_5__["Node"].AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) { return function () { return new VRDeviceOrientationFreeCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(), scene); }; }); /** * Camera used to simulate VR rendering (based on FreeCamera) * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras */ var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](VRDeviceOrientationFreeCamera, _super); /** * Creates a new VRDeviceOrientationFreeCamera * @param name defines camera name * @param position defines the start position of the camera * @param scene defines the scene the camera belongs to * @param compensateDistortion defines if the camera needs to compensate the lens distorsion * @param vrCameraMetrics defines the vr metrics associated to the camera */ function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) { if (compensateDistortion === void 0) { compensateDistortion = true; } if (vrCameraMetrics === void 0) { vrCameraMetrics = _vrCameraMetrics__WEBPACK_IMPORTED_MODULE_3__["VRCameraMetrics"].GetDefault(); } var _this = _super.call(this, name, position, scene) || this; vrCameraMetrics.compensateDistortion = compensateDistortion; _this.setCameraRigMode(_Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics }); return _this; } /** * Gets camera class name * @returns VRDeviceOrientationFreeCamera */ VRDeviceOrientationFreeCamera.prototype.getClassName = function () { return "VRDeviceOrientationFreeCamera"; }; return VRDeviceOrientationFreeCamera; }(_Cameras_deviceOrientationCamera__WEBPACK_IMPORTED_MODULE_2__["DeviceOrientationCamera"])); /***/ }), /***/ "./Cameras/VR/vrDeviceOrientationGamepadCamera.ts": /*!********************************************************!*\ !*** ./Cameras/VR/vrDeviceOrientationGamepadCamera.ts ***! \********************************************************/ /*! exports provided: VRDeviceOrientationGamepadCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationGamepadCamera", function() { return VRDeviceOrientationGamepadCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _vrDeviceOrientationFreeCamera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vrDeviceOrientationFreeCamera */ "./Cameras/VR/vrDeviceOrientationFreeCamera.ts"); /* harmony import */ var _vrCameraMetrics__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./vrCameraMetrics */ "./Cameras/VR/vrCameraMetrics.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); _node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) { return function () { return new VRDeviceOrientationGamepadCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), scene); }; }); /** * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera) * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras */ var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](VRDeviceOrientationGamepadCamera, _super); /** * Creates a new VRDeviceOrientationGamepadCamera * @param name defines camera name * @param position defines the start position of the camera * @param scene defines the scene the camera belongs to * @param compensateDistortion defines if the camera needs to compensate the lens distorsion * @param vrCameraMetrics defines the vr metrics associated to the camera */ function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) { if (compensateDistortion === void 0) { compensateDistortion = true; } if (vrCameraMetrics === void 0) { vrCameraMetrics = _vrCameraMetrics__WEBPACK_IMPORTED_MODULE_2__["VRCameraMetrics"].GetDefault(); } var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this; _this.inputs.addGamepad(); return _this; } /** * Gets camera class name * @returns VRDeviceOrientationGamepadCamera */ VRDeviceOrientationGamepadCamera.prototype.getClassName = function () { return "VRDeviceOrientationGamepadCamera"; }; return VRDeviceOrientationGamepadCamera; }(_vrDeviceOrientationFreeCamera__WEBPACK_IMPORTED_MODULE_1__["VRDeviceOrientationFreeCamera"])); /***/ }), /***/ "./Cameras/VR/vrExperienceHelper.ts": /*!******************************************!*\ !*** ./Cameras/VR/vrExperienceHelper.ts ***! \******************************************/ /*! exports provided: OnAfterEnteringVRObservableEvent, VRExperienceHelper */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OnAfterEnteringVRObservableEvent", function() { return OnAfterEnteringVRObservableEvent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VRExperienceHelper", function() { return VRExperienceHelper; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Cameras/freeCamera */ "./Cameras/freeCamera.ts"); /* harmony import */ var _Cameras_targetCamera__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Cameras/targetCamera */ "./Cameras/targetCamera.ts"); /* harmony import */ var _Cameras_deviceOrientationCamera__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Cameras/deviceOrientationCamera */ "./Cameras/deviceOrientationCamera.ts"); /* harmony import */ var _Cameras_VR_vrDeviceOrientationFreeCamera__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Cameras/VR/vrDeviceOrientationFreeCamera */ "./Cameras/VR/vrDeviceOrientationFreeCamera.ts"); /* harmony import */ var _Cameras_VR_webVRCamera__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Cameras/VR/webVRCamera */ "./Cameras/VR/webVRCamera.ts"); /* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../Gamepads/gamepad */ "./Gamepads/gamepad.ts"); /* harmony import */ var _Gamepads_Controllers_poseEnabledController__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../Gamepads/Controllers/poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts"); /* harmony import */ var _Gamepads_Controllers_webVRController__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../../Gamepads/Controllers/webVRController */ "./Gamepads/Controllers/webVRController.ts"); /* harmony import */ var _Gamepads_xboxGamepad__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../../Gamepads/xboxGamepad */ "./Gamepads/xboxGamepad.ts"); /* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../../Meshes/mesh */ "./Meshes/mesh.ts"); /* harmony import */ var _Culling_ray__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../../Culling/ray */ "./Culling/ray.ts"); /* harmony import */ var _Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../../Materials/imageProcessingConfiguration */ "./Materials/imageProcessingConfiguration.ts"); /* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../../Materials/standardMaterial */ "./Materials/standardMaterial.ts"); /* harmony import */ var _Materials_Textures_dynamicTexture__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../../Materials/Textures/dynamicTexture */ "./Materials/Textures/dynamicTexture.ts"); /* harmony import */ var _PostProcesses_imageProcessingPostProcess__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../../PostProcesses/imageProcessingPostProcess */ "./PostProcesses/imageProcessingPostProcess.ts"); /* harmony import */ var _Animations_easing__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../../Animations/easing */ "./Animations/easing.ts"); /* harmony import */ var _Animations_animation__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../../Animations/animation */ "./Animations/animation.ts"); /* harmony import */ var _Cameras_VR_vrCameraMetrics__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../../Cameras/VR/vrCameraMetrics */ "./Cameras/VR/vrCameraMetrics.ts"); /* harmony import */ var _Meshes_Builders_groundBuilder__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../../Meshes/Builders/groundBuilder */ "./Meshes/Builders/groundBuilder.ts"); /* harmony import */ var _Meshes_Builders_torusBuilder__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../../Meshes/Builders/torusBuilder */ "./Meshes/Builders/torusBuilder.ts"); /* harmony import */ var _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../../Meshes/Builders/cylinderBuilder */ "./Meshes/Builders/cylinderBuilder.ts"); /* harmony import */ var _Gamepads_gamepadSceneComponent__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../../Gamepads/gamepadSceneComponent */ "./Gamepads/gamepadSceneComponent.ts"); /* harmony import */ var _Animations_animatable__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ../../Animations/animatable */ "./Animations/animatable.ts"); var VRExperienceHelperGazer = /** @class */ (function () { function VRExperienceHelperGazer(scene, gazeTrackerToClone) { if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; } this.scene = scene; /** @hidden */ this._pointerDownOnMeshAsked = false; /** @hidden */ this._isActionableMesh = false; /** @hidden */ this._teleportationRequestInitiated = false; /** @hidden */ this._teleportationBackRequestInitiated = false; /** @hidden */ this._rotationRightAsked = false; /** @hidden */ this._rotationLeftAsked = false; /** @hidden */ this._dpadPressed = true; /** @hidden */ this._activePointer = false; this._id = VRExperienceHelperGazer._idCounter++; // Gaze tracker if (!gazeTrackerToClone) { this._gazeTracker = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_14__["Mesh"].CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false); this._gazeTracker.bakeCurrentTransformIntoVertices(); this._gazeTracker.isPickable = false; this._gazeTracker.isVisible = false; var targetMat = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_17__["StandardMaterial"]("targetMat", scene); targetMat.specularColor = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Color3"].Black(); targetMat.emissiveColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Color3"](0.7, 0.7, 0.7); targetMat.backFaceCulling = false; this._gazeTracker.material = targetMat; } else { this._gazeTracker = gazeTrackerToClone.clone("gazeTracker"); } } /** @hidden */ VRExperienceHelperGazer.prototype._getForwardRay = function (length) { return new _Culling_ray__WEBPACK_IMPORTED_MODULE_15__["Ray"](_Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Zero(), new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"](0, 0, length)); }; /** @hidden */ VRExperienceHelperGazer.prototype._selectionPointerDown = function () { this._pointerDownOnMeshAsked = true; if (this._currentHit) { this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id }); } }; /** @hidden */ VRExperienceHelperGazer.prototype._selectionPointerUp = function () { if (this._currentHit) { this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id }); } this._pointerDownOnMeshAsked = false; }; /** @hidden */ VRExperienceHelperGazer.prototype._activatePointer = function () { this._activePointer = true; }; /** @hidden */ VRExperienceHelperGazer.prototype._deactivatePointer = function () { this._activePointer = false; }; /** @hidden */ VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) { if (distance === void 0) { distance = 100; } }; VRExperienceHelperGazer.prototype.dispose = function () { this._interactionsEnabled = false; this._teleportationEnabled = false; if (this._gazeTracker) { this._gazeTracker.dispose(); } }; VRExperienceHelperGazer._idCounter = 0; return VRExperienceHelperGazer; }()); var VRExperienceHelperControllerGazer = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](VRExperienceHelperControllerGazer, _super); function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) { var _this = _super.call(this, scene, gazeTrackerToClone) || this; _this.webVRController = webVRController; // Laser pointer _this._laserPointer = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_14__["Mesh"].CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false); var laserPointerMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_17__["StandardMaterial"]("laserPointerMat", scene); laserPointerMaterial.emissiveColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Color3"](0.7, 0.7, 0.7); laserPointerMaterial.alpha = 0.6; _this._laserPointer.material = laserPointerMaterial; _this._laserPointer.rotation.x = Math.PI / 2; _this._laserPointer.position.z = -0.5; _this._laserPointer.isVisible = false; _this._laserPointer.isPickable = false; if (!webVRController.mesh) { // Create an empty mesh that is used prior to loading the high quality model var preloadMesh = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_14__["Mesh"]("preloadControllerMesh", scene); var preloadPointerPose = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_14__["Mesh"](_Gamepads_Controllers_poseEnabledController__WEBPACK_IMPORTED_MODULE_11__["PoseEnabledController"].POINTING_POSE, scene); preloadPointerPose.rotation.x = -0.7; preloadMesh.addChild(preloadPointerPose); webVRController.attachToMesh(preloadMesh); } _this._setLaserPointerParent(webVRController.mesh); _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) { _this._setLaserPointerParent(mesh); }); return _this; } VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) { return this.webVRController.getForwardRay(length); }; /** @hidden */ VRExperienceHelperControllerGazer.prototype._activatePointer = function () { _super.prototype._activatePointer.call(this); this._laserPointer.isVisible = true; }; /** @hidden */ VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () { _super.prototype._deactivatePointer.call(this); this._laserPointer.isVisible = false; }; /** @hidden */ VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) { this._laserPointer.material.emissiveColor = color; }; /** @hidden */ VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) { var makeNotPick = function (root) { root.isPickable = false; root.getChildMeshes().forEach(function (c) { makeNotPick(c); }); }; makeNotPick(mesh); var meshChildren = mesh.getChildren(undefined, false); var laserParent = mesh; this.webVRController._pointingPoseNode = null; for (var i = 0; i < meshChildren.length; i++) { if (meshChildren[i].name && meshChildren[i].name.indexOf(_Gamepads_Controllers_poseEnabledController__WEBPACK_IMPORTED_MODULE_11__["PoseEnabledController"].POINTING_POSE) >= 0) { laserParent = meshChildren[i]; this.webVRController._pointingPoseNode = laserParent; break; } } this._laserPointer.parent = laserParent; }; VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) { if (distance === void 0) { distance = 100; } this._laserPointer.scaling.y = distance; this._laserPointer.position.z = -distance / 2; }; VRExperienceHelperControllerGazer.prototype.dispose = function () { _super.prototype.dispose.call(this); this._laserPointer.dispose(); if (this._meshAttachedObserver) { this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver); } }; return VRExperienceHelperControllerGazer; }(VRExperienceHelperGazer)); var VRExperienceHelperCameraGazer = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](VRExperienceHelperCameraGazer, _super); function VRExperienceHelperCameraGazer(getCamera, scene) { var _this = _super.call(this, scene) || this; _this.getCamera = getCamera; return _this; } VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) { var camera = this.getCamera(); if (camera) { return camera.getForwardRay(length); } else { return new _Culling_ray__WEBPACK_IMPORTED_MODULE_15__["Ray"](_Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Zero(), _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Forward()); } }; return VRExperienceHelperCameraGazer; }(VRExperienceHelperGazer)); /** * Event containing information after VR has been entered */ var OnAfterEnteringVRObservableEvent = /** @class */ (function () { function OnAfterEnteringVRObservableEvent() { } return OnAfterEnteringVRObservableEvent; }()); /** * Helps to quickly add VR support to an existing scene. * See http://doc.babylonjs.com/how_to/webvr_helper */ var VRExperienceHelper = /** @class */ (function () { /** * Instantiates a VRExperienceHelper. * Helps to quickly add VR support to an existing scene. * @param scene The scene the VRExperienceHelper belongs to. * @param webVROptions Options to modify the vr experience helper's behavior. */ function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) { if (webVROptions === void 0) { webVROptions = {}; } var _this = this; this.webVROptions = webVROptions; // Can the system support WebVR, even if a headset isn't plugged in? this._webVRsupported = false; // If WebVR is supported, is a headset plugged in and are we ready to present? this._webVRready = false; // Are we waiting for the requestPresent callback to complete? this._webVRrequesting = false; // Are we presenting to the headset right now? (this is the vrDevice state) this._webVRpresenting = false; // Are we presenting in the fullscreen fallback? this._fullscreenVRpresenting = false; /** * Observable raised right before entering VR. */ this.onEnteringVRObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Observable raised when entering VR has completed. */ this.onAfterEnteringVRObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Observable raised when exiting VR. */ this.onExitingVRObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Observable raised when controller mesh is loaded. */ this.onControllerMeshLoadedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); this._useCustomVRButton = false; this._teleportationRequested = false; this._teleportActive = false; this._floorMeshesCollection = []; this._rotationAllowed = true; this._teleportBackwardsVector = new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"](0, -1, -1); this._isDefaultTeleportationTarget = true; this._teleportationFillColor = "#444444"; this._teleportationBorderColor = "#FFFFFF"; this._rotationAngle = 0; this._haloCenter = new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"](0, 0, 0); this._padSensibilityUp = 0.65; this._padSensibilityDown = 0.35; this._leftController = null; this._rightController = null; /** * Observable raised when a new mesh is selected based on meshSelectionPredicate */ this.onNewMeshSelected = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Observable raised when a new mesh is picked based on meshSelectionPredicate */ this.onNewMeshPicked = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Observable raised before camera teleportation */ this.onBeforeCameraTeleport = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Observable raised after camera teleportation */ this.onAfterCameraTeleport = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Observable raised when current selected mesh gets unselected */ this.onSelectedMeshUnselected = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept. */ this.teleportationEnabled = true; this._teleportationInitialized = false; this._interactionsEnabled = false; this._interactionsRequested = false; this._displayGaze = true; this._displayLaserPointer = true; /** * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes */ this.updateGazeTrackerScale = true; /** * If the gaze trackers color should be updated when selecting meshes */ this.updateGazeTrackerColor = true; /** * Defines wether or not Pointer lock should be requested when switching to * full screen. */ this.requestPointerLockOnFullScreen = true; this._onResize = function () { _this.moveButtonToBottomRight(); if (_this._fullscreenVRpresenting && _this._webVRready) { _this.exitVR(); } }; this._onFullscreenChange = function () { var anyDoc = document; if (anyDoc.fullscreen !== undefined) { _this._fullscreenVRpresenting = document.fullscreen; } else if (anyDoc.mozFullScreen !== undefined) { _this._fullscreenVRpresenting = anyDoc.mozFullScreen; } else if (anyDoc.webkitIsFullScreen !== undefined) { _this._fullscreenVRpresenting = anyDoc.webkitIsFullScreen; } else if (anyDoc.msIsFullScreen !== undefined) { _this._fullscreenVRpresenting = anyDoc.msIsFullScreen; } else if (document.msFullscreenElement !== undefined) { _this._fullscreenVRpresenting = document.msFullscreenElement; } if (!_this._fullscreenVRpresenting && _this._canvas) { _this.exitVR(); if (!_this._useCustomVRButton) { _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px"; _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px"; } } }; this._cachedAngularSensibility = { angularSensibilityX: null, angularSensibilityY: null, angularSensibility: null }; this.beforeRender = function () { if (_this._leftController && _this._leftController._activePointer) { _this._castRayAndSelectObject(_this._leftController); } if (_this._rightController && _this._rightController._activePointer) { _this._castRayAndSelectObject(_this._rightController); } if (_this._noControllerIsActive) { _this._castRayAndSelectObject(_this._cameraGazer); } else { _this._cameraGazer._gazeTracker.isVisible = false; } }; this._onNewGamepadConnected = function (gamepad) { if (gamepad.type !== _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_10__["Gamepad"].POSE_ENABLED) { if (gamepad.leftStick) { gamepad.onleftstickchanged(function (stickValues) { if (_this._teleportationInitialized && _this.teleportationEnabled) { // Listening to classic/xbox gamepad only if no VR controller is active if ((!_this._leftController && !_this._rightController) || ((_this._leftController && !_this._leftController._activePointer) && (_this._rightController && !_this._rightController._activePointer))) { _this._checkTeleportWithRay(stickValues, _this._cameraGazer); _this._checkTeleportBackwards(stickValues, _this._cameraGazer); } } }); } if (gamepad.rightStick) { gamepad.onrightstickchanged(function (stickValues) { if (_this._teleportationInitialized) { _this._checkRotate(stickValues, _this._cameraGazer); } }); } if (gamepad.type === _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_10__["Gamepad"].XBOX) { gamepad.onbuttondown(function (buttonPressed) { if (_this._interactionsEnabled && buttonPressed === _Gamepads_xboxGamepad__WEBPACK_IMPORTED_MODULE_13__["Xbox360Button"].A) { _this._cameraGazer._selectionPointerDown(); } }); gamepad.onbuttonup(function (buttonPressed) { if (_this._interactionsEnabled && buttonPressed === _Gamepads_xboxGamepad__WEBPACK_IMPORTED_MODULE_13__["Xbox360Button"].A) { _this._cameraGazer._selectionPointerUp(); } }); } } else { var webVRController = gamepad; var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker); if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) { _this._rightController = controller; } else { _this._leftController = controller; } _this._tryEnableInteractionOnController(controller); } }; // This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded this._tryEnableInteractionOnController = function (controller) { if (_this._interactionsRequested && !controller._interactionsEnabled) { _this._enableInteractionOnController(controller); } if (_this._teleportationRequested && !controller._teleportationEnabled) { _this._enableTeleportationOnController(controller); } }; this._onNewGamepadDisconnected = function (gamepad) { if (gamepad instanceof _Gamepads_Controllers_webVRController__WEBPACK_IMPORTED_MODULE_12__["WebVRController"]) { if (gamepad.hand === "left" && _this._leftController != null) { _this._leftController.dispose(); _this._leftController = null; } if (gamepad.hand === "right" && _this._rightController != null) { _this._rightController.dispose(); _this._rightController = null; } } }; this._workingVector = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Zero(); this._workingQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Quaternion"].Identity(); this._workingMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Matrix"].Identity(); this._scene = scene; this._canvas = scene.getEngine().getRenderingCanvas(); // Parse options if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) { webVROptions.createFallbackVRDeviceOrientationFreeCamera = true; } if (webVROptions.createDeviceOrientationCamera === undefined) { webVROptions.createDeviceOrientationCamera = true; } if (webVROptions.laserToggle === undefined) { webVROptions.laserToggle = true; } if (webVROptions.defaultHeight === undefined) { webVROptions.defaultHeight = 1.7; } if (webVROptions.useCustomVRButton) { this._useCustomVRButton = true; if (webVROptions.customVRButton) { this._btnVR = webVROptions.customVRButton; } } if (webVROptions.rayLength) { this._rayLength = webVROptions.rayLength; } this._defaultHeight = webVROptions.defaultHeight; if (webVROptions.positionScale) { this._rayLength *= webVROptions.positionScale; this._defaultHeight *= webVROptions.positionScale; } this._hasEnteredVR = false; // Set position if (this._scene.activeCamera) { this._position = this._scene.activeCamera.position.clone(); } else { this._position = new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"](0, this._defaultHeight, 0); } // Set non-vr camera if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) { this._deviceOrientationCamera = new _Cameras_deviceOrientationCamera__WEBPACK_IMPORTED_MODULE_5__["DeviceOrientationCamera"]("deviceOrientationVRHelper", this._position.clone(), scene); // Copy data from existing camera if (this._scene.activeCamera) { this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ; this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ; // Set rotation from previous camera if (this._scene.activeCamera instanceof _Cameras_targetCamera__WEBPACK_IMPORTED_MODULE_4__["TargetCamera"] && this._scene.activeCamera.rotation) { var targetCamera = this._scene.activeCamera; if (targetCamera.rotationQuaternion) { this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion); } else { this._deviceOrientationCamera.rotationQuaternion.copyFrom(_Maths_math__WEBPACK_IMPORTED_MODULE_9__["Quaternion"].RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z)); } this._deviceOrientationCamera.rotation = targetCamera.rotation.clone(); } } this._scene.activeCamera = this._deviceOrientationCamera; if (this._canvas) { this._scene.activeCamera.attachControl(this._canvas); } } else { this._existingCamera = this._scene.activeCamera; } // Create VR cameras if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) { if (webVROptions.useMultiview) { if (!webVROptions.vrDeviceOrientationCameraMetrics) { webVROptions.vrDeviceOrientationCameraMetrics = _Cameras_VR_vrCameraMetrics__WEBPACK_IMPORTED_MODULE_22__["VRCameraMetrics"].GetDefault(); } webVROptions.vrDeviceOrientationCameraMetrics.multiviewEnabled = true; } this._vrDeviceOrientationCamera = new _Cameras_VR_vrDeviceOrientationFreeCamera__WEBPACK_IMPORTED_MODULE_6__["VRDeviceOrientationFreeCamera"]("VRDeviceOrientationVRHelper", this._position, this._scene, true, webVROptions.vrDeviceOrientationCameraMetrics); this._vrDeviceOrientationCamera.angularSensibility = Number.MAX_VALUE; } this._webVRCamera = new _Cameras_VR_webVRCamera__WEBPACK_IMPORTED_MODULE_7__["WebVRFreeCamera"]("WebVRHelper", this._position, this._scene, webVROptions); this._webVRCamera.useStandingMatrix(); this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene); // Create default button if (!this._useCustomVRButton) { this._btnVR = document.createElement("BUTTON"); this._btnVR.className = "babylonVRicon"; this._btnVR.id = "babylonVRiconbtn"; this._btnVR.title = "Click to switch to VR"; var css = ".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }"; css += ".babylonVRicon.vrdisplaypresenting { display: none; }"; // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR) // css += ".babylonVRicon.vrdisplaysupported { }"; // css += ".babylonVRicon.vrdisplayready { }"; // css += ".babylonVRicon.vrdisplayrequesting { }"; var style = document.createElement('style'); style.appendChild(document.createTextNode(css)); document.getElementsByTagName('head')[0].appendChild(style); this.moveButtonToBottomRight(); } // VR button click event if (this._btnVR) { this._btnVR.addEventListener("click", function () { if (!_this.isInVRMode) { _this.enterVR(); } else { _this.exitVR(); } }); } // Window events window.addEventListener("resize", this._onResize); document.addEventListener("fullscreenchange", this._onFullscreenChange, false); document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false); document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false); document.addEventListener("msfullscreenchange", this._onFullscreenChange, false); document.onmsfullscreenchange = this._onFullscreenChange; // Display vr button when headset is connected if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) { this.displayVRButton(); } else { this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) { if (e.vrDisplay) { _this.displayVRButton(); } }); } // Exiting VR mode using 'ESC' key on desktop this._onKeyDown = function (event) { if (event.keyCode === 27 && _this.isInVRMode) { _this.exitVR(); } }; document.addEventListener("keydown", this._onKeyDown); // Exiting VR mode double tapping the touch screen this._scene.onPrePointerObservable.add(function () { if (_this.isInVRMode) { _this.exitVR(); if (_this._fullscreenVRpresenting) { _this._scene.getEngine().exitFullscreen(); } } }, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_8__["PointerEventTypes"].POINTERDOUBLETAP, false); // Listen for WebVR display changes this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); }; this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); }; this._onVRRequestPresentStart = function () { _this._webVRrequesting = true; _this.updateButtonVisibility(); }; this._onVRRequestPresentComplete = function () { _this._webVRrequesting = false; _this.updateButtonVisibility(); }; scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged); scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart); scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete); window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange); scene.onDisposeObservable.add(function () { _this.dispose(); }); // Gamepad connection events this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); }); this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected); this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected); this.updateButtonVisibility(); //create easing functions this._circleEase = new _Animations_easing__WEBPACK_IMPORTED_MODULE_20__["CircleEase"](); this._circleEase.setEasingMode(_Animations_easing__WEBPACK_IMPORTED_MODULE_20__["EasingFunction"].EASINGMODE_EASEINOUT); if (this.webVROptions.floorMeshes) { this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes }); } } Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", { /** Return this.onEnteringVRObservable * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly */ get: function () { return this.onEnteringVRObservable; }, enumerable: true, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", { /** Return this.onExitingVRObservable * Note: This one is for backward compatibility. Please use onExitingVRObservable directly */ get: function () { return this.onExitingVRObservable; }, enumerable: true, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", { /** Return this.onControllerMeshLoadedObservable * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly */ get: function () { return this.onControllerMeshLoadedObservable; }, enumerable: true, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", { /** * The mesh used to display where the user is going to teleport. */ get: function () { return this._teleportationTarget; }, /** * Sets the mesh to be used to display where the user is going to teleport. */ set: function (value) { if (value) { value.name = "teleportationTarget"; this._isDefaultTeleportationTarget = false; this._teleportationTarget = value; } }, enumerable: true, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", { /** * The mesh used to display where the user is selecting, this mesh will be cloned and set as the gazeTracker for the left and right controller * when set bakeCurrentTransformIntoVertices will be called on the mesh. * See http://doc.babylonjs.com/resources/baking_transformations */ get: function () { return this._cameraGazer._gazeTracker; }, set: function (value) { if (value) { // Dispose of existing meshes if (this._cameraGazer._gazeTracker) { this._cameraGazer._gazeTracker.dispose(); } if (this._leftController && this._leftController._gazeTracker) { this._leftController._gazeTracker.dispose(); } if (this._rightController && this._rightController._gazeTracker) { this._rightController._gazeTracker.dispose(); } // Set and create gaze trackers on head and controllers this._cameraGazer._gazeTracker = value; this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(); this._cameraGazer._gazeTracker.isPickable = false; this._cameraGazer._gazeTracker.isVisible = false; this._cameraGazer._gazeTracker.name = "gazeTracker"; if (this._leftController) { this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker"); } if (this._rightController) { this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker"); } } }, enumerable: true, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", { /** * The gaze tracking mesh corresponding to the left controller */ get: function () { if (this._leftController) { return this._leftController._gazeTracker; } return null; }, enumerable: true, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", { /** * The gaze tracking mesh corresponding to the right controller */ get: function () { if (this._rightController) { return this._rightController._gazeTracker; } return null; }, enumerable: true, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", { /** * If the ray of the gaze should be displayed. */ get: function () { return this._displayGaze; }, /** * Sets if the ray of the gaze should be displayed. */ set: function (value) { this._displayGaze = value; if (!value) { this._cameraGazer._gazeTracker.isVisible = false; if (this._leftController) { this._leftController._gazeTracker.isVisible = false; } if (this._rightController) { this._rightController._gazeTracker.isVisible = false; } } }, enumerable: true, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", { /** * If the ray of the LaserPointer should be displayed. */ get: function () { return this._displayLaserPointer; }, /** * Sets if the ray of the LaserPointer should be displayed. */ set: function (value) { this._displayLaserPointer = value; if (!value) { if (this._rightController) { this._rightController._deactivatePointer(); this._rightController._gazeTracker.isVisible = false; } if (this._leftController) { this._leftController._deactivatePointer(); this._leftController._gazeTracker.isVisible = false; } } else { if (this._rightController) { this._rightController._activatePointer(); } if (this._leftController) { this._leftController._activatePointer(); } } }, enumerable: true, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", { /** * The deviceOrientationCamera used as the camera when not in VR. */ get: function () { return this._deviceOrientationCamera; }, enumerable: true, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", { /** * Based on the current WebVR support, returns the current VR camera used. */ get: function () { if (this._webVRready) { return this._webVRCamera; } else { return this._scene.activeCamera; } }, enumerable: true, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", { /** * The webVRCamera which is used when in VR. */ get: function () { return this._webVRCamera; }, enumerable: true, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", { /** * The deviceOrientationCamera that is used as a fallback when vr device is not connected. */ get: function () { return this._vrDeviceOrientationCamera; }, enumerable: true, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", { get: function () { var result = this._cameraGazer._teleportationRequestInitiated || (this._leftController !== null && this._leftController._teleportationRequestInitiated) || (this._rightController !== null && this._rightController._teleportationRequestInitiated); return result; }, enumerable: true, configurable: true }); // Raised when one of the controller has loaded successfully its associated default mesh VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) { if (this._leftController && this._leftController.webVRController == webVRController) { if (webVRController.mesh) { this._leftController._setLaserPointerParent(webVRController.mesh); } } if (this._rightController && this._rightController.webVRController == webVRController) { if (webVRController.mesh) { this._rightController._setLaserPointerParent(webVRController.mesh); } } try { this.onControllerMeshLoadedObservable.notifyObservers(webVRController); } catch (err) { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Error in your custom logic onControllerMeshLoaded: " + err); } }; Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", { /** * Gets a value indicating if we are currently in VR mode. */ get: function () { return this._webVRpresenting || this._fullscreenVRpresenting; }, enumerable: true, configurable: true }); VRExperienceHelper.prototype.onVrDisplayPresentChange = function () { var vrDisplay = this._scene.getEngine().getVRDevice(); if (vrDisplay) { var wasPresenting = this._webVRpresenting; this._webVRpresenting = vrDisplay.isPresenting; if (wasPresenting && !this._webVRpresenting) { this.exitVR(); } } else { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?'); } this.updateButtonVisibility(); }; VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) { this._webVRsupported = eventArgs.vrSupported; this._webVRready = !!eventArgs.vrDisplay; this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting; this.updateButtonVisibility(); }; VRExperienceHelper.prototype.moveButtonToBottomRight = function () { if (this._canvas && !this._useCustomVRButton) { this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px"; this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px"; } }; VRExperienceHelper.prototype.displayVRButton = function () { if (!this._useCustomVRButton && !this._btnVRDisplayed) { document.body.appendChild(this._btnVR); this._btnVRDisplayed = true; } }; VRExperienceHelper.prototype.updateButtonVisibility = function () { if (!this._btnVR || this._useCustomVRButton) { return; } this._btnVR.className = "babylonVRicon"; if (this.isInVRMode) { this._btnVR.className += " vrdisplaypresenting"; } else { if (this._webVRready) { this._btnVR.className += " vrdisplayready"; } if (this._webVRsupported) { this._btnVR.className += " vrdisplaysupported"; } if (this._webVRrequesting) { this._btnVR.className += " vrdisplayrequesting"; } } }; /** * Attempt to enter VR. If a headset is connected and ready, will request present on that. * Otherwise, will use the fullscreen API. */ VRExperienceHelper.prototype.enterVR = function () { var _this = this; if (this.onEnteringVRObservable) { try { this.onEnteringVRObservable.notifyObservers(this); } catch (err) { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Error in your custom logic onEnteringVR: " + err); } } if (this._scene.activeCamera) { this._position = this._scene.activeCamera.position.clone(); if (this.vrDeviceOrientationCamera) { this.vrDeviceOrientationCamera.rotation = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Quaternion"].FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(); this.vrDeviceOrientationCamera.angularSensibility = 2000; } if (this.webVRCamera) { var currentYRotation = this.webVRCamera.deviceRotationQuaternion.toEulerAngles().y; var desiredYRotation = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Quaternion"].FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles().y; var delta = desiredYRotation - currentYRotation; var currentGlobalRotation = this.webVRCamera.rotationQuaternion.toEulerAngles().y; this.webVRCamera.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Quaternion"].FromEulerAngles(0, currentGlobalRotation + delta, 0); } // make sure that we return to the last active camera this._existingCamera = this._scene.activeCamera; // Remove and cache angular sensability to avoid camera rotation when in VR if (this._existingCamera.angularSensibilityX) { this._cachedAngularSensibility.angularSensibilityX = this._existingCamera.angularSensibilityX; this._existingCamera.angularSensibilityX = Number.MAX_VALUE; } if (this._existingCamera.angularSensibilityY) { this._cachedAngularSensibility.angularSensibilityY = this._existingCamera.angularSensibilityY; this._existingCamera.angularSensibilityY = Number.MAX_VALUE; } if (this._existingCamera.angularSensibility) { this._cachedAngularSensibility.angularSensibility = this._existingCamera.angularSensibility; this._existingCamera.angularSensibility = Number.MAX_VALUE; } } if (this._webVRrequesting) { return; } // If WebVR is supported and a headset is connected if (this._webVRready) { if (!this._webVRpresenting) { this._scene.getEngine().onVRRequestPresentComplete.addOnce(function (result) { _this.onAfterEnteringVRObservable.notifyObservers({ success: result }); }); this._webVRCamera.position = this._position; this._scene.activeCamera = this._webVRCamera; } } else if (this._vrDeviceOrientationCamera) { this._vrDeviceOrientationCamera.position = this._position; if (this._scene.activeCamera) { this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ; } this._scene.activeCamera = this._vrDeviceOrientationCamera; this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen); this.updateButtonVisibility(); this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce(function () { _this.onAfterEnteringVRObservable.notifyObservers({ success: true }); }); } if (this._scene.activeCamera && this._canvas) { this._scene.activeCamera.attachControl(this._canvas); } if (this._interactionsEnabled) { this._scene.registerBeforeRender(this.beforeRender); } if (this._displayLaserPointer) { [this._leftController, this._rightController].forEach(function (controller) { if (controller) { controller._activatePointer(); } }); } this._hasEnteredVR = true; }; /** * Attempt to exit VR, or fullscreen. */ VRExperienceHelper.prototype.exitVR = function () { if (this._hasEnteredVR) { if (this.onExitingVRObservable) { try { this.onExitingVRObservable.notifyObservers(this); } catch (err) { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Error in your custom logic onExitingVR: " + err); } } if (this._webVRpresenting) { this._scene.getEngine().disableVR(); } if (this._scene.activeCamera) { this._position = this._scene.activeCamera.position.clone(); } if (this.vrDeviceOrientationCamera) { this.vrDeviceOrientationCamera.angularSensibility = Number.MAX_VALUE; } if (this._deviceOrientationCamera) { this._deviceOrientationCamera.position = this._position; this._scene.activeCamera = this._deviceOrientationCamera; if (this._canvas) { this._scene.activeCamera.attachControl(this._canvas); } // Restore angular sensibility if (this._cachedAngularSensibility.angularSensibilityX) { this._deviceOrientationCamera.angularSensibilityX = this._cachedAngularSensibility.angularSensibilityX; this._cachedAngularSensibility.angularSensibilityX = null; } if (this._cachedAngularSensibility.angularSensibilityY) { this._deviceOrientationCamera.angularSensibilityY = this._cachedAngularSensibility.angularSensibilityY; this._cachedAngularSensibility.angularSensibilityY = null; } if (this._cachedAngularSensibility.angularSensibility) { this._deviceOrientationCamera.angularSensibility = this._cachedAngularSensibility.angularSensibility; this._cachedAngularSensibility.angularSensibility = null; } } else if (this._existingCamera) { this._existingCamera.position = this._position; this._scene.activeCamera = this._existingCamera; // Restore angular sensibility if (this._cachedAngularSensibility.angularSensibilityX) { this._existingCamera.angularSensibilityX = this._cachedAngularSensibility.angularSensibilityX; this._cachedAngularSensibility.angularSensibilityX = null; } if (this._cachedAngularSensibility.angularSensibilityY) { this._existingCamera.angularSensibilityY = this._cachedAngularSensibility.angularSensibilityY; this._cachedAngularSensibility.angularSensibilityY = null; } if (this._cachedAngularSensibility.angularSensibility) { this._existingCamera.angularSensibility = this._cachedAngularSensibility.angularSensibility; this._cachedAngularSensibility.angularSensibility = null; } } this.updateButtonVisibility(); if (this._interactionsEnabled) { this._scene.unregisterBeforeRender(this.beforeRender); this._cameraGazer._gazeTracker.isVisible = false; if (this._leftController) { this._leftController._gazeTracker.isVisible = false; } if (this._rightController) { this._rightController._gazeTracker.isVisible = false; } } // resize to update width and height when exiting vr exits fullscreen this._scene.getEngine().resize(); [this._leftController, this._rightController].forEach(function (controller) { if (controller) { controller._deactivatePointer(); } }); this._hasEnteredVR = false; } }; Object.defineProperty(VRExperienceHelper.prototype, "position", { /** * The position of the vr experience helper. */ get: function () { return this._position; }, /** * Sets the position of the vr experience helper. */ set: function (value) { this._position = value; if (this._scene.activeCamera) { this._scene.activeCamera.position = value; } }, enumerable: true, configurable: true }); /** * Enables controllers and user interactions such as selecting and object or clicking on an object. */ VRExperienceHelper.prototype.enableInteractions = function () { var _this = this; if (!this._interactionsEnabled) { this._interactionsRequested = true; if (this._leftController) { this._enableInteractionOnController(this._leftController); } if (this._rightController) { this._enableInteractionOnController(this._rightController); } this.raySelectionPredicate = function (mesh) { return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName); }; this.meshSelectionPredicate = function () { return true; }; this._raySelectionPredicate = function (mesh) { if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1 && mesh.name.indexOf("teleportationTarget") === -1 && mesh.name.indexOf("torusTeleportation") === -1)) { return _this.raySelectionPredicate(mesh); } return false; }; this._interactionsEnabled = true; } }; Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", { get: function () { return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer); }, enumerable: true, configurable: true }); VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) { for (var i = 0; i < this._floorMeshesCollection.length; i++) { if (this._floorMeshesCollection[i].id === mesh.id) { return true; } } if (this._floorMeshName && mesh.name === this._floorMeshName) { return true; } return false; }; /** * Adds a floor mesh to be used for teleportation. * @param floorMesh the mesh to be used for teleportation. */ VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) { if (!this._floorMeshesCollection) { return; } if (this._floorMeshesCollection.indexOf(floorMesh) > -1) { return; } this._floorMeshesCollection.push(floorMesh); }; /** * Removes a floor mesh from being used for teleportation. * @param floorMesh the mesh to be removed. */ VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) { if (!this._floorMeshesCollection) { return; } var meshIndex = this._floorMeshesCollection.indexOf(floorMesh); if (meshIndex !== -1) { this._floorMeshesCollection.splice(meshIndex, 1); } }; /** * Enables interactions and teleportation using the VR controllers and gaze. * @param vrTeleportationOptions options to modify teleportation behavior. */ VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) { if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; } if (!this._teleportationInitialized) { this._teleportationRequested = true; this.enableInteractions(); if (vrTeleportationOptions.floorMeshName) { this._floorMeshName = vrTeleportationOptions.floorMeshName; } if (vrTeleportationOptions.floorMeshes) { this._floorMeshesCollection = vrTeleportationOptions.floorMeshes; } if (this._leftController != null) { this._enableTeleportationOnController(this._leftController); } if (this._rightController != null) { this._enableTeleportationOnController(this._rightController); } // Creates an image processing post process for the vignette not relying // on the main scene configuration for image processing to reduce setup and spaces // (gamma/linear) conflicts. var imageProcessingConfiguration = new _Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_16__["ImageProcessingConfiguration"](); imageProcessingConfiguration.vignetteColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Color4"](0, 0, 0, 0); imageProcessingConfiguration.vignetteEnabled = true; this._postProcessMove = new _PostProcesses_imageProcessingPostProcess__WEBPACK_IMPORTED_MODULE_19__["ImageProcessingPostProcess"]("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration); this._webVRCamera.detachPostProcess(this._postProcessMove); this._teleportationInitialized = true; if (this._isDefaultTeleportationTarget) { this._createTeleportationCircles(); this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor); } } }; VRExperienceHelper.prototype._enableInteractionOnController = function (controller) { var _this = this; var controllerMesh = controller.webVRController.mesh; if (controllerMesh) { controller._interactionsEnabled = true; if (this.isInVRMode && this._displayLaserPointer) { controller._activatePointer(); } if (this.webVROptions.laserToggle) { controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) { // Enabling / disabling laserPointer if (_this._displayLaserPointer && stateObject.value === 1) { if (controller._activePointer) { controller._deactivatePointer(); } else { controller._activatePointer(); } if (_this.displayGaze) { controller._gazeTracker.isVisible = controller._activePointer; } } }); } controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) { var gazer = controller; if (_this._noControllerIsActive) { gazer = _this._cameraGazer; } if (!gazer._pointerDownOnMeshAsked) { if (stateObject.value > _this._padSensibilityUp) { gazer._selectionPointerDown(); } } else if (stateObject.value < _this._padSensibilityDown) { gazer._selectionPointerUp(); } }); } }; VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) { // Dont teleport if another gaze already requested teleportation if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) { return; } if (!gazer._teleportationRequestInitiated) { if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) { gazer._activatePointer(); gazer._teleportationRequestInitiated = true; } } else { // Listening to the proper controller values changes to confirm teleportation if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) { if (this._teleportActive) { this.teleportCamera(this._haloCenter); } gazer._teleportationRequestInitiated = false; } } }; VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) { // Only rotate when user is not currently selecting a teleportation location if (gazer._teleportationRequestInitiated) { return; } if (!gazer._rotationLeftAsked) { if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) { gazer._rotationLeftAsked = true; if (this._rotationAllowed) { this._rotateCamera(false); } } } else { if (stateObject.x > -this._padSensibilityDown) { gazer._rotationLeftAsked = false; } } if (!gazer._rotationRightAsked) { if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) { gazer._rotationRightAsked = true; if (this._rotationAllowed) { this._rotateCamera(true); } } } else { if (stateObject.x < this._padSensibilityDown) { gazer._rotationRightAsked = false; } } }; VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) { // Only teleport backwards when user is not currently selecting a teleportation location if (gazer._teleportationRequestInitiated) { return; } // Teleport backwards if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) { if (!gazer._teleportationBackRequestInitiated) { if (!this.currentVRCamera) { return; } // Get rotation and position of the current camera var rotation = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Quaternion"].FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()); var position = this.currentVRCamera.position; // If the camera has device position, use that instead if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) { rotation = this.currentVRCamera.deviceRotationQuaternion; position = this.currentVRCamera.devicePosition; } // Get matrix with only the y rotation of the device rotation rotation.toEulerAnglesToRef(this._workingVector); this._workingVector.z = 0; this._workingVector.x = 0; _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Quaternion"].RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion); this._workingQuaternion.toRotationMatrix(this._workingMatrix); // Rotate backwards ray by device rotation to cast at the ground behind the user _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"].TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector); // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff var ray = new _Culling_ray__WEBPACK_IMPORTED_MODULE_15__["Ray"](position, this._workingVector); var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate); if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) { this.teleportCamera(hit.pickedPoint); } gazer._teleportationBackRequestInitiated = true; } } else { gazer._teleportationBackRequestInitiated = false; } }; VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) { var _this = this; var controllerMesh = controller.webVRController.mesh; if (controllerMesh) { if (!controller._interactionsEnabled) { this._enableInteractionOnController(controller); } controller._interactionsEnabled = true; controller._teleportationEnabled = true; if (controller.webVRController.controllerType === _Gamepads_Controllers_poseEnabledController__WEBPACK_IMPORTED_MODULE_11__["PoseEnabledControllerType"].VIVE) { controller._dpadPressed = false; controller.webVRController.onPadStateChangedObservable.add(function (stateObject) { controller._dpadPressed = stateObject.pressed; if (!controller._dpadPressed) { controller._rotationLeftAsked = false; controller._rotationRightAsked = false; controller._teleportationBackRequestInitiated = false; } }); } controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) { if (_this.teleportationEnabled) { _this._checkTeleportBackwards(stateObject, controller); _this._checkTeleportWithRay(stateObject, controller); } _this._checkRotate(stateObject, controller); }); } }; VRExperienceHelper.prototype._createTeleportationCircles = function () { this._teleportationTarget = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_14__["Mesh"].CreateGround("teleportationTarget", 2, 2, 2, this._scene); this._teleportationTarget.isPickable = false; var length = 512; var dynamicTexture = new _Materials_Textures_dynamicTexture__WEBPACK_IMPORTED_MODULE_18__["DynamicTexture"]("DynamicTexture", length, this._scene, true); dynamicTexture.hasAlpha = true; var context = dynamicTexture.getContext(); var centerX = length / 2; var centerY = length / 2; var radius = 200; context.beginPath(); context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false); context.fillStyle = this._teleportationFillColor; context.fill(); context.lineWidth = 10; context.strokeStyle = this._teleportationBorderColor; context.stroke(); context.closePath(); dynamicTexture.update(); var teleportationCircleMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_17__["StandardMaterial"]("TextPlaneMaterial", this._scene); teleportationCircleMaterial.diffuseTexture = dynamicTexture; this._teleportationTarget.material = teleportationCircleMaterial; var torus = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_14__["Mesh"].CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false); torus.isPickable = false; torus.parent = this._teleportationTarget; var animationInnerCircle = new _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"]("animationInnerCircle", "position.y", 30, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONTYPE_FLOAT, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONLOOPMODE_CYCLE); var keys = []; keys.push({ frame: 0, value: 0 }); keys.push({ frame: 30, value: 0.4 }); keys.push({ frame: 60, value: 0 }); animationInnerCircle.setKeys(keys); var easingFunction = new _Animations_easing__WEBPACK_IMPORTED_MODULE_20__["SineEase"](); easingFunction.setEasingMode(_Animations_easing__WEBPACK_IMPORTED_MODULE_20__["EasingFunction"].EASINGMODE_EASEINOUT); animationInnerCircle.setEasingFunction(easingFunction); torus.animations = []; torus.animations.push(animationInnerCircle); this._scene.beginAnimation(torus, 0, 60, true); this._hideTeleportationTarget(); }; VRExperienceHelper.prototype._displayTeleportationTarget = function () { this._teleportActive = true; if (this._teleportationInitialized) { this._teleportationTarget.isVisible = true; if (this._isDefaultTeleportationTarget) { this._teleportationTarget.getChildren()[0].isVisible = true; } } }; VRExperienceHelper.prototype._hideTeleportationTarget = function () { this._teleportActive = false; if (this._teleportationInitialized) { this._teleportationTarget.isVisible = false; if (this._isDefaultTeleportationTarget) { this._teleportationTarget.getChildren()[0].isVisible = false; } } }; VRExperienceHelper.prototype._rotateCamera = function (right) { var _this = this; if (!(this.currentVRCamera instanceof _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_3__["FreeCamera"])) { return; } if (right) { this._rotationAngle++; } else { this._rotationAngle--; } this.currentVRCamera.animations = []; var target = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Quaternion"].FromRotationMatrix(_Maths_math__WEBPACK_IMPORTED_MODULE_9__["Matrix"].RotationY(Math.PI / 4 * this._rotationAngle)); var animationRotation = new _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"]("animationRotation", "rotationQuaternion", 90, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONTYPE_QUATERNION, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONLOOPMODE_CONSTANT); var animationRotationKeys = []; animationRotationKeys.push({ frame: 0, value: this.currentVRCamera.rotationQuaternion }); animationRotationKeys.push({ frame: 6, value: target }); animationRotation.setKeys(animationRotationKeys); animationRotation.setEasingFunction(this._circleEase); this.currentVRCamera.animations.push(animationRotation); this._postProcessMove.animations = []; var animationPP = new _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"]("animationPP", "vignetteWeight", 90, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONTYPE_FLOAT, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONLOOPMODE_CONSTANT); var vignetteWeightKeys = []; vignetteWeightKeys.push({ frame: 0, value: 0 }); vignetteWeightKeys.push({ frame: 3, value: 4 }); vignetteWeightKeys.push({ frame: 6, value: 0 }); animationPP.setKeys(vignetteWeightKeys); animationPP.setEasingFunction(this._circleEase); this._postProcessMove.animations.push(animationPP); var animationPP2 = new _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"]("animationPP2", "vignetteStretch", 90, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONTYPE_FLOAT, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONLOOPMODE_CONSTANT); var vignetteStretchKeys = []; vignetteStretchKeys.push({ frame: 0, value: 0 }); vignetteStretchKeys.push({ frame: 3, value: 10 }); vignetteStretchKeys.push({ frame: 6, value: 0 }); animationPP2.setKeys(vignetteStretchKeys); animationPP2.setEasingFunction(this._circleEase); this._postProcessMove.animations.push(animationPP2); this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0; this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0; this._postProcessMove.samples = 4; this._webVRCamera.attachPostProcess(this._postProcessMove); this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () { _this._webVRCamera.detachPostProcess(_this._postProcessMove); }); this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1); }; VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) { if (hit.pickedPoint) { if (gazer._teleportationRequestInitiated) { this._displayTeleportationTarget(); this._haloCenter.copyFrom(hit.pickedPoint); this._teleportationTarget.position.copyFrom(hit.pickedPoint); } var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray); if (pickNormal) { var axis1 = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Cross(_Maths_math__WEBPACK_IMPORTED_MODULE_9__["Axis"].Y, pickNormal); var axis2 = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Cross(pickNormal, axis1); _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"].RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation); } this._teleportationTarget.position.y += 0.1; } }; /** * Teleports the users feet to the desired location * @param location The location where the user's feet should be placed */ VRExperienceHelper.prototype.teleportCamera = function (location) { var _this = this; if (!(this.currentVRCamera instanceof _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_3__["FreeCamera"])) { return; } // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the // offset of the headset from the anchor. if (this.webVRCamera.leftCamera) { this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition); this._workingVector.subtractInPlace(this.webVRCamera.position); location.subtractToRef(this._workingVector, this._workingVector); } else { this._workingVector.copyFrom(location); } // Add height to account for user's height offset if (this.isInVRMode) { this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor; } else { this._workingVector.y += this._defaultHeight; } this.onBeforeCameraTeleport.notifyObservers(this._workingVector); // Create animation from the camera's position to the new location this.currentVRCamera.animations = []; var animationCameraTeleportation = new _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"]("animationCameraTeleportation", "position", 90, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONTYPE_VECTOR3, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONLOOPMODE_CONSTANT); var animationCameraTeleportationKeys = [{ frame: 0, value: this.currentVRCamera.position }, { frame: 11, value: this._workingVector } ]; animationCameraTeleportation.setKeys(animationCameraTeleportationKeys); animationCameraTeleportation.setEasingFunction(this._circleEase); this.currentVRCamera.animations.push(animationCameraTeleportation); this._postProcessMove.animations = []; var animationPP = new _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"]("animationPP", "vignetteWeight", 90, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONTYPE_FLOAT, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONLOOPMODE_CONSTANT); var vignetteWeightKeys = []; vignetteWeightKeys.push({ frame: 0, value: 0 }); vignetteWeightKeys.push({ frame: 5, value: 8 }); vignetteWeightKeys.push({ frame: 11, value: 0 }); animationPP.setKeys(vignetteWeightKeys); this._postProcessMove.animations.push(animationPP); var animationPP2 = new _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"]("animationPP2", "vignetteStretch", 90, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONTYPE_FLOAT, _Animations_animation__WEBPACK_IMPORTED_MODULE_21__["Animation"].ANIMATIONLOOPMODE_CONSTANT); var vignetteStretchKeys = []; vignetteStretchKeys.push({ frame: 0, value: 0 }); vignetteStretchKeys.push({ frame: 5, value: 10 }); vignetteStretchKeys.push({ frame: 11, value: 0 }); animationPP2.setKeys(vignetteStretchKeys); this._postProcessMove.animations.push(animationPP2); this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0; this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0; this._webVRCamera.attachPostProcess(this._postProcessMove); this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () { _this._webVRCamera.detachPostProcess(_this._postProcessMove); }); this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () { _this.onAfterCameraTeleport.notifyObservers(_this._workingVector); }); this._hideTeleportationTarget(); }; VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) { if (normal) { var angle = Math.acos(_Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Dot(normal, ray.direction)); if (angle < Math.PI / 2) { normal.scaleInPlace(-1); } } return normal; }; VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) { if (!(this.currentVRCamera instanceof _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_3__["FreeCamera"])) { return; } var ray = gazer._getForwardRay(this._rayLength); var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate); if (hit) { // Populate the contrllers mesh that can be used for drag/drop if (gazer._laserPointer) { hit.originMesh = gazer._laserPointer.parent; } this._scene.simulatePointerMove(hit, { pointerId: gazer._id }); } gazer._currentHit = hit; // Moving the gazeTracker on the mesh face targetted if (hit && hit.pickedPoint) { if (this._displayGaze) { var multiplier = 1; gazer._gazeTracker.isVisible = true; if (gazer._isActionableMesh) { multiplier = 3; } if (this.updateGazeTrackerScale) { gazer._gazeTracker.scaling.x = hit.distance * multiplier; gazer._gazeTracker.scaling.y = hit.distance * multiplier; gazer._gazeTracker.scaling.z = hit.distance * multiplier; } var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray); // To avoid z-fighting var deltaFighting = 0.002; if (pickNormal) { var axis1 = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Cross(_Maths_math__WEBPACK_IMPORTED_MODULE_9__["Axis"].Y, pickNormal); var axis2 = _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Cross(pickNormal, axis1); _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Vector3"].RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation); } gazer._gazeTracker.position.copyFrom(hit.pickedPoint); if (gazer._gazeTracker.position.x < 0) { gazer._gazeTracker.position.x += deltaFighting; } else { gazer._gazeTracker.position.x -= deltaFighting; } if (gazer._gazeTracker.position.y < 0) { gazer._gazeTracker.position.y += deltaFighting; } else { gazer._gazeTracker.position.y -= deltaFighting; } if (gazer._gazeTracker.position.z < 0) { gazer._gazeTracker.position.z += deltaFighting; } else { gazer._gazeTracker.position.z -= deltaFighting; } } // Changing the size of the laser pointer based on the distance from the targetted point gazer._updatePointerDistance(hit.distance); } else { gazer._updatePointerDistance(); gazer._gazeTracker.isVisible = false; } if (hit && hit.pickedMesh) { // The object selected is the floor, we're in a teleportation scenario if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) { // Moving the teleportation area to this targetted point //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) { this._notifySelectedMeshUnselected(gazer._currentMeshSelected); } gazer._currentMeshSelected = null; if (gazer._teleportationRequestInitiated) { this._moveTeleportationSelectorTo(hit, gazer, ray); } return; } // If not, we're in a selection scenario //this._teleportationAllowed = false; if (hit.pickedMesh !== gazer._currentMeshSelected) { if (this.meshSelectionPredicate(hit.pickedMesh)) { this.onNewMeshPicked.notifyObservers(hit); gazer._currentMeshSelected = hit.pickedMesh; if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) { this.changeGazeColor(new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Color3"](0, 0, 1)); this.changeLaserColor(new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Color3"](0.2, 0.2, 1)); gazer._isActionableMesh = true; } else { this.changeGazeColor(new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Color3"](0.7, 0.7, 0.7)); this.changeLaserColor(new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Color3"](0.7, 0.7, 0.7)); gazer._isActionableMesh = false; } try { this.onNewMeshSelected.notifyObservers(hit.pickedMesh); } catch (err) { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Error in your custom logic onNewMeshSelected: " + err); } } else { this._notifySelectedMeshUnselected(gazer._currentMeshSelected); gazer._currentMeshSelected = null; this.changeGazeColor(new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Color3"](0.7, 0.7, 0.7)); this.changeLaserColor(new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Color3"](0.7, 0.7, 0.7)); } } } else { this._notifySelectedMeshUnselected(gazer._currentMeshSelected); gazer._currentMeshSelected = null; //this._teleportationAllowed = false; this.changeGazeColor(new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Color3"](0.7, 0.7, 0.7)); this.changeLaserColor(new _Maths_math__WEBPACK_IMPORTED_MODULE_9__["Color3"](0.7, 0.7, 0.7)); } }; VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) { if (mesh) { this.onSelectedMeshUnselected.notifyObservers(mesh); } }; /** * Sets the color of the laser ray from the vr controllers. * @param color new color for the ray. */ VRExperienceHelper.prototype.changeLaserColor = function (color) { if (this._leftController) { this._leftController._setLaserPointerColor(color); } if (this._rightController) { this._rightController._setLaserPointerColor(color); } }; /** * Sets the color of the ray from the vr headsets gaze. * @param color new color for the ray. */ VRExperienceHelper.prototype.changeGazeColor = function (color) { if (!this.updateGazeTrackerColor) { return; } if (!this._cameraGazer._gazeTracker.material) { return; } this._cameraGazer._gazeTracker.material.emissiveColor = color; if (this._leftController) { this._leftController._gazeTracker.material.emissiveColor = color; } if (this._rightController) { this._rightController._gazeTracker.material.emissiveColor = color; } }; /** * Exits VR and disposes of the vr experience helper */ VRExperienceHelper.prototype.dispose = function () { if (this.isInVRMode) { this.exitVR(); } if (this._postProcessMove) { this._postProcessMove.dispose(); } if (this._webVRCamera) { this._webVRCamera.dispose(); } if (this._vrDeviceOrientationCamera) { this._vrDeviceOrientationCamera.dispose(); } if (!this._useCustomVRButton && this._btnVR.parentNode) { document.body.removeChild(this._btnVR); } if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) { this._deviceOrientationCamera.dispose(); } if (this._cameraGazer) { this._cameraGazer.dispose(); } if (this._leftController) { this._leftController.dispose(); } if (this._rightController) { this._rightController.dispose(); } if (this._teleportationTarget) { this._teleportationTarget.dispose(); } this._floorMeshesCollection = []; document.removeEventListener("keydown", this._onKeyDown); window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange); window.removeEventListener("resize", this._onResize); document.removeEventListener("fullscreenchange", this._onFullscreenChange); document.removeEventListener("mozfullscreenchange", this._onFullscreenChange); document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange); document.removeEventListener("msfullscreenchange", this._onFullscreenChange); document.onmsfullscreenchange = null; this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged); this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart); this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete); window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange); this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected); this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected); this._scene.unregisterBeforeRender(this.beforeRender); }; /** * Gets the name of the VRExperienceHelper class * @returns "VRExperienceHelper" */ VRExperienceHelper.prototype.getClassName = function () { return "VRExperienceHelper"; }; return VRExperienceHelper; }()); /***/ }), /***/ "./Cameras/VR/webVRCamera.ts": /*!***********************************!*\ !*** ./Cameras/VR/webVRCamera.ts ***! \***********************************/ /*! exports provided: WebVRFreeCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebVRFreeCamera", function() { return WebVRFreeCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/freeCamera */ "./Cameras/freeCamera.ts"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Gamepads/gamepad */ "./Gamepads/gamepad.ts"); /* harmony import */ var _Gamepads_Controllers_poseEnabledController__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Gamepads/Controllers/poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../node */ "./node.ts"); /* harmony import */ var _Lights_hemisphericLight__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../Lights/hemisphericLight */ "./Lights/hemisphericLight.ts"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _PostProcesses_vrMultiviewToSingleviewPostProcess__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../PostProcesses/vrMultiviewToSingleviewPostProcess */ "./PostProcesses/vrMultiviewToSingleviewPostProcess.ts"); /* harmony import */ var _RigModes_webVRRigMode__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../RigModes/webVRRigMode */ "./Cameras/RigModes/webVRRigMode.ts"); // Side effect import to define the stereoscopic mode. _node__WEBPACK_IMPORTED_MODULE_7__["Node"].AddNodeConstructor("WebVRFreeCamera", function (name, scene) { return function () { return new WebVRFreeCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(), scene); }; }); _node__WEBPACK_IMPORTED_MODULE_7__["Node"].AddNodeConstructor("WebVRGamepadCamera", function (name, scene) { return function () { return new WebVRFreeCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(), scene); }; }); /** * This represents a WebVR camera. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift. * @example http://doc.babylonjs.com/how_to/webvr_camera */ var WebVRFreeCamera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](WebVRFreeCamera, _super); /** * Instantiates a WebVRFreeCamera. * @param name The name of the WebVRFreeCamera * @param position The starting anchor position for the camera * @param scene The scene the camera belongs to * @param webVROptions a set of customizable options for the webVRCamera */ function WebVRFreeCamera(name, position, scene, webVROptions) { if (webVROptions === void 0) { webVROptions = {}; } var _this = _super.call(this, name, position, scene) || this; _this.webVROptions = webVROptions; /** * @hidden * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay */ _this._vrDevice = null; /** * The rawPose of the vrDevice. */ _this.rawPose = null; _this._specsVersion = "1.1"; _this._attached = false; _this._descendants = []; // Represents device position and rotation in room space. Should only be used to help calculate babylon space values _this._deviceRoomPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(); /** @hidden */ _this._deviceRoomRotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].Identity(); _this._standingMatrix = null; /** * Represents device position in babylon space. */ _this.devicePosition = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(); /** * Represents device rotation in babylon space. */ _this.deviceRotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].Identity(); /** * The scale of the device to be used when translating from device space to babylon space. */ _this.deviceScaleFactor = 1; _this._deviceToWorld = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].Identity(); _this._worldToDevice = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].Identity(); /** * References to the webVR controllers for the vrDevice. */ _this.controllers = []; /** * Emits an event when a controller is attached. */ _this.onControllersAttachedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Emits an event when a controller's mesh has been loaded; */ _this.onControllerMeshLoadedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Emits an event when the HMD's pose has been updated. */ _this.onPoseUpdatedFromDeviceObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); _this._poseSet = false; /** * If the rig cameras be used as parent instead of this camera. */ _this.rigParenting = true; _this._defaultHeight = undefined; _this._htmlElementAttached = null; _this._detachIfAttached = function () { var vrDisplay = _this.getEngine().getVRDevice(); if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) { _this.detachControl(_this._htmlElementAttached); } }; _this._workingVector = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(); _this._oneVector = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].One(); _this._workingMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].Identity(); _this._tmpMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"](); _this._cache.position = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(); if (webVROptions.defaultHeight) { _this._defaultHeight = webVROptions.defaultHeight; _this.position.y = _this._defaultHeight; } _this.minZ = 0.1; //legacy support - the compensation boolean was removed. if (arguments.length === 5) { _this.webVROptions = arguments[4]; } // default webVR options if (_this.webVROptions.trackPosition == undefined) { _this.webVROptions.trackPosition = true; } if (_this.webVROptions.controllerMeshes == undefined) { _this.webVROptions.controllerMeshes = true; } if (_this.webVROptions.defaultLightingOnControllers == undefined) { _this.webVROptions.defaultLightingOnControllers = true; } _this.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"](); if (_this.webVROptions && _this.webVROptions.positionScale) { _this.deviceScaleFactor = _this.webVROptions.positionScale; } //enable VR var engine = _this.getEngine(); _this._onVREnabled = function (success) { if (success) { _this.initControllers(); } }; engine.onVRRequestPresentComplete.add(_this._onVREnabled); engine.initWebVR().add(function (event) { if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) { return; } _this._vrDevice = event.vrDisplay; //reset the rig parameters. _this.setCameraRigMode(_Cameras_camera__WEBPACK_IMPORTED_MODULE_3__["Camera"].RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion }); if (_this._attached) { _this.getEngine().enableVR(); } }); if (typeof (VRFrameData) !== "undefined") { _this._frameData = new VRFrameData(); } if (webVROptions.useMultiview) { if (!_this.getScene().getEngine().getCaps().multiview) { _Misc_logger__WEBPACK_IMPORTED_MODULE_9__["Logger"].Warn("Multiview is not supported, falling back to standard rendering"); _this._useMultiviewToSingleView = false; } else { _this._useMultiviewToSingleView = true; _this._rigPostProcess = new _PostProcesses_vrMultiviewToSingleviewPostProcess__WEBPACK_IMPORTED_MODULE_10__["VRMultiviewToSingleviewPostProcess"]("VRMultiviewToSingleview", _this, 1.0); } } /** * The idea behind the following lines: * objects that have the camera as parent should actually have the rig cameras as a parent. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera, * the second will not show it correctly. * * To solve this - each object that has the camera as parent will be added to a protected array. * When the rig camera renders, it will take this array and set all of those to be its children. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly. * Amazing! */ scene.onBeforeCameraRenderObservable.add(function (camera) { if (camera.parent === _this && _this.rigParenting) { _this._descendants = _this.getDescendants(true, function (n) { // don't take the cameras or the controllers! var isController = _this.controllers.some(function (controller) { return controller._mesh === n; }); var isRigCamera = _this._rigCameras.indexOf(n) !== -1; return !isController && !isRigCamera; }); _this._descendants.forEach(function (node) { node.parent = camera; }); } }); scene.onAfterCameraRenderObservable.add(function (camera) { if (camera.parent === _this && _this.rigParenting) { _this._descendants.forEach(function (node) { node.parent = _this; }); } }); return _this; } /** * Gets the device distance from the ground in meters. * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned. */ WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () { if (this._standingMatrix) { // Add standing matrix offset to get real offset from ground in room this._standingMatrix.getTranslationToRef(this._workingVector); return this._deviceRoomPosition.y + this._workingVector.y; } //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero. return this._defaultHeight || 0; }; /** * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported. */ WebVRFreeCamera.prototype.useStandingMatrix = function (callback) { var _this = this; if (callback === void 0) { callback = function (bool) { }; } // Use standing matrix if available this.getEngine().initWebVRAsync().then(function (result) { if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) { callback(false); } else { _this._standingMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"](); _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix); if (!_this.getScene().useRightHandedSystem) { if (_this._standingMatrix) { _this._standingMatrix.toggleModelMatrixHandInPlace(); } } callback(true); } }); }; /** * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground. * @returns A promise with a boolean set to if the standing matrix is supported. */ WebVRFreeCamera.prototype.useStandingMatrixAsync = function () { var _this = this; return new Promise(function (res) { _this.useStandingMatrix(function (supported) { res(supported); }); }); }; /** * Disposes the camera */ WebVRFreeCamera.prototype.dispose = function () { this._detachIfAttached(); this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled); if (this._updateCacheWhenTrackingDisabledObserver) { this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver); } _super.prototype.dispose.call(this); }; /** * Gets a vrController by name. * @param name The name of the controller to retreive * @returns the controller matching the name specified or null if not found */ WebVRFreeCamera.prototype.getControllerByName = function (name) { for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) { var gp = _a[_i]; if (gp.hand === name) { return gp; } } return null; }; Object.defineProperty(WebVRFreeCamera.prototype, "leftController", { /** * The controller corrisponding to the users left hand. */ get: function () { if (!this._leftController) { this._leftController = this.getControllerByName("left"); } return this._leftController; }, enumerable: true, configurable: true }); Object.defineProperty(WebVRFreeCamera.prototype, "rightController", { /** * The controller corrisponding to the users right hand. */ get: function () { if (!this._rightController) { this._rightController = this.getControllerByName("right"); } return this._rightController; }, enumerable: true, configurable: true }); /** * Casts a ray forward from the vrCamera's gaze. * @param length Length of the ray (default: 100) * @returns the ray corrisponding to the gaze */ WebVRFreeCamera.prototype.getForwardRay = function (length) { if (length === void 0) { length = 100; } if (this.leftCamera) { // Use left eye to avoid computation to compute center on every call return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera } else { return _super.prototype.getForwardRay.call(this, length); } }; /** * @hidden * Updates the camera based on device's frame data */ WebVRFreeCamera.prototype._checkInputs = function () { if (this._vrDevice && this._vrDevice.isPresenting) { this._vrDevice.getFrameData(this._frameData); this.updateFromDevice(this._frameData.pose); } _super.prototype._checkInputs.call(this); }; /** * Updates the poseControlled values based on the input device pose. * @param poseData Pose coming from the device */ WebVRFreeCamera.prototype.updateFromDevice = function (poseData) { if (poseData && poseData.orientation) { this.rawPose = poseData; this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]); if (this.getScene().useRightHandedSystem) { this._deviceRoomRotationQuaternion.z *= -1; this._deviceRoomRotationQuaternion.w *= -1; } if (this.webVROptions.trackPosition && this.rawPose.position) { this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]); if (this.getScene().useRightHandedSystem) { this._deviceRoomPosition.z *= -1; } } this._poseSet = true; } }; /** * WebVR's attach control will start broadcasting frames to the device. * Note that in certain browsers (chrome for example) this function must be called * within a user-interaction callback. Example: *
 scene.onPointerDown = function() { camera.attachControl(canvas); }
* * @param element html element to attach the vrDevice to * @param noPreventDefault prevent the default html element operation when attaching the vrDevice */ WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) { _super.prototype.attachControl.call(this, element, noPreventDefault); this._attached = true; this._htmlElementAttached = element; noPreventDefault = _Cameras_camera__WEBPACK_IMPORTED_MODULE_3__["Camera"].ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault; if (this._vrDevice) { this.getEngine().enableVR(); } window.addEventListener('vrdisplaypresentchange', this._detachIfAttached); }; /** * Detaches the camera from the html element and disables VR * * @param element html element to detach from */ WebVRFreeCamera.prototype.detachControl = function (element) { this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver); this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver); _super.prototype.detachControl.call(this, element); this._attached = false; this.getEngine().disableVR(); window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached); }; /** * @returns the name of this class */ WebVRFreeCamera.prototype.getClassName = function () { return "WebVRFreeCamera"; }; /** * Calls resetPose on the vrDisplay * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose */ WebVRFreeCamera.prototype.resetToCurrentRotation = function () { //uses the vrDisplay's "resetPose()". //pitch and roll won't be affected. this._vrDevice.resetPose(); }; /** * @hidden * Updates the rig cameras (left and right eye) */ WebVRFreeCamera.prototype._updateRigCameras = function () { var camLeft = this._rigCameras[0]; var camRight = this._rigCameras[1]; camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion); camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion); camLeft.position.copyFrom(this._deviceRoomPosition); camRight.position.copyFrom(this._deviceRoomPosition); }; // Remove translation from 6dof headset if trackposition is set to false WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) { if (isViewMatrix === void 0) { isViewMatrix = false; } if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) { _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix); if (!isViewMatrix) { this._tmpMatrix.invert(); } this._tmpMatrix.multiplyToRef(matrix, matrix); } }; /** * @hidden * Updates the cached values of the camera * @param ignoreParentClass ignores updating the parent class's cache (default: false) */ WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) { var _this = this; if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) { // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition if (!this.updateCacheCalled) { // make sure it is only called once per loop. this.update() might cause an infinite loop. this.updateCacheCalled = true; this.update(); } // Set working vector to the device position in room space rotated by the new rotation this.rotationQuaternion.toRotationMatrix(this._workingMatrix); _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector); // Subtract this vector from the current device position in world to get the translation for the device world matrix this.devicePosition.subtractToRef(this._workingVector, this._workingVector); _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld); // Add translation from anchor position this._deviceToWorld.getTranslationToRef(this._workingVector); this._workingVector.addInPlace(this.position); this._workingVector.subtractInPlace(this._cache.position); this._deviceToWorld.setTranslation(this._workingVector); // Set an inverted matrix to be used when updating the camera this._deviceToWorld.invertToRef(this._worldToDevice); // Update the gamepad to ensure the mesh is updated on the same frame as camera this.controllers.forEach(function (controller) { controller._deviceToWorld.copyFrom(_this._deviceToWorld); _this._correctPositionIfNotTrackPosition(controller._deviceToWorld); controller.update(); }); } if (!ignoreParentClass) { _super.prototype._updateCache.call(this); } this.updateCacheCalled = false; }; /** * @hidden * Get current device position in babylon world */ WebVRFreeCamera.prototype._computeDevicePosition = function () { _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition); }; /** * Updates the current device position and rotation in the babylon world */ WebVRFreeCamera.prototype.update = function () { this._computeDevicePosition(); // Get current device rotation in babylon world _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix); this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix); _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion); if (this._poseSet) { this.onPoseUpdatedFromDeviceObservable.notifyObservers(null); } _super.prototype.update.call(this); }; /** * @hidden * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix) * @returns an identity matrix */ WebVRFreeCamera.prototype._getViewMatrix = function () { return _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].Identity(); }; /** * This function is called by the two RIG cameras. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance) * @hidden */ WebVRFreeCamera.prototype._getWebVRViewMatrix = function () { // Update the parent camera prior to using a child camera to avoid desynchronization var parentCamera = this._cameraRigParams["parentCamera"]; parentCamera._updateCache(); //WebVR 1.1 var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix; _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].FromArrayToRef(viewArray, 0, this._webvrViewMatrix); if (!this.getScene().useRightHandedSystem) { this._webvrViewMatrix.toggleModelMatrixHandInPlace(); } // update the camera rotation matrix this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix); _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint); // Computing target and final matrix this.position.addToRef(this._transformedReferencePoint, this._currentTarget); // should the view matrix be updated with scale and position offset? if (parentCamera.deviceScaleFactor !== 1) { this._webvrViewMatrix.invert(); // scale the position, if set if (parentCamera.deviceScaleFactor) { this._webvrViewMatrix.multiplyAtIndex(12, parentCamera.deviceScaleFactor); this._webvrViewMatrix.multiplyAtIndex(13, parentCamera.deviceScaleFactor); this._webvrViewMatrix.multiplyAtIndex(14, parentCamera.deviceScaleFactor); } this._webvrViewMatrix.invert(); } // Remove translation from 6dof headset if trackposition is set to false parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true); parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix); // Compute global position this._workingMatrix = this._workingMatrix || _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].Identity(); this._webvrViewMatrix.invertToRef(this._workingMatrix); this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix); this._workingMatrix.getTranslationToRef(this._globalPosition); this._markSyncedWithParent(); return this._webvrViewMatrix; }; /** @hidden */ WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () { var parentCamera = this.parent; parentCamera._vrDevice.depthNear = parentCamera.minZ; parentCamera._vrDevice.depthFar = parentCamera.maxZ; var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix; _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].FromArrayToRef(projectionArray, 0, this._projectionMatrix); //babylon compatible matrix if (!this.getScene().useRightHandedSystem) { this._projectionMatrix.toggleProjectionMatrixHandInPlace(); } return this._projectionMatrix; }; /** * Initializes the controllers and their meshes */ WebVRFreeCamera.prototype.initControllers = function () { var _this = this; this.controllers = []; var manager = this.getScene().gamepadManager; this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) { if (gamepad.type === _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_5__["Gamepad"].POSE_ENABLED) { var webVrController = gamepad; if (webVrController.defaultModel) { webVrController.defaultModel.setEnabled(false); } if (webVrController.hand === "right") { _this._rightController = null; } if (webVrController.hand === "left") { _this._leftController = null; } var controllerIndex = _this.controllers.indexOf(webVrController); if (controllerIndex !== -1) { _this.controllers.splice(controllerIndex, 1); } } }); this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) { if (gamepad.type === _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_5__["Gamepad"].POSE_ENABLED) { var webVrController_1 = gamepad; if (!_this.webVROptions.trackPosition) { webVrController_1._disableTrackPosition(new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"](webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25)); // Cache must be updated before rendering controllers to avoid them being one frame behind if (!_this._updateCacheWhenTrackingDisabledObserver) { _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () { _this._updateCache(); }); } } webVrController_1.deviceScaleFactor = _this.deviceScaleFactor; webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld); _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld); if (_this.webVROptions.controllerMeshes) { if (webVrController_1.defaultModel) { webVrController_1.defaultModel.setEnabled(true); } else { // Load the meshes webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) { loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor); _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1); if (_this.webVROptions.defaultLightingOnControllers) { if (!_this._lightOnControllers) { _this._lightOnControllers = new _Lights_hemisphericLight__WEBPACK_IMPORTED_MODULE_8__["HemisphericLight"]("vrControllersLight", new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"](0, 1, 0), _this.getScene()); } var activateLightOnSubMeshes_1 = function (mesh, light) { var children = mesh.getChildren(); if (children && children.length !== 0) { children.forEach(function (mesh) { light.includedOnlyMeshes.push(mesh); activateLightOnSubMeshes_1(mesh, light); }); } }; _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh); activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers); } }); } } webVrController_1.attachToPoseControlledCamera(_this); // since this is async - sanity check. Is the controller already stored? if (_this.controllers.indexOf(webVrController_1) === -1) { //add to the controllers array _this.controllers.push(webVrController_1); // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them... // So we're overriding setting left & right manually to be sure var firstViveWandDetected = false; for (var i = 0; i < _this.controllers.length; i++) { if (_this.controllers[i].controllerType === _Gamepads_Controllers_poseEnabledController__WEBPACK_IMPORTED_MODULE_6__["PoseEnabledControllerType"].VIVE) { if (!firstViveWandDetected) { firstViveWandDetected = true; _this.controllers[i].hand = "left"; } else { _this.controllers[i].hand = "right"; } } } //did we find enough controllers? Great! let the developer know. if (_this.controllers.length >= 2) { _this.onControllersAttachedObservable.notifyObservers(_this.controllers); } } } }); }; return WebVRFreeCamera; }(_Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_2__["FreeCamera"])); /***/ }), /***/ "./Cameras/XR/index.ts": /*!*****************************!*\ !*** ./Cameras/XR/index.ts ***! \*****************************/ /*! exports provided: WebXRCamera, WebXREnterExitUIButton, WebXREnterExitUIOptions, WebXREnterExitUI, WebXRState, WebXRExperienceHelper, WebXRController, WebXRInput, WebXRManagedOutputCanvas, WebXRSessionManager */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _webXRCamera__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./webXRCamera */ "./Cameras/XR/webXRCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRCamera", function() { return _webXRCamera__WEBPACK_IMPORTED_MODULE_0__["WebXRCamera"]; }); /* harmony import */ var _webXREnterExitUI__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./webXREnterExitUI */ "./Cameras/XR/webXREnterExitUI.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUIButton", function() { return _webXREnterExitUI__WEBPACK_IMPORTED_MODULE_1__["WebXREnterExitUIButton"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUIOptions", function() { return _webXREnterExitUI__WEBPACK_IMPORTED_MODULE_1__["WebXREnterExitUIOptions"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUI", function() { return _webXREnterExitUI__WEBPACK_IMPORTED_MODULE_1__["WebXREnterExitUI"]; }); /* harmony import */ var _webXRExperienceHelper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./webXRExperienceHelper */ "./Cameras/XR/webXRExperienceHelper.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRState", function() { return _webXRExperienceHelper__WEBPACK_IMPORTED_MODULE_2__["WebXRState"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRExperienceHelper", function() { return _webXRExperienceHelper__WEBPACK_IMPORTED_MODULE_2__["WebXRExperienceHelper"]; }); /* harmony import */ var _webXRInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./webXRInput */ "./Cameras/XR/webXRInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRController", function() { return _webXRInput__WEBPACK_IMPORTED_MODULE_3__["WebXRController"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRInput", function() { return _webXRInput__WEBPACK_IMPORTED_MODULE_3__["WebXRInput"]; }); /* harmony import */ var _webXRManagedOutputCanvas__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./webXRManagedOutputCanvas */ "./Cameras/XR/webXRManagedOutputCanvas.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRManagedOutputCanvas", function() { return _webXRManagedOutputCanvas__WEBPACK_IMPORTED_MODULE_4__["WebXRManagedOutputCanvas"]; }); /* harmony import */ var _webXRSessionManager__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./webXRSessionManager */ "./Cameras/XR/webXRSessionManager.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRSessionManager", function() { return _webXRSessionManager__WEBPACK_IMPORTED_MODULE_5__["WebXRSessionManager"]; }); /***/ }), /***/ "./Cameras/XR/webXRCamera.ts": /*!***********************************!*\ !*** ./Cameras/XR/webXRCamera.ts ***! \***********************************/ /*! exports provided: WebXRCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebXRCamera", function() { return WebXRCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Cameras/freeCamera */ "./Cameras/freeCamera.ts"); /* harmony import */ var _Cameras_targetCamera__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Cameras/targetCamera */ "./Cameras/targetCamera.ts"); /** * WebXR Camera which holds the views for the xrSession * @see https://doc.babylonjs.com/how_to/webxr */ var WebXRCamera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](WebXRCamera, _super); /** * Creates a new webXRCamera, this should only be set at the camera after it has been updated by the xrSessionManager * @param name the name of the camera * @param scene the scene to add the camera to */ function WebXRCamera(name, scene) { var _this = _super.call(this, name, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(), scene) || this; // Initial camera configuration _this.minZ = 0; _this.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"](); _this.cameraRigMode = _Cameras_camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_CUSTOM; _this.updateUpVectorFromRotation = true; _this._updateNumberOfRigCameras(1); return _this; } WebXRCamera.prototype._updateNumberOfRigCameras = function (viewCount) { if (viewCount === void 0) { viewCount = 1; } while (this.rigCameras.length < viewCount) { var newCamera = new _Cameras_targetCamera__WEBPACK_IMPORTED_MODULE_4__["TargetCamera"]("view: " + this.rigCameras.length, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(), this.getScene()); newCamera.minZ = 0; newCamera.parent = this; newCamera.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"](); newCamera.updateUpVectorFromRotation = true; this.rigCameras.push(newCamera); } while (this.rigCameras.length > viewCount) { var removedCamera = this.rigCameras.pop(); if (removedCamera) { removedCamera.dispose(); } } }; /** @hidden */ WebXRCamera.prototype._updateForDualEyeDebugging = function (pupilDistance) { if (pupilDistance === void 0) { pupilDistance = 0.01; } // Create initial camera rigs this._updateNumberOfRigCameras(2); this.rigCameras[0].viewport = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Viewport"](0, 0, 0.5, 1.0); this.rigCameras[0].position.x = -pupilDistance / 2; this.rigCameras[0].outputRenderTarget = null; this.rigCameras[1].viewport = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Viewport"](0.5, 0, 0.5, 1.0); this.rigCameras[1].position.x = pupilDistance / 2; this.rigCameras[1].outputRenderTarget = null; }; /** * Updates the cameras position from the current pose information of the XR session * @param xrSessionManager the session containing pose information * @returns true if the camera has been updated, false if the session did not contain pose or frame data */ WebXRCamera.prototype.updateFromXRSessionManager = function (xrSessionManager) { var _this = this; // Ensure all frame data is available if (!xrSessionManager._currentXRFrame || !xrSessionManager._currentXRFrame.getDevicePose) { return false; } var pose = xrSessionManager._currentXRFrame.getDevicePose(xrSessionManager._frameOfReference); if (!pose || !pose.poseModelMatrix) { return false; } // Update the parent cameras matrix _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].FromFloat32ArrayToRefScaled(pose.poseModelMatrix, 0, 1, WebXRCamera._TmpMatrix); if (!this._scene.useRightHandedSystem) { WebXRCamera._TmpMatrix.toggleModelMatrixHandInPlace(); } WebXRCamera._TmpMatrix.getTranslationToRef(this.position); WebXRCamera._TmpMatrix.getRotationMatrixToRef(WebXRCamera._TmpMatrix); _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].FromRotationMatrixToRef(WebXRCamera._TmpMatrix, this.rotationQuaternion); this.computeWorldMatrix(); // Update camera rigs this._updateNumberOfRigCameras(xrSessionManager._currentXRFrame.views.length); xrSessionManager._currentXRFrame.views.forEach(function (view, i) { // Update view/projection matrix _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].FromFloat32ArrayToRefScaled(pose.getViewMatrix(view), 0, 1, _this.rigCameras[i]._computedViewMatrix); _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].FromFloat32ArrayToRefScaled(view.projectionMatrix, 0, 1, _this.rigCameras[i]._projectionMatrix); if (!_this._scene.useRightHandedSystem) { _this.rigCameras[i]._computedViewMatrix.toggleModelMatrixHandInPlace(); _this.rigCameras[i]._projectionMatrix.toggleProjectionMatrixHandInPlace(); } // Update viewport var viewport = xrSessionManager._xrSession.baseLayer.getViewport(view); var width = xrSessionManager._xrSession.baseLayer.framebufferWidth; var height = xrSessionManager._xrSession.baseLayer.framebufferHeight; _this.rigCameras[i].viewport.width = viewport.width / width; _this.rigCameras[i].viewport.height = viewport.height / height; _this.rigCameras[i].viewport.x = viewport.x / width; _this.rigCameras[i].viewport.y = viewport.y / height; // Set cameras to render to the session's render target _this.rigCameras[i].outputRenderTarget = xrSessionManager._sessionRenderTargetTexture; }); return true; }; WebXRCamera._TmpMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); return WebXRCamera; }(_Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_3__["FreeCamera"])); /***/ }), /***/ "./Cameras/XR/webXREnterExitUI.ts": /*!****************************************!*\ !*** ./Cameras/XR/webXREnterExitUI.ts ***! \****************************************/ /*! exports provided: WebXREnterExitUIButton, WebXREnterExitUIOptions, WebXREnterExitUI */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUIButton", function() { return WebXREnterExitUIButton; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUIOptions", function() { return WebXREnterExitUIOptions; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUI", function() { return WebXREnterExitUI; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _webXRExperienceHelper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./webXRExperienceHelper */ "./Cameras/XR/webXRExperienceHelper.ts"); /** * Button which can be used to enter a different mode of XR */ var WebXREnterExitUIButton = /** @class */ (function () { /** * Creates a WebXREnterExitUIButton * @param element button element * @param initializationOptions XR initialization options for the button */ function WebXREnterExitUIButton( /** button element */ element, /** XR initialization options for the button */ initializationOptions) { this.element = element; this.initializationOptions = initializationOptions; } /** * Overwritable function which can be used to update the button's visuals when the state changes * @param activeButton the current active button in the UI */ WebXREnterExitUIButton.prototype.update = function (activeButton) { }; return WebXREnterExitUIButton; }()); /** * Options to create the webXR UI */ var WebXREnterExitUIOptions = /** @class */ (function () { function WebXREnterExitUIOptions() { } return WebXREnterExitUIOptions; }()); /** * UI to allow the user to enter/exit XR mode */ var WebXREnterExitUI = /** @class */ (function () { function WebXREnterExitUI(scene, options) { var _this = this; this.scene = scene; this._buttons = []; this._activeButton = null; /** * Fired every time the active button is changed. * * When xr is entered via a button that launches xr that button will be the callback parameter * * When exiting xr the callback parameter will be null) */ this.activeButtonChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); this._overlay = document.createElement("div"); this._overlay.style.cssText = "z-index:11;position: absolute; right: 20px;bottom: 50px;"; if (options.customButtons) { this._buttons = options.customButtons; } else { var hmdBtn = document.createElement("button"); hmdBtn.style.cssText = "color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-repeat:no-repeat; background-position: center; outline: none;"; hmdBtn.innerText = "HMD"; this._buttons.push(new WebXREnterExitUIButton(hmdBtn, { immersive: true, outputContext: options.outputCanvasContext })); this._buttons[this._buttons.length - 1].update = function (activeButton) { this.element.style.display = (activeButton === null || activeButton === this) ? "" : "none"; this.element.innerText = activeButton === this ? "EXIT" : "HMD"; }; var windowBtn = document.createElement("button"); windowBtn.style.cssText = hmdBtn.style.cssText; windowBtn.innerText = "Window"; this._buttons.push(new WebXREnterExitUIButton(windowBtn, { immersive: false, environmentIntegration: true, outputContext: options.outputCanvasContext })); this._buttons[this._buttons.length - 1].update = function (activeButton) { this.element.style.display = (activeButton === null || activeButton === this) ? "" : "none"; this.element.innerText = activeButton === this ? "EXIT" : "Window"; }; this._updateButtons(null); } var renderCanvas = scene.getEngine().getRenderingCanvas(); if (renderCanvas && renderCanvas.parentNode) { renderCanvas.parentNode.appendChild(this._overlay); scene.onDisposeObservable.addOnce(function () { _this.dispose(); }); } } /** * Creates UI to allow the user to enter/exit XR mode * @param scene the scene to add the ui to * @param helper the xr experience helper to enter/exit xr with * @param options options to configure the UI * @returns the created ui */ WebXREnterExitUI.CreateAsync = function (scene, helper, options) { var _this = this; var ui = new WebXREnterExitUI(scene, options); var supportedPromises = ui._buttons.map(function (btn) { return helper.supportsSessionAsync(btn.initializationOptions); }); helper.onStateChangedObservable.add(function (state) { if (state == _webXRExperienceHelper__WEBPACK_IMPORTED_MODULE_2__["WebXRState"].NOT_IN_XR) { ui._updateButtons(null); } }); return Promise.all(supportedPromises).then(function (results) { results.forEach(function (supported, i) { if (supported) { ui._overlay.appendChild(ui._buttons[i].element); ui._buttons[i].element.onclick = function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"](_this, void 0, void 0, function () { return tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"](this, function (_a) { switch (_a.label) { case 0: if (!(helper.state == _webXRExperienceHelper__WEBPACK_IMPORTED_MODULE_2__["WebXRState"].IN_XR)) return [3 /*break*/, 2]; ui._updateButtons(null); return [4 /*yield*/, helper.exitXRAsync()]; case 1: _a.sent(); return [2 /*return*/]; case 2: if (!(helper.state == _webXRExperienceHelper__WEBPACK_IMPORTED_MODULE_2__["WebXRState"].NOT_IN_XR)) return [3 /*break*/, 4]; ui._updateButtons(ui._buttons[i]); return [4 /*yield*/, helper.enterXRAsync(ui._buttons[i].initializationOptions, "eye-level")]; case 3: _a.sent(); _a.label = 4; case 4: return [2 /*return*/]; } }); }); }; } }); return ui; }); }; WebXREnterExitUI.prototype._updateButtons = function (activeButton) { var _this = this; this._activeButton = activeButton; this._buttons.forEach(function (b) { b.update(_this._activeButton); }); this.activeButtonChangedObservable.notifyObservers(this._activeButton); }; /** * Disposes of the object */ WebXREnterExitUI.prototype.dispose = function () { var renderCanvas = this.scene.getEngine().getRenderingCanvas(); if (renderCanvas && renderCanvas.parentNode && renderCanvas.parentNode.contains(this._overlay)) { renderCanvas.parentNode.removeChild(this._overlay); } this.activeButtonChangedObservable.clear(); }; return WebXREnterExitUI; }()); /***/ }), /***/ "./Cameras/XR/webXRExperienceHelper.ts": /*!*********************************************!*\ !*** ./Cameras/XR/webXRExperienceHelper.ts ***! \*********************************************/ /*! exports provided: WebXRState, WebXRExperienceHelper */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebXRState", function() { return WebXRState; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebXRExperienceHelper", function() { return WebXRExperienceHelper; }); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts"); /* harmony import */ var _webXRSessionManager__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./webXRSessionManager */ "./Cameras/XR/webXRSessionManager.ts"); /* harmony import */ var _webXRCamera__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./webXRCamera */ "./Cameras/XR/webXRCamera.ts"); /** * States of the webXR experience */ var WebXRState; (function (WebXRState) { /** * Transitioning to being in XR mode */ WebXRState[WebXRState["ENTERING_XR"] = 0] = "ENTERING_XR"; /** * Transitioning to non XR mode */ WebXRState[WebXRState["EXITING_XR"] = 1] = "EXITING_XR"; /** * In XR mode and presenting */ WebXRState[WebXRState["IN_XR"] = 2] = "IN_XR"; /** * Not entered XR mode */ WebXRState[WebXRState["NOT_IN_XR"] = 3] = "NOT_IN_XR"; })(WebXRState || (WebXRState = {})); /** * Helper class used to enable XR * @see https://doc.babylonjs.com/how_to/webxr */ var WebXRExperienceHelper = /** @class */ (function () { /** * Creates a WebXRExperienceHelper * @param scene The scene the helper should be created in */ function WebXRExperienceHelper(scene) { this.scene = scene; /** * The current state of the XR experience (eg. transitioning, in XR or not in XR) */ this.state = WebXRState.NOT_IN_XR; /** * Fires when the state of the experience helper has changed */ this.onStateChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); this._nonVRCamera = null; this._originalSceneAutoClear = true; this._supported = false; this.camera = new _webXRCamera__WEBPACK_IMPORTED_MODULE_4__["WebXRCamera"]("", scene); this._sessionManager = new _webXRSessionManager__WEBPACK_IMPORTED_MODULE_3__["WebXRSessionManager"](scene); this.container = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_2__["AbstractMesh"]("", scene); this.camera.parent = this.container; } WebXRExperienceHelper.prototype._setState = function (val) { this.state = val; this.onStateChangedObservable.notifyObservers(this.state); }; /** * Creates the experience helper * @param scene the scene to attach the experience helper to * @returns a promise for the experience helper */ WebXRExperienceHelper.CreateAsync = function (scene) { var helper = new WebXRExperienceHelper(scene); return helper._sessionManager.initializeAsync().then(function () { helper._supported = true; return helper; }).catch(function () { return helper; }); }; /** * Exits XR mode and returns the scene to its original state * @returns promise that resolves after xr mode has exited */ WebXRExperienceHelper.prototype.exitXRAsync = function () { this._setState(WebXRState.EXITING_XR); return this._sessionManager.exitXRAsync(); }; /** * Enters XR mode (This must be done within a user interaction in most browsers eg. button click) * @param sessionCreationOptions options for the XR session * @param frameOfReference frame of reference of the XR session * @returns promise that resolves after xr mode has entered */ WebXRExperienceHelper.prototype.enterXRAsync = function (sessionCreationOptions, frameOfReference) { var _this = this; if (!this._supported) { throw "XR session not supported by this browser"; } this._setState(WebXRState.ENTERING_XR); return this._sessionManager.enterXRAsync(sessionCreationOptions, frameOfReference).then(function () { // Cache pre xr scene settings _this._originalSceneAutoClear = _this.scene.autoClear; _this._nonVRCamera = _this.scene.activeCamera; // Overwrite current scene settings _this.scene.autoClear = false; _this.scene.activeCamera = _this.camera; _this._sessionManager.onXRFrameObservable.add(function () { _this.camera.updateFromXRSessionManager(_this._sessionManager); }); _this._sessionManager.onXRSessionEnded.addOnce(function () { // Reset camera rigs output render target to ensure sessions render target is not drawn after it ends _this.camera.rigCameras.forEach(function (c) { c.outputRenderTarget = null; }); // Restore scene settings _this.scene.autoClear = _this._originalSceneAutoClear; _this.scene.activeCamera = _this._nonVRCamera; _this._sessionManager.onXRFrameObservable.clear(); _this._setState(WebXRState.NOT_IN_XR); }); _this._setState(WebXRState.IN_XR); }); }; /** * Fires a ray and returns the closest hit in the xr sessions enviornment, useful to place objects in AR * @param ray ray to cast into the environment * @returns Promise which resolves with a collision point in the environment if it exists */ WebXRExperienceHelper.prototype.environmentPointHitTestAsync = function (ray) { return this._sessionManager.environmentPointHitTestAsync(ray); }; /** * Updates the global position of the camera by moving the camera's container * This should be used instead of modifying the camera's position as it will be overwritten by an xrSessions's update frame * @param position The desired global position of the camera */ WebXRExperienceHelper.prototype.setPositionOfCameraUsingContainer = function (position) { this.camera.globalPosition.subtractToRef(position, WebXRExperienceHelper._TmpVector); this.container.position.subtractInPlace(WebXRExperienceHelper._TmpVector); }; /** * Rotates the xr camera by rotating the camera's container around the camera's position * This should be used instead of modifying the camera's rotation as it will be overwritten by an xrSessions's update frame * @param rotation the desired quaternion rotation to apply to the camera */ WebXRExperienceHelper.prototype.rotateCameraByQuaternionUsingContainer = function (rotation) { if (!this.container.rotationQuaternion) { this.container.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].FromEulerVector(this.container.rotation); } this.container.rotationQuaternion.multiplyInPlace(rotation); this.container.position.rotateByQuaternionAroundPointToRef(rotation, this.camera.globalPosition, this.container.position); }; /** * Checks if the creation options are supported by the xr session * @param options creation options * @returns true if supported */ WebXRExperienceHelper.prototype.supportsSessionAsync = function (options) { if (!this._supported) { return Promise.resolve(false); } return this._sessionManager.supportsSessionAsync(options); }; /** * Disposes of the experience helper */ WebXRExperienceHelper.prototype.dispose = function () { this.camera.dispose(); this.container.dispose(); this.onStateChangedObservable.clear(); this._sessionManager.dispose(); }; WebXRExperienceHelper._TmpVector = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](); return WebXRExperienceHelper; }()); /***/ }), /***/ "./Cameras/XR/webXRInput.ts": /*!**********************************!*\ !*** ./Cameras/XR/webXRInput.ts ***! \**********************************/ /*! exports provided: WebXRController, WebXRInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebXRController", function() { return WebXRController; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebXRInput", function() { return WebXRInput; }); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts"); /** * Represents an XR input */ var WebXRController = /** @class */ (function () { /** * Creates the controller * @see https://doc.babylonjs.com/how_to/webxr * @param scene the scene which the controller should be associated to */ function WebXRController(scene) { this.pointer = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"]("controllerPointer", scene); } /** * Disposes of the object */ WebXRController.prototype.dispose = function () { if (this.grip) { this.grip.dispose(); } this.pointer.dispose(); }; return WebXRController; }()); /** * XR input used to track XR inputs such as controllers/rays */ var WebXRInput = /** @class */ (function () { /** * Initializes the WebXRInput * @param helper experience helper which the input should be created for */ function WebXRInput(helper) { var _this = this; this.helper = helper; /** * XR controllers being tracked */ this.controllers = []; this._tmpMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"](); this._frameObserver = helper._sessionManager.onXRFrameObservable.add(function () { if (!helper._sessionManager._currentXRFrame || !helper._sessionManager._currentXRFrame.getDevicePose) { return; } var xrFrame = helper._sessionManager._currentXRFrame; var inputSources = helper._sessionManager._xrSession.getInputSources(); inputSources.forEach(function (input, i) { var inputPose = xrFrame.getInputPose(input, helper._sessionManager._frameOfReference); if (inputPose) { if (_this.controllers.length <= i) { _this.controllers.push(new WebXRController(helper.container.getScene())); } var controller = _this.controllers[i]; // Manage the grip if it exists if (inputPose.gripMatrix) { if (!controller.grip) { controller.grip = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"]("controllerGrip", helper.container.getScene()); } _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].FromFloat32ArrayToRefScaled(inputPose.gripMatrix, 0, 1, _this._tmpMatrix); if (!controller.grip.getScene().useRightHandedSystem) { _this._tmpMatrix.toggleModelMatrixHandInPlace(); } if (!controller.grip.rotationQuaternion) { controller.grip.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"](); } _this._tmpMatrix.decompose(controller.grip.scaling, controller.grip.rotationQuaternion, controller.grip.position); } // Manager pointer of controller _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].FromFloat32ArrayToRefScaled(inputPose.targetRay.transformMatrix, 0, 1, _this._tmpMatrix); if (!controller.pointer.getScene().useRightHandedSystem) { _this._tmpMatrix.toggleModelMatrixHandInPlace(); } if (!controller.pointer.rotationQuaternion) { controller.pointer.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"](); } _this._tmpMatrix.decompose(controller.pointer.scaling, controller.pointer.rotationQuaternion, controller.pointer.position); } }); }); } /** * Disposes of the object */ WebXRInput.prototype.dispose = function () { this.controllers.forEach(function (c) { c.dispose(); }); this.helper._sessionManager.onXRFrameObservable.remove(this._frameObserver); }; return WebXRInput; }()); /***/ }), /***/ "./Cameras/XR/webXRManagedOutputCanvas.ts": /*!************************************************!*\ !*** ./Cameras/XR/webXRManagedOutputCanvas.ts ***! \************************************************/ /*! exports provided: WebXRManagedOutputCanvas */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebXRManagedOutputCanvas", function() { return WebXRManagedOutputCanvas; }); /* harmony import */ var _webXRExperienceHelper__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./webXRExperienceHelper */ "./Cameras/XR/webXRExperienceHelper.ts"); /** * Creates a canvas that is added/removed from the webpage when entering/exiting XR */ var WebXRManagedOutputCanvas = /** @class */ (function () { /** * Initializes the canvas to be added/removed upon entering/exiting xr * @param helper the xr experience helper used to trigger adding/removing of the canvas * @param canvas The canvas to be added/removed (If not specified a full screen canvas will be created) */ function WebXRManagedOutputCanvas(helper, canvas) { var _this = this; this._canvas = null; /** * xrpresent context of the canvas which can be used to display/mirror xr content */ this.canvasContext = null; if (!canvas) { canvas = document.createElement('canvas'); canvas.style.cssText = "position:absolute; bottom:0px;right:0px;z-index:10;width:100%;height:100%;background-color: #000000;"; } this._setManagedOutputCanvas(canvas); helper.onStateChangedObservable.add(function (stateInfo) { if (stateInfo == _webXRExperienceHelper__WEBPACK_IMPORTED_MODULE_0__["WebXRState"].ENTERING_XR) { // The canvas is added to the screen before entering XR because currently the xr session must be initialized while the canvas is added render properly _this._addCanvas(); } else if (helper.state == _webXRExperienceHelper__WEBPACK_IMPORTED_MODULE_0__["WebXRState"].NOT_IN_XR) { _this._removeCanvas(); } }); } /** * Disposes of the object */ WebXRManagedOutputCanvas.prototype.dispose = function () { this._removeCanvas(); this._setManagedOutputCanvas(null); }; WebXRManagedOutputCanvas.prototype._setManagedOutputCanvas = function (canvas) { this._removeCanvas(); if (!canvas) { this._canvas = null; this.canvasContext = null; } else { this._canvas = canvas; this.canvasContext = this._canvas.getContext('xrpresent'); } }; WebXRManagedOutputCanvas.prototype._addCanvas = function () { if (this._canvas) { document.body.appendChild(this._canvas); } }; WebXRManagedOutputCanvas.prototype._removeCanvas = function () { if (this._canvas && document.body.contains(this._canvas)) { document.body.removeChild(this._canvas); } }; return WebXRManagedOutputCanvas; }()); /***/ }), /***/ "./Cameras/XR/webXRSessionManager.ts": /*!*******************************************!*\ !*** ./Cameras/XR/webXRSessionManager.ts ***! \*******************************************/ /*! exports provided: WebXRSessionManager */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebXRSessionManager", function() { return WebXRSessionManager; }); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Materials/Textures/internalTexture */ "./Materials/Textures/internalTexture.ts"); /* harmony import */ var _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts"); /** * Manages an XRSession * @see https://doc.babylonjs.com/how_to/webxr */ var WebXRSessionManager = /** @class */ (function () { /** * Constructs a WebXRSessionManager, this must be initialized within a user action before usage * @param scene The scene which the session should be created for */ function WebXRSessionManager(scene) { this.scene = scene; /** * Fires every time a new xrFrame arrives which can be used to update the camera */ this.onXRFrameObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Fires when the xr session is ended either by the device or manually done */ this.onXRSessionEnded = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** @hidden */ this._sessionRenderTargetTexture = null; this._tmpMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"](); } /** * Initializes the manager * After initialization enterXR can be called to start an XR session * @returns Promise which resolves after it is initialized */ WebXRSessionManager.prototype.initializeAsync = function () { var _this = this; _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Warn("The WebXR APIs are still under development and are subject to change in the future."); // Check if the browser supports webXR this._xrNavigator = navigator; if (!this._xrNavigator.xr) { return Promise.reject("webXR not supported by this browser"); } // Request the webXR device return this._xrNavigator.xr.requestDevice().then(function (device) { _this._xrDevice = device; return _this.scene.getEngine()._gl.setCompatibleXRDevice(_this._xrDevice); }); }; /** * Enters XR with the desired XR session options, this must be done with a user action (eg. button click event) * @param sessionCreationOptions xr options to create the session with * @param frameOfReferenceType option to configure how the xr pose is expressed * @returns Promise which resolves after it enters XR */ WebXRSessionManager.prototype.enterXRAsync = function (sessionCreationOptions, frameOfReferenceType) { var _this = this; // initialize session return this._xrDevice.requestSession(sessionCreationOptions).then(function (session) { _this._xrSession = session; // handle when the session is ended (By calling session.end or device ends its own session eg. pressing home button on phone) _this._xrSession.addEventListener("end", function () { // Remove render target texture and notify frame obervers _this._sessionRenderTargetTexture = null; // Restore frame buffer to avoid clear on xr framebuffer after session end _this.scene.getEngine().restoreDefaultFramebuffer(); // Need to restart render loop as after the session is ended the last request for new frame will never call callback _this.scene.getEngine().customAnimationFrameRequester = null; _this.onXRSessionEnded.notifyObservers(null); _this.scene.getEngine()._renderLoop(); }, { once: true }); _this._xrSession.baseLayer = new XRWebGLLayer(_this._xrSession, _this.scene.getEngine()._gl); return _this._xrSession.requestFrameOfReference(frameOfReferenceType); }).then(function (frameOfRef) { _this._frameOfReference = frameOfRef; // Tell the engine's render loop to be driven by the xr session's refresh rate and provide xr pose information _this.scene.getEngine().customAnimationFrameRequester = { requestAnimationFrame: _this._xrSession.requestAnimationFrame.bind(_this._xrSession), renderFunction: function (timestamp, xrFrame) { // Store the XR frame in the manager to be consumed by the XR camera to update pose _this._currentXRFrame = xrFrame; _this.onXRFrameObservable.notifyObservers(null); _this.scene.getEngine()._renderLoop(); } }; // Create render target texture from xr's webgl render target _this._sessionRenderTargetTexture = WebXRSessionManager._CreateRenderTargetTextureFromSession(_this._xrSession, _this.scene); // Stop window's animation frame and trigger sessions animation frame window.cancelAnimationFrame(_this.scene.getEngine()._frameHandler); _this.scene.getEngine()._renderLoop(); }); }; /** * Stops the xrSession and restores the renderloop * @returns Promise which resolves after it exits XR */ WebXRSessionManager.prototype.exitXRAsync = function () { return this._xrSession.end(); }; /** * Fires a ray and returns the closest hit in the xr sessions enviornment, useful to place objects in AR * @param ray ray to cast into the environment * @returns Promise which resolves with a collision point in the environment if it exists */ WebXRSessionManager.prototype.environmentPointHitTestAsync = function (ray) { var _this = this; return new Promise(function (res) { // Compute left handed inputs to request hit test var origin = new Float32Array([ray.origin.x, ray.origin.y, ray.origin.z]); var direction = new Float32Array([ray.direction.x, ray.direction.y, ray.direction.z]); if (!_this.scene.useRightHandedSystem) { origin[2] *= -1; direction[2] *= -1; } // Fire hittest _this._xrSession.requestHitTest(origin, direction, _this._frameOfReference) .then(function (hits) { if (hits.length > 0) { _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].FromFloat32ArrayToRefScaled(hits[0].hitMatrix, 0, 1.0, _this._tmpMatrix); var hitPoint = _this._tmpMatrix.getTranslation(); if (!_this.scene.useRightHandedSystem) { hitPoint.z *= -1; } res(hitPoint); } else { res(null); } }).catch(function () { res(null); }); }); }; /** * Checks if a session would be supported for the creation options specified * @param options creation options to check if they are supported * @returns true if supported */ WebXRSessionManager.prototype.supportsSessionAsync = function (options) { return this._xrDevice.supportsSession(options).then(function () { return true; }).catch(function () { return false; }); }; /** * @hidden * Converts the render layer of xrSession to a render target * @param session session to create render target for * @param scene scene the new render target should be created for */ WebXRSessionManager._CreateRenderTargetTextureFromSession = function (session, scene) { // Create internal texture var internalTexture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_3__["InternalTexture"](scene.getEngine(), _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_3__["InternalTexture"].DATASOURCE_UNKNOWN, true); internalTexture.width = session.baseLayer.framebufferWidth; internalTexture.height = session.baseLayer.framebufferHeight; internalTexture._framebuffer = session.baseLayer.framebuffer; // Create render target texture from the internal texture var renderTargetTexture = new _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_4__["RenderTargetTexture"]("XR renderTargetTexture", { width: internalTexture.width, height: internalTexture.height }, scene, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, true); renderTargetTexture._texture = internalTexture; return renderTargetTexture; }; /** * Disposes of the session manager */ WebXRSessionManager.prototype.dispose = function () { this.onXRFrameObservable.clear(); this.onXRSessionEnded.clear(); }; return WebXRSessionManager; }()); /***/ }), /***/ "./Cameras/arcRotateCamera.ts": /*!************************************!*\ !*** ./Cameras/arcRotateCamera.ts ***! \************************************/ /*! exports provided: ArcRotateCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCamera", function() { return ArcRotateCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../node */ "./node.ts"); /* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts"); /* harmony import */ var _Behaviors_Cameras_autoRotationBehavior__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Behaviors/Cameras/autoRotationBehavior */ "./Behaviors/Cameras/autoRotationBehavior.ts"); /* harmony import */ var _Behaviors_Cameras_bouncingBehavior__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Behaviors/Cameras/bouncingBehavior */ "./Behaviors/Cameras/bouncingBehavior.ts"); /* harmony import */ var _Behaviors_Cameras_framingBehavior__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Behaviors/Cameras/framingBehavior */ "./Behaviors/Cameras/framingBehavior.ts"); /* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./camera */ "./Cameras/camera.ts"); /* harmony import */ var _targetCamera__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./targetCamera */ "./Cameras/targetCamera.ts"); /* harmony import */ var _Cameras_arcRotateCameraInputsManager__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Cameras/arcRotateCameraInputsManager */ "./Cameras/arcRotateCameraInputsManager.ts"); _node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("ArcRotateCamera", function (name, scene) { return function () { return new ArcRotateCamera(name, 0, 0, 1.0, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), scene); }; }); /** * This represents an orbital type of camera. * * This camera always points towards a given target position and can be rotated around that target with the target as the centre of rotation. It can be controlled with cursors and mouse, or with touch events. * Think of this camera as one orbiting its target position, or more imaginatively as a spy satellite orbiting the earth. Its position relative to the target (earth) can be set by three parameters, alpha (radians) the longitudinal rotation, beta (radians) the latitudinal rotation and radius the distance from the target position. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera */ var ArcRotateCamera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ArcRotateCamera, _super); /** * Instantiates a new ArcRotateCamera in a given scene * @param name Defines the name of the camera * @param alpha Defines the camera rotation along the logitudinal axis * @param beta Defines the camera rotation along the latitudinal axis * @param radius Defines the camera distance from its target * @param target Defines the camera target * @param scene Defines the scene the camera belongs to * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined */ function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) { if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; } var _this = _super.call(this, name, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), scene, setActiveOnSceneIfNoneActive) || this; _this._upVector = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Up(); /** * Current inertia value on the longitudinal axis. * The bigger this number the longer it will take for the camera to stop. */ _this.inertialAlphaOffset = 0; /** * Current inertia value on the latitudinal axis. * The bigger this number the longer it will take for the camera to stop. */ _this.inertialBetaOffset = 0; /** * Current inertia value on the radius axis. * The bigger this number the longer it will take for the camera to stop. */ _this.inertialRadiusOffset = 0; /** * Minimum allowed angle on the longitudinal axis. * This can help limiting how the Camera is able to move in the scene. */ _this.lowerAlphaLimit = null; /** * Maximum allowed angle on the longitudinal axis. * This can help limiting how the Camera is able to move in the scene. */ _this.upperAlphaLimit = null; /** * Minimum allowed angle on the latitudinal axis. * This can help limiting how the Camera is able to move in the scene. */ _this.lowerBetaLimit = 0.01; /** * Maximum allowed angle on the latitudinal axis. * This can help limiting how the Camera is able to move in the scene. */ _this.upperBetaLimit = Math.PI - 0.01; /** * Minimum allowed distance of the camera to the target (The camera can not get closer). * This can help limiting how the Camera is able to move in the scene. */ _this.lowerRadiusLimit = null; /** * Maximum allowed distance of the camera to the target (The camera can not get further). * This can help limiting how the Camera is able to move in the scene. */ _this.upperRadiusLimit = null; /** * Defines the current inertia value used during panning of the camera along the X axis. */ _this.inertialPanningX = 0; /** * Defines the current inertia value used during panning of the camera along the Y axis. */ _this.inertialPanningY = 0; /** * Defines the distance used to consider the camera in pan mode vs pinch/zoom. * Basically if your fingers moves away from more than this distance you will be considered * in pinch mode. */ _this.pinchToPanMaxDistance = 20; /** * Defines the maximum distance the camera can pan. * This could help keeping the cammera always in your scene. */ _this.panningDistanceLimit = null; /** * Defines the target of the camera before paning. */ _this.panningOriginTarget = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); /** * Defines the value of the inertia used during panning. * 0 would mean stop inertia and one would mean no decelleration at all. */ _this.panningInertia = 0.9; //-- end properties for backward compatibility for inputs /** * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function) */ _this.zoomOnFactor = 1; /** * Defines a screen offset for the camera position. */ _this.targetScreenOffset = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector2"].Zero(); /** * Allows the camera to be completely reversed. * If false the camera can not arrive upside down. */ _this.allowUpsideDown = true; /** * Define if double tap/click is used to restore the previously saved state of the camera. */ _this.useInputToRestoreState = true; /** @hidden */ _this._viewMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"](); /** * Defines the allowed panning axis. */ _this.panningAxis = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](1, 1, 0); /** * Observable triggered when the mesh target has been changed on the camera. */ _this.onMeshTargetChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Defines whether the camera should check collision with the objects oh the scene. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this */ _this.checkCollisions = false; /** * Defines the collision radius of the camera. * This simulates a sphere around the camera. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera */ _this.collisionRadius = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0.5, 0.5, 0.5); _this._previousPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); _this._collisionVelocity = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); _this._newPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); _this._computationVector = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) { if (collidedMesh === void 0) { collidedMesh = null; } if (!collidedMesh) { _this._previousPosition.copyFrom(_this._position); } else { _this.setPosition(newPosition); if (_this.onCollide) { _this.onCollide(collidedMesh); } } // Recompute because of constraints var cosa = Math.cos(_this.alpha); var sina = Math.sin(_this.alpha); var cosb = Math.cos(_this.beta); var sinb = Math.sin(_this.beta); if (sinb === 0) { sinb = 0.0001; } var target = _this._getTargetPosition(); _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb); target.addToRef(_this._computationVector, _this._newPosition); _this._position.copyFrom(_this._newPosition); var up = _this.upVector; if (_this.allowUpsideDown && _this.beta < 0) { up = up.clone(); up = up.negate(); } _this._computeViewMatrix(_this._position, target, up); _this._viewMatrix.addAtIndex(12, _this.targetScreenOffset.x); _this._viewMatrix.addAtIndex(13, _this.targetScreenOffset.y); _this._collisionTriggered = false; }; _this._target = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); if (target) { _this.setTarget(target); } _this.alpha = alpha; _this.beta = beta; _this.radius = radius; _this.getViewMatrix(); _this.inputs = new _Cameras_arcRotateCameraInputsManager__WEBPACK_IMPORTED_MODULE_11__["ArcRotateCameraInputsManager"](_this); _this.inputs.addKeyboard().addMouseWheel().addPointers(); return _this; } Object.defineProperty(ArcRotateCamera.prototype, "target", { /** * Defines the target point of the camera. * The camera looks towards it form the radius distance. */ get: function () { return this._target; }, set: function (value) { this.setTarget(value); }, enumerable: true, configurable: true }); Object.defineProperty(ArcRotateCamera.prototype, "position", { /** * Define the current local position of the camera in the scene */ get: function () { return this._position; }, set: function (newPosition) { this.setPosition(newPosition); }, enumerable: true, configurable: true }); Object.defineProperty(ArcRotateCamera.prototype, "upVector", { get: function () { return this._upVector; }, /** * The vector the camera should consider as up. (default is Vector3(0, 1, 0) as returned by Vector3.Up()) * Setting this will copy the given vector to the camera's upVector, and set rotation matrices to and from Y up. * DO NOT set the up vector using copyFrom or copyFromFloats, as this bypasses setting the above matrices. */ set: function (vec) { if (!this._upToYMatrix) { this._YToUpMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"](); this._upToYMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"](); this._upVector = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); } vec.normalize(); this._upVector.copyFrom(vec); this.setMatUp(); }, enumerable: true, configurable: true }); /** * Sets the Y-up to camera up-vector rotation matrix, and the up-vector to Y-up rotation matrix. */ ArcRotateCamera.prototype.setMatUp = function () { // from y-up to custom-up (used in _getViewMatrix) _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].RotationAlignToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].UpReadOnly, this._upVector, this._YToUpMatrix); // from custom-up to y-up (used in rebuildAnglesAndRadius) _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].RotationAlignToRef(this._upVector, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].UpReadOnly, this._upToYMatrix); }; Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", { //-- begin properties for backward compatibility for inputs /** * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating. */ get: function () { var pointers = this.inputs.attached["pointers"]; if (pointers) { return pointers.angularSensibilityX; } return 0; }, set: function (value) { var pointers = this.inputs.attached["pointers"]; if (pointers) { pointers.angularSensibilityX = value; } }, enumerable: true, configurable: true }); Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", { /** * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating. */ get: function () { var pointers = this.inputs.attached["pointers"]; if (pointers) { return pointers.angularSensibilityY; } return 0; }, set: function (value) { var pointers = this.inputs.attached["pointers"]; if (pointers) { pointers.angularSensibilityY = value; } }, enumerable: true, configurable: true }); Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", { /** * Gets or Set the pointer pinch precision or how fast is the camera zooming. */ get: function () { var pointers = this.inputs.attached["pointers"]; if (pointers) { return pointers.pinchPrecision; } return 0; }, set: function (value) { var pointers = this.inputs.attached["pointers"]; if (pointers) { pointers.pinchPrecision = value; } }, enumerable: true, configurable: true }); Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", { /** * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming. * It will be used instead of pinchDeltaPrecision if different from 0. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used. */ get: function () { var pointers = this.inputs.attached["pointers"]; if (pointers) { return pointers.pinchDeltaPercentage; } return 0; }, set: function (value) { var pointers = this.inputs.attached["pointers"]; if (pointers) { pointers.pinchDeltaPercentage = value; } }, enumerable: true, configurable: true }); Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", { /** * Gets or Set the pointer panning sensibility or how fast is the camera moving. */ get: function () { var pointers = this.inputs.attached["pointers"]; if (pointers) { return pointers.panningSensibility; } return 0; }, set: function (value) { var pointers = this.inputs.attached["pointers"]; if (pointers) { pointers.panningSensibility = value; } }, enumerable: true, configurable: true }); Object.defineProperty(ArcRotateCamera.prototype, "keysUp", { /** * Gets or Set the list of keyboard keys used to control beta angle in a positive direction. */ get: function () { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { return keyboard.keysUp; } return []; }, set: function (value) { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { keyboard.keysUp = value; } }, enumerable: true, configurable: true }); Object.defineProperty(ArcRotateCamera.prototype, "keysDown", { /** * Gets or Set the list of keyboard keys used to control beta angle in a negative direction. */ get: function () { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { return keyboard.keysDown; } return []; }, set: function (value) { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { keyboard.keysDown = value; } }, enumerable: true, configurable: true }); Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", { /** * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction. */ get: function () { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { return keyboard.keysLeft; } return []; }, set: function (value) { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { keyboard.keysLeft = value; } }, enumerable: true, configurable: true }); Object.defineProperty(ArcRotateCamera.prototype, "keysRight", { /** * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction. */ get: function () { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { return keyboard.keysRight; } return []; }, set: function (value) { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { keyboard.keysRight = value; } }, enumerable: true, configurable: true }); Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", { /** * Gets or Set the mouse wheel precision or how fast is the camera zooming. */ get: function () { var mousewheel = this.inputs.attached["mousewheel"]; if (mousewheel) { return mousewheel.wheelPrecision; } return 0; }, set: function (value) { var mousewheel = this.inputs.attached["mousewheel"]; if (mousewheel) { mousewheel.wheelPrecision = value; } }, enumerable: true, configurable: true }); Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", { /** * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming. * It will be used instead of pinchDeltaPrecision if different from 0. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used. */ get: function () { var mousewheel = this.inputs.attached["mousewheel"]; if (mousewheel) { return mousewheel.wheelDeltaPercentage; } return 0; }, set: function (value) { var mousewheel = this.inputs.attached["mousewheel"]; if (mousewheel) { mousewheel.wheelDeltaPercentage = value; } }, enumerable: true, configurable: true }); Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", { /** * Gets the bouncing behavior of the camera if it has been enabled. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior */ get: function () { return this._bouncingBehavior; }, enumerable: true, configurable: true }); Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", { /** * Defines if the bouncing behavior of the camera is enabled on the camera. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior */ get: function () { return this._bouncingBehavior != null; }, set: function (value) { if (value === this.useBouncingBehavior) { return; } if (value) { this._bouncingBehavior = new _Behaviors_Cameras_bouncingBehavior__WEBPACK_IMPORTED_MODULE_7__["BouncingBehavior"](); this.addBehavior(this._bouncingBehavior); } else if (this._bouncingBehavior) { this.removeBehavior(this._bouncingBehavior); this._bouncingBehavior = null; } }, enumerable: true, configurable: true }); Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", { /** * Gets the framing behavior of the camera if it has been enabled. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior */ get: function () { return this._framingBehavior; }, enumerable: true, configurable: true }); Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", { /** * Defines if the framing behavior of the camera is enabled on the camera. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior */ get: function () { return this._framingBehavior != null; }, set: function (value) { if (value === this.useFramingBehavior) { return; } if (value) { this._framingBehavior = new _Behaviors_Cameras_framingBehavior__WEBPACK_IMPORTED_MODULE_8__["FramingBehavior"](); this.addBehavior(this._framingBehavior); } else if (this._framingBehavior) { this.removeBehavior(this._framingBehavior); this._framingBehavior = null; } }, enumerable: true, configurable: true }); Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", { /** * Gets the auto rotation behavior of the camera if it has been enabled. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior */ get: function () { return this._autoRotationBehavior; }, enumerable: true, configurable: true }); Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", { /** * Defines if the auto rotation behavior of the camera is enabled on the camera. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior */ get: function () { return this._autoRotationBehavior != null; }, set: function (value) { if (value === this.useAutoRotationBehavior) { return; } if (value) { this._autoRotationBehavior = new _Behaviors_Cameras_autoRotationBehavior__WEBPACK_IMPORTED_MODULE_6__["AutoRotationBehavior"](); this.addBehavior(this._autoRotationBehavior); } else if (this._autoRotationBehavior) { this.removeBehavior(this._autoRotationBehavior); this._autoRotationBehavior = null; } }, enumerable: true, configurable: true }); // Cache /** @hidden */ ArcRotateCamera.prototype._initCache = function () { _super.prototype._initCache.call(this); this._cache._target = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); this._cache.alpha = undefined; this._cache.beta = undefined; this._cache.radius = undefined; this._cache.targetScreenOffset = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector2"].Zero(); }; /** @hidden */ ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) { if (!ignoreParentClass) { _super.prototype._updateCache.call(this); } this._cache._target.copyFrom(this._getTargetPosition()); this._cache.alpha = this.alpha; this._cache.beta = this.beta; this._cache.radius = this.radius; this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset); }; ArcRotateCamera.prototype._getTargetPosition = function () { if (this._targetHost && this._targetHost.getAbsolutePosition) { var pos = this._targetHost.absolutePosition; if (this._targetBoundingCenter) { pos.addToRef(this._targetBoundingCenter, this._target); } else { this._target.copyFrom(pos); } } var lockedTargetPosition = this._getLockedTargetPosition(); if (lockedTargetPosition) { return lockedTargetPosition; } return this._target; }; /** * Stores the current state of the camera (alpha, beta, radius and target) * @returns the camera itself */ ArcRotateCamera.prototype.storeState = function () { this._storedAlpha = this.alpha; this._storedBeta = this.beta; this._storedRadius = this.radius; this._storedTarget = this._getTargetPosition().clone(); return _super.prototype.storeState.call(this); }; /** * @hidden * Restored camera state. You must call storeState() first */ ArcRotateCamera.prototype._restoreStateValues = function () { if (!_super.prototype._restoreStateValues.call(this)) { return false; } this.alpha = this._storedAlpha; this.beta = this._storedBeta; this.radius = this._storedRadius; this.setTarget(this._storedTarget.clone()); this.inertialAlphaOffset = 0; this.inertialBetaOffset = 0; this.inertialRadiusOffset = 0; this.inertialPanningX = 0; this.inertialPanningY = 0; return true; }; // Synchronized /** @hidden */ ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () { if (!_super.prototype._isSynchronizedViewMatrix.call(this)) { return false; } return this._cache._target.equals(this._getTargetPosition()) && this._cache.alpha === this.alpha && this._cache.beta === this.beta && this._cache.radius === this.radius && this._cache.targetScreenOffset.equals(this.targetScreenOffset); }; /** * Attached controls to the current camera. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls * @param panningMouseButton Defines whether panning is allowed through mouse click button */ ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) { var _this = this; if (useCtrlForPanning === void 0) { useCtrlForPanning = true; } if (panningMouseButton === void 0) { panningMouseButton = 2; } this._useCtrlForPanning = useCtrlForPanning; this._panningMouseButton = panningMouseButton; this.inputs.attachElement(element, noPreventDefault); this._reset = function () { _this.inertialAlphaOffset = 0; _this.inertialBetaOffset = 0; _this.inertialRadiusOffset = 0; _this.inertialPanningX = 0; _this.inertialPanningY = 0; }; }; /** * Detach the current controls from the camera. * The camera will stop reacting to inputs. * @param element Defines the element to stop listening the inputs from */ ArcRotateCamera.prototype.detachControl = function (element) { this.inputs.detachElement(element); if (this._reset) { this._reset(); } }; /** @hidden */ ArcRotateCamera.prototype._checkInputs = function () { //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called. if (this._collisionTriggered) { return; } this.inputs.checkInputs(); // Inertia if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) { var inertialAlphaOffset = this.inertialAlphaOffset; if (this.beta <= 0) { inertialAlphaOffset *= -1; } if (this.getScene().useRightHandedSystem) { inertialAlphaOffset *= -1; } if (this.parent && this.parent._getWorldMatrixDeterminant() < 0) { inertialAlphaOffset *= -1; } this.alpha += inertialAlphaOffset; this.beta += this.inertialBetaOffset; this.radius -= this.inertialRadiusOffset; this.inertialAlphaOffset *= this.inertia; this.inertialBetaOffset *= this.inertia; this.inertialRadiusOffset *= this.inertia; if (Math.abs(this.inertialAlphaOffset) < _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]) { this.inertialAlphaOffset = 0; } if (Math.abs(this.inertialBetaOffset) < _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]) { this.inertialBetaOffset = 0; } if (Math.abs(this.inertialRadiusOffset) < this.speed * _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]) { this.inertialRadiusOffset = 0; } } // Panning inertia if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) { if (!this._localDirection) { this._localDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); this._transformedDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); } this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY); this._localDirection.multiplyInPlace(this.panningAxis); this._viewMatrix.invertToRef(this._cameraTransformMatrix); _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection); //Eliminate y if map panning is enabled (panningAxis == 1,0,1) if (!this.panningAxis.y) { this._transformedDirection.y = 0; } if (!this._targetHost) { if (this.panningDistanceLimit) { this._transformedDirection.addInPlace(this._target); var distanceSquared = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].DistanceSquared(this._transformedDirection, this.panningOriginTarget); if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) { this._target.copyFrom(this._transformedDirection); } } else { this._target.addInPlace(this._transformedDirection); } } this.inertialPanningX *= this.panningInertia; this.inertialPanningY *= this.panningInertia; if (Math.abs(this.inertialPanningX) < this.speed * _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]) { this.inertialPanningX = 0; } if (Math.abs(this.inertialPanningY) < this.speed * _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]) { this.inertialPanningY = 0; } } // Limits this._checkLimits(); _super.prototype._checkInputs.call(this); }; ArcRotateCamera.prototype._checkLimits = function () { if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) { if (this.allowUpsideDown && this.beta > Math.PI) { this.beta = this.beta - (2 * Math.PI); } } else { if (this.beta < this.lowerBetaLimit) { this.beta = this.lowerBetaLimit; } } if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) { if (this.allowUpsideDown && this.beta < -Math.PI) { this.beta = this.beta + (2 * Math.PI); } } else { if (this.beta > this.upperBetaLimit) { this.beta = this.upperBetaLimit; } } if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) { this.alpha = this.lowerAlphaLimit; } if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) { this.alpha = this.upperAlphaLimit; } if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) { this.radius = this.lowerRadiusLimit; this.inertialRadiusOffset = 0; } if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) { this.radius = this.upperRadiusLimit; this.inertialRadiusOffset = 0; } }; /** * Rebuilds angles (alpha, beta) and radius from the give position and target */ ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () { this._position.subtractToRef(this._getTargetPosition(), this._computationVector); // need to rotate to Y up equivalent if up vector not Axis.Y if (this._upVector.x !== 0 || this._upVector.y !== 1.0 || this._upVector.z !== 0) { _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(this._computationVector, this._upToYMatrix, this._computationVector); } this.radius = this._computationVector.length(); if (this.radius === 0) { this.radius = 0.0001; // Just to avoid division by zero } // Alpha if (this._computationVector.x === 0 && this._computationVector.z === 0) { this.alpha = Math.PI / 2; // avoid division by zero when looking along up axis, and set to acos(0) } else { this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2))); } if (this._computationVector.z < 0) { this.alpha = 2 * Math.PI - this.alpha; } // Beta this.beta = Math.acos(this._computationVector.y / this.radius); this._checkLimits(); }; /** * Use a position to define the current camera related information like aplha, beta and radius * @param position Defines the position to set the camera at */ ArcRotateCamera.prototype.setPosition = function (position) { if (this._position.equals(position)) { return; } this._position.copyFrom(position); this.rebuildAnglesAndRadius(); }; /** * Defines the target the camera should look at. * This will automatically adapt alpha beta and radius to fit within the new target. * @param target Defines the new target as a Vector or a mesh * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim) */ ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) { if (toBoundingCenter === void 0) { toBoundingCenter = false; } if (allowSamePosition === void 0) { allowSamePosition = false; } if (target.getBoundingInfo) { if (toBoundingCenter) { this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone(); } else { this._targetBoundingCenter = null; } target.computeWorldMatrix(); this._targetHost = target; this._target = this._getTargetPosition(); this.onMeshTargetChangedObservable.notifyObservers(this._targetHost); } else { var newTarget = target; var currentTarget = this._getTargetPosition(); if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) { return; } this._targetHost = null; this._target = newTarget; this._targetBoundingCenter = null; this.onMeshTargetChangedObservable.notifyObservers(null); } this.rebuildAnglesAndRadius(); }; /** @hidden */ ArcRotateCamera.prototype._getViewMatrix = function () { // Compute var cosa = Math.cos(this.alpha); var sina = Math.sin(this.alpha); var cosb = Math.cos(this.beta); var sinb = Math.sin(this.beta); if (sinb === 0) { sinb = 0.0001; } var target = this._getTargetPosition(); this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb); // Rotate according to up vector if (this._upVector.x !== 0 || this._upVector.y !== 1.0 || this._upVector.z !== 0) { _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(this._computationVector, this._YToUpMatrix, this._computationVector); } target.addToRef(this._computationVector, this._newPosition); if (this.getScene().collisionsEnabled && this.checkCollisions) { var coordinator = this.getScene().collisionCoordinator; if (!this._collider) { this._collider = coordinator.createCollider(); } this._collider._radius = this.collisionRadius; this._newPosition.subtractToRef(this._position, this._collisionVelocity); this._collisionTriggered = true; coordinator.getNewPosition(this._position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId); } else { this._position.copyFrom(this._newPosition); var up = this.upVector; if (this.allowUpsideDown && sinb < 0) { up = up.clone(); up = up.negate(); } this._computeViewMatrix(this._position, target, up); this._viewMatrix.addAtIndex(12, this.targetScreenOffset.x); this._viewMatrix.addAtIndex(13, this.targetScreenOffset.y); } this._currentTarget = target; return this._viewMatrix; }; /** * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport. * @param meshes Defines the mesh to zoom on * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance) */ ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) { if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; } meshes = meshes || this.getScene().meshes; var minMaxVector = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__["Mesh"].MinMax(meshes); var distance = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Distance(minMaxVector.min, minMaxVector.max); this.radius = distance * this.zoomOnFactor; this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ); }; /** * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius. * The target will be changed but the radius * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance) */ ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) { if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; } var meshesOrMinMaxVector; var distance; if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes; meshesOrMinMaxVector = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__["Mesh"].MinMax(meshes); distance = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max); } else { //minMaxVector and distance var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance; meshesOrMinMaxVector = minMaxVectorAndDistance; distance = minMaxVectorAndDistance.distance; } this._target = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__["Mesh"].Center(meshesOrMinMaxVector); if (!doNotUpdateMaxZ) { this.maxZ = distance * 2; } }; /** * @override * Override Camera.createRigCamera */ ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) { var alphaShift = 0; switch (this.cameraRigMode) { case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_ANAGLYPH: case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL: case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_OVERUNDER: case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_VR: alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1); break; case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED: alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1); break; } var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene()); rigCam._cameraRigParams = {}; return rigCam; }; /** * @hidden * @override * Override Camera._updateRigCameras */ ArcRotateCamera.prototype._updateRigCameras = function () { var camLeft = this._rigCameras[0]; var camRight = this._rigCameras[1]; camLeft.beta = camRight.beta = this.beta; switch (this.cameraRigMode) { case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_ANAGLYPH: case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL: case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_OVERUNDER: case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_VR: camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle; camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle; break; case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED: camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle; camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle; break; } _super.prototype._updateRigCameras.call(this); }; /** * Destroy the camera and release the current resources hold by it. */ ArcRotateCamera.prototype.dispose = function () { this.inputs.clear(); _super.prototype.dispose.call(this); }; /** * Gets the current object class name. * @return the class name */ ArcRotateCamera.prototype.getClassName = function () { return "ArcRotateCamera"; }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCamera.prototype, "alpha", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCamera.prototype, "beta", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCamera.prototype, "radius", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])("target") ], ArcRotateCamera.prototype, "_target", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])("upVector") ], ArcRotateCamera.prototype, "_upVector", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCamera.prototype, "upperBetaLimit", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCamera.prototype, "inertialPanningX", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCamera.prototype, "inertialPanningY", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])() ], ArcRotateCamera.prototype, "panningOriginTarget", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCamera.prototype, "panningInertia", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCamera.prototype, "zoomOnFactor", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCamera.prototype, "targetScreenOffset", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCamera.prototype, "allowUpsideDown", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0); return ArcRotateCamera; }(_targetCamera__WEBPACK_IMPORTED_MODULE_10__["TargetCamera"])); /***/ }), /***/ "./Cameras/arcRotateCameraInputsManager.ts": /*!*************************************************!*\ !*** ./Cameras/arcRotateCameraInputsManager.ts ***! \*************************************************/ /*! exports provided: ArcRotateCameraInputsManager */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraInputsManager", function() { return ArcRotateCameraInputsManager; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Cameras_Inputs_arcRotateCameraPointersInput__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Cameras/Inputs/arcRotateCameraPointersInput */ "./Cameras/Inputs/arcRotateCameraPointersInput.ts"); /* harmony import */ var _Cameras_Inputs_arcRotateCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Cameras/Inputs/arcRotateCameraKeyboardMoveInput */ "./Cameras/Inputs/arcRotateCameraKeyboardMoveInput.ts"); /* harmony import */ var _Cameras_Inputs_arcRotateCameraMouseWheelInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Cameras/Inputs/arcRotateCameraMouseWheelInput */ "./Cameras/Inputs/arcRotateCameraMouseWheelInput.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /** * Default Inputs manager for the ArcRotateCamera. * It groups all the default supported inputs for ease of use. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs */ var ArcRotateCameraInputsManager = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ArcRotateCameraInputsManager, _super); /** * Instantiates a new ArcRotateCameraInputsManager. * @param camera Defines the camera the inputs belong to */ function ArcRotateCameraInputsManager(camera) { return _super.call(this, camera) || this; } /** * Add mouse wheel input support to the input manager. * @returns the current input manager */ ArcRotateCameraInputsManager.prototype.addMouseWheel = function () { this.add(new _Cameras_Inputs_arcRotateCameraMouseWheelInput__WEBPACK_IMPORTED_MODULE_3__["ArcRotateCameraMouseWheelInput"]()); return this; }; /** * Add pointers input support to the input manager. * @returns the current input manager */ ArcRotateCameraInputsManager.prototype.addPointers = function () { this.add(new _Cameras_Inputs_arcRotateCameraPointersInput__WEBPACK_IMPORTED_MODULE_1__["ArcRotateCameraPointersInput"]()); return this; }; /** * Add keyboard input support to the input manager. * @returns the current input manager */ ArcRotateCameraInputsManager.prototype.addKeyboard = function () { this.add(new _Cameras_Inputs_arcRotateCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_2__["ArcRotateCameraKeyboardMoveInput"]()); return this; }; return ArcRotateCameraInputsManager; }(_Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_4__["CameraInputsManager"])); /***/ }), /***/ "./Cameras/camera.ts": /*!***************************!*\ !*** ./Cameras/camera.ts ***! \***************************/ /*! exports provided: Camera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Camera", function() { return Camera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Misc_smartArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/smartArray */ "./Misc/smartArray.ts"); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../node */ "./node.ts"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); /* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Misc/devTools */ "./Misc/devTools.ts"); /** * This is the base class of all the camera used in the application. * @see http://doc.babylonjs.com/features/cameras */ var Camera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Camera, _super); /** * Instantiates a new camera object. * This should not be used directly but through the inherited cameras: ArcRotate, Free... * @see http://doc.babylonjs.com/features/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 */ function Camera(name, position, scene, setActiveOnSceneIfNoneActive) { if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; } var _this = _super.call(this, name, scene) || this; /** @hidden */ _this._position = _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Vector3"].Zero(); /** * The vector the camera should consider as up. * (default is Vector3(0, 1, 0) aka Vector3.Up()) */ _this.upVector = _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Vector3"].Up(); /** * Define the current limit on the left side for an orthographic camera * In scene unit */ _this.orthoLeft = null; /** * Define the current limit on the right side for an orthographic camera * In scene unit */ _this.orthoRight = null; /** * Define the current limit on the bottom side for an orthographic camera * In scene unit */ _this.orthoBottom = null; /** * Define the current limit on the top side for an orthographic camera * In scene unit */ _this.orthoTop = null; /** * Field Of View is set in Radians. (default is 0.8) */ _this.fov = 0.8; /** * Define the minimum distance the camera can see from. * This is important to note that the depth buffer are not infinite and the closer it starts * the more your scene might encounter depth fighting issue. */ _this.minZ = 1; /** * Define the maximum distance the camera can see to. * This is important to note that the depth buffer are not infinite and the further it end * the more your scene might encounter depth fighting issue. */ _this.maxZ = 10000.0; /** * Define the default inertia of the camera. * This helps giving a smooth feeling to the camera movement. */ _this.inertia = 0.9; /** * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC) */ _this.mode = Camera.PERSPECTIVE_CAMERA; /** * Define wether the camera is intermediate. * This is useful to not present the output directly to the screen in case of rig without post process for instance */ _this.isIntermediate = false; /** * Define the viewport of the camera. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit. */ _this.viewport = new _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Viewport"](0, 0, 1.0, 1.0); /** * Restricts the camera to viewing objects with the same layerMask. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0 */ _this.layerMask = 0x0FFFFFFF; /** * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED) */ _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED; /** * Rig mode of the camera. * This is useful to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes. * This is normally controlled byt the camera themselves as internal use. */ _this.cameraRigMode = Camera.RIG_MODE_NONE; /** * Defines the list of custom render target which are rendered to and then used as the input to this camera's render. Eg. display another camera view on a TV in the main scene * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere * else in the scene. */ _this.customRenderTargets = new Array(); /** * When set, the camera will render to this render target instead of the default canvas */ _this.outputRenderTarget = null; /** * Observable triggered when the camera view matrix has changed. */ _this.onViewMatrixChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_4__["Observable"](); /** * Observable triggered when the camera Projection matrix has changed. */ _this.onProjectionMatrixChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_4__["Observable"](); /** * Observable triggered when the inputs have been processed. */ _this.onAfterCheckInputsObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_4__["Observable"](); /** * Observable triggered when reset has been called and applied to the camera. */ _this.onRestoreStateObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_4__["Observable"](); /** @hidden */ _this._rigCameras = new Array(); _this._webvrViewMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].Identity(); /** @hidden */ _this._skipRendering = false; /** @hidden */ _this._projectionMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"](); /** @hidden */ _this._postProcesses = new Array(); /** @hidden */ _this._activeMeshes = new _Misc_smartArray__WEBPACK_IMPORTED_MODULE_2__["SmartArray"](256); _this._globalPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Vector3"].Zero(); /** hidden */ _this._computedViewMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].Identity(); _this._doNotComputeProjectionMatrix = false; _this._transformMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].Zero(); _this._refreshFrustumPlanes = true; /** @hidden */ _this._isCamera = true; /** @hidden */ _this._isLeftCamera = false; /** @hidden */ _this._isRightCamera = true; _this.getScene().addCamera(_this); if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) { _this.getScene().activeCamera = _this; } _this.position = position; return _this; } Object.defineProperty(Camera.prototype, "position", { /** * Define the current local position of the camera in the scene */ get: function () { return this._position; }, set: function (newPosition) { this._position = newPosition; }, enumerable: true, configurable: true }); /** * Store current camera state (fov, position, etc..) * @returns the camera */ Camera.prototype.storeState = function () { this._stateStored = true; this._storedFov = this.fov; return this; }; /** * Restores the camera state values if it has been stored. You must call storeState() first */ Camera.prototype._restoreStateValues = function () { 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 */ Camera.prototype.restoreState = function () { if (this._restoreStateValues()) { this.onRestoreStateObservable.notifyObservers(this); return true; } return false; }; /** * Gets the class name of the camera. * @returns the class name */ Camera.prototype.getClassName = function () { return "Camera"; }; /** * Gets a string representation of the camera useful for debug purpose. * @param fullDetails Defines that a more verboe level of logging is required * @returns the string representation */ Camera.prototype.toString = function (fullDetails) { var ret = "Name: " + this.name; ret += ", type: " + this.getClassName(); if (this.animations) { for (var i = 0; i < this.animations.length; i++) { ret += ", animation[0]: " + this.animations[i].toString(fullDetails); } } if (fullDetails) { } return ret; }; Object.defineProperty(Camera.prototype, "globalPosition", { /** * Gets the current world space position of the camera. */ get: function () { return this._globalPosition; }, enumerable: true, configurable: true }); /** * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame) * @returns the active meshe list */ Camera.prototype.getActiveMeshes = function () { return this._activeMeshes; }; /** * Check wether 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 */ Camera.prototype.isActiveMesh = function (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) * @return true if the camera is ready */ Camera.prototype.isReady = function (completeCheck) { if (completeCheck === void 0) { completeCheck = false; } if (completeCheck) { for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) { var pp = _a[_i]; if (pp && !pp.isReady()) { return false; } } } return _super.prototype.isReady.call(this, completeCheck); }; /** @hidden */ Camera.prototype._initCache = function () { _super.prototype._initCache.call(this); this._cache.position = new _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Vector3"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); this._cache.upVector = new _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Vector3"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); this._cache.mode = undefined; this._cache.minZ = undefined; this._cache.maxZ = undefined; this._cache.fov = undefined; this._cache.fovMode = undefined; this._cache.aspectRatio = undefined; this._cache.orthoLeft = undefined; this._cache.orthoRight = undefined; this._cache.orthoBottom = undefined; this._cache.orthoTop = undefined; this._cache.renderWidth = undefined; this._cache.renderHeight = undefined; }; /** @hidden */ Camera.prototype._updateCache = function (ignoreParentClass) { if (!ignoreParentClass) { _super.prototype._updateCache.call(this); } this._cache.position.copyFrom(this.position); this._cache.upVector.copyFrom(this.upVector); }; /** @hidden */ Camera.prototype._isSynchronized = function () { return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix(); }; /** @hidden */ Camera.prototype._isSynchronizedViewMatrix = function () { if (!_super.prototype._isSynchronized.call(this)) { return false; } return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent(); }; /** @hidden */ Camera.prototype._isSynchronizedProjectionMatrix = function () { var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ; if (!check) { return false; } var engine = this.getEngine(); if (this.mode === Camera.PERSPECTIVE_CAMERA) { check = this._cache.fov === this.fov && this._cache.fovMode === this.fovMode && this._cache.aspectRatio === engine.getAspectRatio(this); } else { check = 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(); } return check; }; /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ Camera.prototype.attachControl = function (element, noPreventDefault) { }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ Camera.prototype.detachControl = function (element) { }; /** * Update the camera state according to the different inputs gathered during the frame. */ Camera.prototype.update = function () { this._checkInputs(); if (this.cameraRigMode !== Camera.RIG_MODE_NONE) { this._updateRigCameras(); } }; /** @hidden */ Camera.prototype._checkInputs = function () { this.onAfterCheckInputsObservable.notifyObservers(this); }; Object.defineProperty(Camera.prototype, "rigCameras", { /** @hidden */ get: function () { return this._rigCameras; }, enumerable: true, configurable: true }); Object.defineProperty(Camera.prototype, "rigPostProcess", { /** * Gets the post process used by the rig cameras */ get: function () { return this._rigPostProcess; }, enumerable: true, configurable: true }); /** * Internal, gets the first post proces. * @returns the first post process to be run on this camera. */ Camera.prototype._getFirstPostProcess = function () { for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) { if (this._postProcesses[ppIndex] !== null) { return this._postProcesses[ppIndex]; } } return null; }; Camera.prototype._cascadePostProcessesToRigCams = function () { // invalidate framebuffer var firstPostProcess = this._getFirstPostProcess(); if (firstPostProcess) { firstPostProcess.markTextureDirty(); } // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera for (var i = 0, len = this._rigCameras.length; i < len; i++) { var cam = this._rigCameras[i]; var rigPostProcess = cam._rigPostProcess; // for VR rig, there does not have to be a post process if (rigPostProcess) { var isPass = rigPostProcess.getEffectName() === "pass"; if (isPass) { // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses cam.isIntermediate = this._postProcesses.length === 0; } cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess); rigPostProcess.markTextureDirty(); } else { cam._postProcesses = this._postProcesses.slice(0); } } }; /** * Attach a post process to the camera. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#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 */ Camera.prototype.attachPostProcess = function (postProcess, insertAt) { if (insertAt === void 0) { insertAt = null; } if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) { _Misc_logger__WEBPACK_IMPORTED_MODULE_7__["Logger"].Error("You're trying to reuse a post process not defined as reusable."); return 0; } if (insertAt == null || insertAt < 0) { this._postProcesses.push(postProcess); } else if (this._postProcesses[insertAt] === null) { this._postProcesses[insertAt] = postProcess; } else { this._postProcesses.splice(insertAt, 0, postProcess); } this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated return this._postProcesses.indexOf(postProcess); }; /** * Detach a post process to the camera. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess * @param postProcess The post process to detach from the camera */ Camera.prototype.detachPostProcess = function (postProcess) { var idx = this._postProcesses.indexOf(postProcess); if (idx !== -1) { this._postProcesses[idx] = null; } this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated }; /** * Gets the current world matrix of the camera */ Camera.prototype.getWorldMatrix = function () { if (this._isSynchronizedViewMatrix()) { return this._worldMatrix; } // Getting the the view matrix will also compute the world matrix. this.getViewMatrix(); return this._worldMatrix; }; /** @hidden */ Camera.prototype._getViewMatrix = function () { return _Maths_math__WEBPACK_IMPORTED_MODULE_5__["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 */ Camera.prototype.getViewMatrix = function (force) { if (!force && this._isSynchronizedViewMatrix()) { return this._computedViewMatrix; } 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); } 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 */ Camera.prototype.freezeProjectionMatrix = function (projection) { this._doNotComputeProjectionMatrix = true; if (projection !== undefined) { this._projectionMatrix = projection; } }; /** * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix. */ Camera.prototype.unfreezeProjectionMatrix = function () { 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 */ Camera.prototype.getProjectionMatrix = function (force) { if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) { return this._projectionMatrix; } // Cache this._cache.mode = this.mode; this._cache.minZ = this.minZ; this._cache.maxZ = this.maxZ; // Matrix this._refreshFrustumPlanes = true; var engine = this.getEngine(); var scene = this.getScene(); if (this.mode === Camera.PERSPECTIVE_CAMERA) { this._cache.fov = this.fov; this._cache.fovMode = this.fovMode; this._cache.aspectRatio = engine.getAspectRatio(this); if (this.minZ <= 0) { this.minZ = 0.1; } if (scene.useRightHandedSystem) { _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED); } else { _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED); } } else { var halfWidth = engine.getRenderWidth() / 2.0; var halfHeight = engine.getRenderHeight() / 2.0; if (scene.useRightHandedSystem) { _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix); } else { _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix); } 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(); } this.onProjectionMatrixChangedObservable.notifyObservers(this); return this._projectionMatrix; }; /** * Gets the transformation matrix (ie. the multiplication of view by projection matrices) * @returns a Matrix */ Camera.prototype.getTransformationMatrix = function () { this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix); return this._transformMatrix; }; Camera.prototype._updateFrustumPlanes = function () { if (!this._refreshFrustumPlanes) { return; } this.getTransformationMatrix(); if (!this._frustumPlanes) { this._frustumPlanes = _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Frustum"].GetPlanes(this._transformMatrix); } else { _Maths_math__WEBPACK_IMPORTED_MODULE_5__["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 * @returns true if the object is in frustum otherwise false */ Camera.prototype.isInFrustum = function (target) { this._updateFrustumPlanes(); return target.isInFrustum(this._frustumPlanes); }; /** * Checks if a cullable object (mesh...) is in the camera frustum * Unlike isInFrustum this cheks the full bounding box * @param target The object to check * @returns true if the object is in frustum otherwise false */ Camera.prototype.isCompletelyInFrustum = function (target) { this._updateFrustumPlanes(); return target.isCompletelyInFrustum(this._frustumPlanes); }; /** * 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 matrx is used to create a workd space ray * @param origin Defines the start point of the ray which defaults to the camera position * @returns the forward ray */ Camera.prototype.getForwardRay = function (length, transform, origin) { if (length === void 0) { length = 100; } throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_9__["_DevTools"].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) */ Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) { if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; } // Observables this.onViewMatrixChangedObservable.clear(); this.onProjectionMatrixChangedObservable.clear(); this.onAfterCheckInputsObservable.clear(); this.onRestoreStateObservable.clear(); // Inputs if (this.inputs) { this.inputs.clear(); } // Animations this.getScene().stopAnimation(this); // Remove from scene this.getScene().removeCamera(this); while (this._rigCameras.length > 0) { var camera = this._rigCameras.pop(); if (camera) { camera.dispose(); } } // Postprocesses if (this._rigPostProcess) { this._rigPostProcess.dispose(this); this._rigPostProcess = null; this._postProcesses = []; } else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) { this._rigPostProcess = null; this._postProcesses = []; } else { var i = this._postProcesses.length; while (--i >= 0) { var postProcess = this._postProcesses[i]; if (postProcess) { postProcess.dispose(this); } } } // Render targets var i = this.customRenderTargets.length; while (--i >= 0) { this.customRenderTargets[i].dispose(); } this.customRenderTargets = []; // Active Meshes this._activeMeshes.dispose(); _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures); }; Object.defineProperty(Camera.prototype, "isLeftCamera", { /** * Gets the left camera of a rig setup in case of Rigged Camera */ get: function () { return this._isLeftCamera; }, enumerable: true, configurable: true }); Object.defineProperty(Camera.prototype, "isRightCamera", { /** * Gets the right camera of a rig setup in case of Rigged Camera */ get: function () { return this._isRightCamera; }, enumerable: true, configurable: true }); Object.defineProperty(Camera.prototype, "leftCamera", { /** * Gets the left camera of a rig setup in case of Rigged Camera */ get: function () { if (this._rigCameras.length < 1) { return null; } return this._rigCameras[0]; }, enumerable: true, configurable: true }); Object.defineProperty(Camera.prototype, "rightCamera", { /** * Gets the right camera of a rig setup in case of Rigged Camera */ get: function () { if (this._rigCameras.length < 2) { return null; } return this._rigCameras[1]; }, enumerable: true, configurable: true }); /** * Gets the left camera target of a rig setup in case of Rigged Camera * @returns the target position */ Camera.prototype.getLeftTarget = function () { 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 */ Camera.prototype.getRightTarget = function () { if (this._rigCameras.length < 2) { return null; } return this._rigCameras[1].getTarget(); }; /** * @hidden */ Camera.prototype.setCameraRigMode = function (mode, rigParams) { if (this.cameraRigMode === mode) { return; } while (this._rigCameras.length > 0) { var camera = this._rigCameras.pop(); if (camera) { camera.dispose(); } } this.cameraRigMode = mode; this._cameraRigParams = {}; //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target, //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637; this._cameraRigParams.stereoHalfAngle = _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].ToRadians(this._cameraRigParams.interaxialDistance / 0.0637); // create the rig cameras, unless none if (this.cameraRigMode !== Camera.RIG_MODE_NONE) { var leftCamera = this.createRigCamera(this.name + "_L", 0); if (leftCamera) { leftCamera._isLeftCamera = true; } var rightCamera = this.createRigCamera(this.name + "_R", 1); if (rightCamera) { rightCamera._isRightCamera = true; } if (leftCamera && rightCamera) { this._rigCameras.push(leftCamera); this._rigCameras.push(rightCamera); } } switch (this.cameraRigMode) { case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH: Camera._setStereoscopicAnaglyphRigMode(this); break; case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL: case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED: case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER: Camera._setStereoscopicRigMode(this); break; case Camera.RIG_MODE_VR: Camera._setVRRigMode(this, rigParams); break; case Camera.RIG_MODE_WEBVR: Camera._setWebVRRigMode(this, rigParams); break; } this._cascadePostProcessesToRigCams(); this.update(); }; /** @hidden */ Camera._setStereoscopicRigMode = function (camera) { throw "Import Cameras/RigModes/stereoscopicRigMode before using stereoscopic rig mode"; }; /** @hidden */ Camera._setStereoscopicAnaglyphRigMode = function (camera) { throw "Import Cameras/RigModes/stereoscopicAnaglyphRigMode before using stereoscopic anaglyph rig mode"; }; /** @hidden */ Camera._setVRRigMode = function (camera, rigParams) { throw "Import Cameras/RigModes/vrRigMode before using VR rig mode"; }; /** @hidden */ Camera._setWebVRRigMode = function (camera, rigParams) { throw "Import Cameras/RigModes/WebVRRigMode before using Web VR rig mode"; }; /** @hidden */ Camera.prototype._getVRProjectionMatrix = function () { _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix); this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix); return this._projectionMatrix; }; Camera.prototype._updateCameraRotationMatrix = function () { //Here for WebVR }; Camera.prototype._updateWebVRCameraRotationMatrix = function () { //Here for WebVR }; /** * This function MUST be overwritten by the different WebVR cameras available. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right. * @hidden */ Camera.prototype._getWebVRProjectionMatrix = function () { return _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].Identity(); }; /** * This function MUST be overwritten by the different WebVR cameras available. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right. * @hidden */ Camera.prototype._getWebVRViewMatrix = function () { return _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].Identity(); }; /** @hidden */ Camera.prototype.setCameraRigParameter = function (name, value) { if (!this._cameraRigParams) { this._cameraRigParams = {}; } this._cameraRigParams[name] = value; //provisionnally: if (name === "interaxialDistance") { this._cameraRigParams.stereoHalfAngle = _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].ToRadians(value / 0.0637); } }; /** * needs to be overridden by children so sub has required properties to be copied * @hidden */ Camera.prototype.createRigCamera = function (name, cameraIndex) { return null; }; /** * May need to be overridden by children * @hidden */ Camera.prototype._updateRigCameras = function () { for (var i = 0; i < this._rigCameras.length; i++) { this._rigCameras[i].minZ = this.minZ; this._rigCameras[i].maxZ = this.maxZ; this._rigCameras[i].fov = this.fov; this._rigCameras[i].upVector.copyFrom(this.upVector); } // only update viewport when ANAGLYPH if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) { this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport; } }; /** @hidden */ Camera.prototype._setupInputs = function () { }; /** * Serialiaze the camera setup to a json represention * @returns the JSON representation */ Camera.prototype.serialize = function () { var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); // Type serializationObject.type = this.getClassName(); // Parent if (this.parent) { serializationObject.parentId = this.parent.id; } if (this.inputs) { this.inputs.serialize(serializationObject); } // Animations _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].AppendSerializedAnimations(this, serializationObject); serializationObject.ranges = this.serializeAnimationRanges(); return serializationObject; }; /** * Clones the current camera. * @param name The cloned camera name * @returns the cloned camera */ Camera.prototype.clone = function (name) { return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this); }; /** * Gets the direction of the camera relative to a given local axis. * @param localAxis Defines the reference axis to provide a relative direction. * @return the direction */ Camera.prototype.getDirection = function (localAxis) { var result = _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Vector3"].Zero(); this.getDirectionToRef(localAxis, result); return result; }; /** * 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 */ Camera.prototype.getDirectionToRef = function (localAxis, result) { _Maths_math__WEBPACK_IMPORTED_MODULE_5__["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 construc the camera */ Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) { if (interaxial_distance === void 0) { interaxial_distance = 0; } if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; } var constructorFunc = _node__WEBPACK_IMPORTED_MODULE_6__["Node"].Construct(type, name, scene, { interaxial_distance: interaxial_distance, isStereoscopicSideBySide: isStereoscopicSideBySide }); if (constructorFunc) { return constructorFunc; } // Default to universal camera return function () { return Camera._createDefaultParsedCamera(name, scene); }; }; /** * Compute the world matrix of the camera. * @returns the camera workd matrix */ Camera.prototype.computeWorldMatrix = function () { 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 */ Camera.Parse = function (parsedCamera, scene) { var type = parsedCamera.type; var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide); var camera = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(construct, parsedCamera, scene); // Parent if (parsedCamera.parentId) { camera._waitingParentId = parsedCamera.parentId; } //If camera has an input manager, let it parse inputs settings if (camera.inputs) { camera.inputs.parse(parsedCamera); camera._setupInputs(); } if (camera.setPosition) { // need to force position camera.position.copyFromFloats(0, 0, 0); camera.setPosition(_Maths_math__WEBPACK_IMPORTED_MODULE_5__["Vector3"].FromArray(parsedCamera.position)); } // Target if (parsedCamera.target) { if (camera.setTarget) { camera.setTarget(_Maths_math__WEBPACK_IMPORTED_MODULE_5__["Vector3"].FromArray(parsedCamera.target)); } } // Apply 3d rig, when found if (parsedCamera.cameraRigMode) { var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {}; camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams); } // Animations if (parsedCamera.animations) { for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) { var parsedAnimation = parsedCamera.animations[animationIndex]; var internalClass = _Misc_typeStore__WEBPACK_IMPORTED_MODULE_8__["_TypeStore"].GetClass("BABYLON.Animation"); if (internalClass) { camera.animations.push(internalClass.Parse(parsedAnimation)); } } _node__WEBPACK_IMPORTED_MODULE_6__["Node"].ParseAnimationRanges(camera, parsedCamera, scene); } if (parsedCamera.autoAnimate) { scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0); } return camera; }; /** @hidden */ Camera._createDefaultParsedCamera = function (name, scene) { throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_9__["_DevTools"].WarnImport("UniversalCamera"); }; /** * This is the default projection mode used by the cameras. * It helps recreating a feeling of perspective and better appreciate depth. * This is the best way to simulate real life cameras. */ Camera.PERSPECTIVE_CAMERA = 0; /** * This helps creating camera with an orthographic mode. * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object. */ Camera.ORTHOGRAPHIC_CAMERA = 1; /** * This is the default FOV mode for perspective cameras. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum. */ Camera.FOVMODE_VERTICAL_FIXED = 0; /** * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum. */ Camera.FOVMODE_HORIZONTAL_FIXED = 1; /** * This specifies ther is no need for a camera rig. * Basically only one eye is rendered corresponding to the camera. */ Camera.RIG_MODE_NONE = 0; /** * Simulates a camera Rig with one blue eye and one red eye. * This can be use with 3d blue and red glasses. */ Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10; /** * Defines that both eyes of the camera will be rendered side by side with a parallel target. */ Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11; /** * Defines that both eyes of the camera will be rendered side by side with a none parallel target. */ Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12; /** * Defines that both eyes of the camera will be rendered over under each other. */ Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13; /** * Defines that both eyes of the camera should be renderered in a VR mode (carbox). */ Camera.RIG_MODE_VR = 20; /** * Defines that both eyes of the camera should be renderered in a VR mode (webVR). */ Camera.RIG_MODE_WEBVR = 21; /** * Custom rig mode allowing rig cameras to be populated manually with any number of cameras */ Camera.RIG_MODE_CUSTOM = 22; /** * Defines if by default attaching controls should prevent the default javascript event to continue. */ Camera.ForceAttachControlToAlwaysPreventDefault = false; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])("position") ], Camera.prototype, "_position", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])() ], Camera.prototype, "upVector", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Camera.prototype, "orthoLeft", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Camera.prototype, "orthoRight", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Camera.prototype, "orthoBottom", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Camera.prototype, "orthoTop", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Camera.prototype, "fov", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Camera.prototype, "minZ", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Camera.prototype, "maxZ", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Camera.prototype, "inertia", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Camera.prototype, "mode", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Camera.prototype, "layerMask", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Camera.prototype, "fovMode", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Camera.prototype, "cameraRigMode", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Camera.prototype, "interaxialDistance", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Camera.prototype, "isStereoscopicSideBySide", void 0); return Camera; }(_node__WEBPACK_IMPORTED_MODULE_6__["Node"])); /***/ }), /***/ "./Cameras/cameraInputsManager.ts": /*!****************************************!*\ !*** ./Cameras/cameraInputsManager.ts ***! \****************************************/ /*! exports provided: CameraInputTypes, CameraInputsManager */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CameraInputTypes", function() { return CameraInputTypes; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CameraInputsManager", function() { return CameraInputsManager; }); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./camera */ "./Cameras/camera.ts"); /** * @ignore * This is a list of all the different input types that are available in the application. * Fo instance: ArcRotateCameraGamepadInput... */ var CameraInputTypes = {}; /** * This represents the input manager used within a camera. * It helps dealing with all the different kind of input attached to a camera. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs */ var CameraInputsManager = /** @class */ (function () { /** * Instantiate a new Camera Input Manager. * @param camera Defines the camera the input manager blongs to */ function CameraInputsManager(camera) { this.attached = {}; this.camera = camera; this.checkInputs = function () { }; } /** * Add an input method to a camera * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs * @param input camera input method */ CameraInputsManager.prototype.add = function (input) { var type = input.getSimpleName(); if (this.attached[type]) { _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Warn("camera input of type " + type + " already exists on camera"); return; } this.attached[type] = input; input.camera = this.camera; //for checkInputs, we are dynamically creating a function //the goal is to avoid the performance penalty of looping for inputs in the render loop if (input.checkInputs) { this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input)); } if (this.attachedElement) { input.attachControl(this.attachedElement); } }; /** * Remove a specific input method from a camera * example: camera.inputs.remove(camera.inputs.attached.mouse); * @param inputToRemove camera input method */ CameraInputsManager.prototype.remove = function (inputToRemove) { for (var cam in this.attached) { var input = this.attached[cam]; if (input === inputToRemove) { input.detachControl(this.attachedElement); input.camera = null; delete this.attached[cam]; this.rebuildInputCheck(); } } }; /** * Remove a specific input type from a camera * example: camera.inputs.remove("ArcRotateCameraGamepadInput"); * @param inputType the type of the input to remove */ CameraInputsManager.prototype.removeByType = function (inputType) { for (var cam in this.attached) { var input = this.attached[cam]; if (input.getClassName() === inputType) { input.detachControl(this.attachedElement); input.camera = null; delete this.attached[cam]; this.rebuildInputCheck(); } } }; CameraInputsManager.prototype._addCheckInputs = function (fn) { var current = this.checkInputs; return function () { current(); fn(); }; }; /** * Attach the input controls to the currently attached dom element to listen the events from. * @param input Defines the input to attach */ CameraInputsManager.prototype.attachInput = function (input) { if (this.attachedElement) { input.attachControl(this.attachedElement, this.noPreventDefault); } }; /** * Attach the current manager inputs controls to a specific dom element to listen the events from. * @param element Defines the dom element to collect the events from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) { if (noPreventDefault === void 0) { noPreventDefault = false; } if (this.attachedElement) { return; } noPreventDefault = _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault; this.attachedElement = element; this.noPreventDefault = noPreventDefault; for (var cam in this.attached) { this.attached[cam].attachControl(element, noPreventDefault); } }; /** * Detach the current manager inputs controls from a specific dom element. * @param element Defines the dom element to collect the events from * @param disconnect Defines whether the input should be removed from the current list of attached inputs */ CameraInputsManager.prototype.detachElement = function (element, disconnect) { if (disconnect === void 0) { disconnect = false; } if (this.attachedElement !== element) { return; } for (var cam in this.attached) { this.attached[cam].detachControl(element); if (disconnect) { this.attached[cam].camera = null; } } this.attachedElement = null; }; /** * Rebuild the dynamic inputCheck function from the current list of * defined inputs in the manager. */ CameraInputsManager.prototype.rebuildInputCheck = function () { this.checkInputs = function () { }; for (var cam in this.attached) { var input = this.attached[cam]; if (input.checkInputs) { this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input)); } } }; /** * Remove all attached input methods from a camera */ CameraInputsManager.prototype.clear = function () { if (this.attachedElement) { this.detachElement(this.attachedElement, true); } this.attached = {}; this.attachedElement = null; this.checkInputs = function () { }; }; /** * Serialize the current input manager attached to a camera. * This ensures than once parsed, * the input associated to the camera will be identical to the current ones * @param serializedCamera Defines the camera serialization JSON the input serialization should write to */ CameraInputsManager.prototype.serialize = function (serializedCamera) { var inputs = {}; for (var cam in this.attached) { var input = this.attached[cam]; var res = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(input); inputs[input.getClassName()] = res; } serializedCamera.inputsmgr = inputs; }; /** * Parses an input manager serialized JSON to restore the previous list of inputs * and states associated to a camera. * @param parsedCamera Defines the JSON to parse */ CameraInputsManager.prototype.parse = function (parsedCamera) { var parsedInputs = parsedCamera.inputsmgr; if (parsedInputs) { this.clear(); for (var n in parsedInputs) { var construct = CameraInputTypes[n]; if (construct) { var parsedinput = parsedInputs[n]; var input = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new construct(); }, parsedinput, null); this.add(input); } } } else { //2016-03-08 this part is for managing backward compatibility for (var n in this.attached) { var construct = CameraInputTypes[this.attached[n].getClassName()]; if (construct) { var input = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new construct(); }, parsedCamera, null); this.remove(this.attached[n]); this.add(input); } } } }; return CameraInputsManager; }()); /***/ }), /***/ "./Cameras/deviceOrientationCamera.ts": /*!********************************************!*\ !*** ./Cameras/deviceOrientationCamera.ts ***! \********************************************/ /*! exports provided: DeviceOrientationCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeviceOrientationCamera", function() { return DeviceOrientationCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _freeCamera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./freeCamera */ "./Cameras/freeCamera.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts"); /* harmony import */ var _Inputs_freeCameraDeviceOrientationInput__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Inputs/freeCameraDeviceOrientationInput */ "./Cameras/Inputs/freeCameraDeviceOrientationInput.ts"); _node__WEBPACK_IMPORTED_MODULE_3__["Node"].AddNodeConstructor("DeviceOrientationCamera", function (name, scene) { return function () { return new DeviceOrientationCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), scene); }; }); // We're mainly based on the logic defined into the FreeCamera code /** * This is a camera specifically designed to react to device orientation events such as a modern mobile device * being tilted forward or back and left or right. */ var DeviceOrientationCamera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DeviceOrientationCamera, _super); /** * Creates a new device orientation camera * @param name The name of the camera * @param position The start position camera * @param scene The scene the camera belongs to */ function DeviceOrientationCamera(name, position, scene) { var _this = _super.call(this, name, position, scene) || this; _this._tmpDragQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"](); /** * Disabled pointer input on first orientation sensor update (Default: true) */ _this.disablePointerInputWhenUsingDeviceOrientation = true; _this._dragFactor = 0; _this._quaternionCache = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"](); _this.inputs.addDeviceOrientation(); // When the orientation sensor fires it's first event, disable mouse input if (_this.inputs._deviceOrientationInput) { _this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce(function () { if (_this.disablePointerInputWhenUsingDeviceOrientation) { if (_this.inputs._mouseInput) { _this.inputs._mouseInput._allowCameraRotation = false; _this.inputs._mouseInput.onPointerMovedObservable.add(function (e) { if (_this._dragFactor != 0) { if (!_this._initialQuaternion) { _this._initialQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"](); } // Rotate the initial space around the y axis to allow users to "turn around" via touch/mouse _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"].FromEulerAnglesToRef(0, e.offsetX * _this._dragFactor, 0, _this._tmpDragQuaternion); _this._initialQuaternion.multiplyToRef(_this._tmpDragQuaternion, _this._initialQuaternion); } }); } } }); } return _this; } /** * Enabled turning on the y axis when the orientation sensor is active * @param dragFactor the factor that controls the turn speed (default: 1/300) */ DeviceOrientationCamera.prototype.enableHorizontalDragging = function (dragFactor) { if (dragFactor === void 0) { dragFactor = 1 / 300; } this._dragFactor = dragFactor; }; /** * Gets the current instance class name ("DeviceOrientationCamera"). * This helps avoiding instanceof at run time. * @returns the class name */ DeviceOrientationCamera.prototype.getClassName = function () { return "DeviceOrientationCamera"; }; /** * @hidden * Checks and applies the current values of the inputs to the camera. (Internal use only) */ DeviceOrientationCamera.prototype._checkInputs = function () { _super.prototype._checkInputs.call(this); this._quaternionCache.copyFrom(this.rotationQuaternion); if (this._initialQuaternion) { this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion); } }; /** * Reset the camera to its default orientation on the specified axis only. * @param axis The axis to reset */ DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) { var _this = this; if (axis === void 0) { axis = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Axis"].Y; } //can only work if this camera has a rotation quaternion already. if (!this.rotationQuaternion) { return; } if (!this._initialQuaternion) { this._initialQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"](); } this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion); ['x', 'y', 'z'].forEach(function (axisName) { if (!axis[axisName]) { _this._initialQuaternion[axisName] = 0; } else { _this._initialQuaternion[axisName] *= -1; } }); this._initialQuaternion.normalize(); //force rotation update this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion); }; return DeviceOrientationCamera; }(_freeCamera__WEBPACK_IMPORTED_MODULE_1__["FreeCamera"])); /***/ }), /***/ "./Cameras/flyCamera.ts": /*!******************************!*\ !*** ./Cameras/flyCamera.ts ***! \******************************/ /*! exports provided: FlyCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FlyCamera", function() { return FlyCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); /* harmony import */ var _targetCamera__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./targetCamera */ "./Cameras/targetCamera.ts"); /* harmony import */ var _flyCameraInputsManager__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./flyCameraInputsManager */ "./Cameras/flyCameraInputsManager.ts"); /** * This is a flying camera, designed for 3D movement and rotation in all directions, * such as in a 3D Space Shooter or a Flight Simulator. */ var FlyCamera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FlyCamera, _super); /** * Instantiates a FlyCamera. * This is a flying camera, designed for 3D movement and rotation in all directions, * such as in a 3D Space Shooter or a Flight Simulator. * @param name Define the name of the camera in the scene. * @param position Define the starting position of the camera in the scene. * @param scene Define the scene the camera belongs to. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active, if no other camera has been defined as active. */ function FlyCamera(name, position, scene, setActiveOnSceneIfNoneActive) { if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; } var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this; /** * Define the collision ellipsoid of the camera. * This is helpful for simulating a camera body, like a player's body. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera */ _this.ellipsoid = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](1, 1, 1); /** * Define an offset for the position of the ellipsoid around the camera. * This can be helpful if the camera is attached away from the player's body center, * such as at its head. */ _this.ellipsoidOffset = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0, 0, 0); /** * Enable or disable collisions of the camera with the rest of the scene objects. */ _this.checkCollisions = false; /** * Enable or disable gravity on the camera. */ _this.applyGravity = false; /** * Define the current direction the camera is moving to. */ _this.cameraDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); /** * Track Roll to maintain the wanted Rolling when looking around. */ _this._trackRoll = 0; /** * Slowly correct the Roll to its original value after a Pitch+Yaw rotation. */ _this.rollCorrect = 100; /** * Mimic a banked turn, Rolling the camera when Yawing. * It's recommended to use rollCorrect = 10 for faster banking correction. */ _this.bankedTurn = false; /** * Limit in radians for how much Roll banking will add. (Default: 90°) */ _this.bankedTurnLimit = Math.PI / 2; /** * Value of 0 disables the banked Roll. * Value of 1 is equal to the Yaw angle in radians. */ _this.bankedTurnMultiplier = 1; _this._needMoveForGravity = false; _this._oldPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); _this._diffPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); _this._newPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); // Collisions. _this._collisionMask = -1; /** @hidden */ _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) { if (collidedMesh === void 0) { collidedMesh = null; } var updatePosition = function (newPos) { _this._newPosition.copyFrom(newPos); _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition); if (_this._diffPosition.length() > _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].CollisionsEpsilon) { _this.position.addInPlace(_this._diffPosition); if (_this.onCollide && collidedMesh) { _this.onCollide(collidedMesh); } } }; updatePosition(newPosition); }; _this.inputs = new _flyCameraInputsManager__WEBPACK_IMPORTED_MODULE_5__["FlyCameraInputsManager"](_this); _this.inputs.addKeyboard().addMouse(); return _this; } Object.defineProperty(FlyCamera.prototype, "angularSensibility", { /** * Gets the input sensibility for mouse input. * Higher values reduce sensitivity. */ get: function () { var mouse = this.inputs.attached["mouse"]; if (mouse) { return mouse.angularSensibility; } return 0; }, /** * Sets the input sensibility for a mouse input. * Higher values reduce sensitivity. */ set: function (value) { var mouse = this.inputs.attached["mouse"]; if (mouse) { mouse.angularSensibility = value; } }, enumerable: true, configurable: true }); Object.defineProperty(FlyCamera.prototype, "keysForward", { /** * Get the keys for camera movement forward. */ get: function () { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { return keyboard.keysForward; } return []; }, /** * Set the keys for camera movement forward. */ set: function (value) { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { keyboard.keysForward = value; } }, enumerable: true, configurable: true }); Object.defineProperty(FlyCamera.prototype, "keysBackward", { /** * Get the keys for camera movement backward. */ get: function () { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { return keyboard.keysBackward; } return []; }, set: function (value) { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { keyboard.keysBackward = value; } }, enumerable: true, configurable: true }); Object.defineProperty(FlyCamera.prototype, "keysUp", { /** * Get the keys for camera movement up. */ get: function () { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { return keyboard.keysUp; } return []; }, /** * Set the keys for camera movement up. */ set: function (value) { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { keyboard.keysUp = value; } }, enumerable: true, configurable: true }); Object.defineProperty(FlyCamera.prototype, "keysDown", { /** * Get the keys for camera movement down. */ get: function () { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { return keyboard.keysDown; } return []; }, /** * Set the keys for camera movement down. */ set: function (value) { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { keyboard.keysDown = value; } }, enumerable: true, configurable: true }); Object.defineProperty(FlyCamera.prototype, "keysLeft", { /** * Get the keys for camera movement left. */ get: function () { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { return keyboard.keysLeft; } return []; }, /** * Set the keys for camera movement left. */ set: function (value) { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { keyboard.keysLeft = value; } }, enumerable: true, configurable: true }); Object.defineProperty(FlyCamera.prototype, "keysRight", { /** * Set the keys for camera movement right. */ get: function () { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { return keyboard.keysRight; } return []; }, /** * Set the keys for camera movement right. */ set: function (value) { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { keyboard.keysRight = value; } }, enumerable: true, configurable: true }); /** * Attach a control to the HTML DOM element. * @param element Defines the element that listens to the input events. * @param noPreventDefault Defines whether events caught by the controls should call preventdefault(). https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault */ FlyCamera.prototype.attachControl = function (element, noPreventDefault) { this.inputs.attachElement(element, noPreventDefault); }; /** * Detach a control from the HTML DOM element. * The camera will stop reacting to that input. * @param element Defines the element that listens to the input events. */ FlyCamera.prototype.detachControl = function (element) { this.inputs.detachElement(element); this.cameraDirection = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0, 0, 0); }; Object.defineProperty(FlyCamera.prototype, "collisionMask", { /** * Get the mask that the camera ignores in collision events. */ get: function () { return this._collisionMask; }, /** * Set the mask that the camera ignores in collision events. */ set: function (mask) { this._collisionMask = !isNaN(mask) ? mask : -1; }, enumerable: true, configurable: true }); /** @hidden */ FlyCamera.prototype._collideWithWorld = function (displacement) { var globalPosition; if (this.parent) { globalPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinates(this.position, this.parent.getWorldMatrix()); } else { globalPosition = this.position; } globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition); this._oldPosition.addInPlace(this.ellipsoidOffset); var coordinator = this.getScene().collisionCoordinator; if (!this._collider) { this._collider = coordinator.createCollider(); } this._collider._radius = this.ellipsoid; this._collider.collisionMask = this._collisionMask; // No need for clone, as long as gravity is not on. var actualDisplacement = displacement; // Add gravity to direction to prevent dual-collision checking. if (this.applyGravity) { // This prevents mending with cameraDirection, a global variable of the fly camera class. actualDisplacement = displacement.add(this.getScene().gravity); } coordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId); }; /** @hidden */ FlyCamera.prototype._checkInputs = function () { if (!this._localDirection) { this._localDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); this._transformedDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); } this.inputs.checkInputs(); _super.prototype._checkInputs.call(this); }; /** @hidden */ FlyCamera.prototype._decideIfNeedsToMove = function () { return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0; }; /** @hidden */ FlyCamera.prototype._updatePosition = function () { if (this.checkCollisions && this.getScene().collisionsEnabled) { this._collideWithWorld(this.cameraDirection); } else { _super.prototype._updatePosition.call(this); } }; /** * Restore the Roll to its target value at the rate specified. * @param rate - Higher means slower restoring. * @hidden */ FlyCamera.prototype.restoreRoll = function (rate) { var limit = this._trackRoll; // Target Roll. var z = this.rotation.z; // Current Roll. var delta = limit - z; // Difference in Roll. var minRad = 0.001; // Tenth of a radian is a barely noticable difference. // If the difference is noticable, restore the Roll. if (Math.abs(delta) >= minRad) { // Change Z rotation towards the target Roll. this.rotation.z += delta / rate; // Match when near enough. if (Math.abs(limit - this.rotation.z) <= minRad) { this.rotation.z = limit; } } }; /** * Destroy the camera and release the current resources held by it. */ FlyCamera.prototype.dispose = function () { this.inputs.clear(); _super.prototype.dispose.call(this); }; /** * Get the current object class name. * @returns the class name. */ FlyCamera.prototype.getClassName = function () { return "FlyCamera"; }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])() ], FlyCamera.prototype, "ellipsoid", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])() ], FlyCamera.prototype, "ellipsoidOffset", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FlyCamera.prototype, "checkCollisions", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FlyCamera.prototype, "applyGravity", void 0); return FlyCamera; }(_targetCamera__WEBPACK_IMPORTED_MODULE_4__["TargetCamera"])); /***/ }), /***/ "./Cameras/flyCameraInputsManager.ts": /*!*******************************************!*\ !*** ./Cameras/flyCameraInputsManager.ts ***! \*******************************************/ /*! exports provided: FlyCameraInputsManager */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FlyCameraInputsManager", function() { return FlyCameraInputsManager; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Cameras_Inputs_flyCameraMouseInput__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Cameras/Inputs/flyCameraMouseInput */ "./Cameras/Inputs/flyCameraMouseInput.ts"); /* harmony import */ var _Cameras_Inputs_flyCameraKeyboardInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Cameras/Inputs/flyCameraKeyboardInput */ "./Cameras/Inputs/flyCameraKeyboardInput.ts"); /** * Default Inputs manager for the FlyCamera. * It groups all the default supported inputs for ease of use. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FlyCameraInputsManager = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FlyCameraInputsManager, _super); /** * Instantiates a new FlyCameraInputsManager. * @param camera Defines the camera the inputs belong to. */ function FlyCameraInputsManager(camera) { return _super.call(this, camera) || this; } /** * Add keyboard input support to the input manager. * @returns the new FlyCameraKeyboardMoveInput(). */ FlyCameraInputsManager.prototype.addKeyboard = function () { this.add(new _Cameras_Inputs_flyCameraKeyboardInput__WEBPACK_IMPORTED_MODULE_3__["FlyCameraKeyboardInput"]()); return this; }; /** * Add mouse input support to the input manager. * @param touchEnabled Enable touch screen support. * @returns the new FlyCameraMouseInput(). */ FlyCameraInputsManager.prototype.addMouse = function (touchEnabled) { if (touchEnabled === void 0) { touchEnabled = true; } this.add(new _Cameras_Inputs_flyCameraMouseInput__WEBPACK_IMPORTED_MODULE_2__["FlyCameraMouseInput"](touchEnabled)); return this; }; return FlyCameraInputsManager; }(_cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__["CameraInputsManager"])); /***/ }), /***/ "./Cameras/followCamera.ts": /*!*********************************!*\ !*** ./Cameras/followCamera.ts ***! \*********************************/ /*! exports provided: FollowCamera, ArcFollowCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FollowCamera", function() { return FollowCamera; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcFollowCamera", function() { return ArcFollowCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _targetCamera__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./targetCamera */ "./Cameras/targetCamera.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../node */ "./node.ts"); /* harmony import */ var _followCameraInputsManager__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./followCameraInputsManager */ "./Cameras/followCameraInputsManager.ts"); _node__WEBPACK_IMPORTED_MODULE_5__["Node"].AddNodeConstructor("FollowCamera", function (name, scene) { return function () { return new FollowCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(), scene); }; }); _node__WEBPACK_IMPORTED_MODULE_5__["Node"].AddNodeConstructor("ArcFollowCamera", function (name, scene) { return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); }; }); /** * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and * an arc rotate version arcFollowCamera are available. * @see http://doc.babylonjs.com/features/cameras#follow-camera */ var FollowCamera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FollowCamera, _super); /** * Instantiates the follow camera. * @see http://doc.babylonjs.com/features/cameras#follow-camera * @param name Define the name of the camera in the scene * @param position Define the position of the camera * @param scene Define the scene the camera belong to * @param lockedTarget Define the target of the camera */ function FollowCamera(name, position, scene, lockedTarget) { if (lockedTarget === void 0) { lockedTarget = null; } var _this = _super.call(this, name, position, scene) || this; /** * Distance the follow camera should follow an object at */ _this.radius = 12; /** * Minimum allowed distance of the camera to the axis of rotation * (The camera can not get closer). * This can help limiting how the Camera is able to move in the scene. */ _this.lowerRadiusLimit = null; /** * Maximum allowed distance of the camera to the axis of rotation * (The camera can not get further). * This can help limiting how the Camera is able to move in the scene. */ _this.upperRadiusLimit = null; /** * Define a rotation offset between the camera and the object it follows */ _this.rotationOffset = 0; /** * Minimum allowed angle to camera position relative to target object. * This can help limiting how the Camera is able to move in the scene. */ _this.lowerRotationOffsetLimit = null; /** * Maximum allowed angle to camera position relative to target object. * This can help limiting how the Camera is able to move in the scene. */ _this.upperRotationOffsetLimit = null; /** * Define a height offset between the camera and the object it follows. * It can help following an object from the top (like a car chaing a plane) */ _this.heightOffset = 4; /** * Minimum allowed height of camera position relative to target object. * This can help limiting how the Camera is able to move in the scene. */ _this.lowerHeightOffsetLimit = null; /** * Maximum allowed height of camera position relative to target object. * This can help limiting how the Camera is able to move in the scene. */ _this.upperHeightOffsetLimit = null; /** * Define how fast the camera can accelerate to follow it s target. */ _this.cameraAcceleration = 0.05; /** * Define the speed limit of the camera following an object. */ _this.maxCameraSpeed = 20; _this.lockedTarget = lockedTarget; _this.inputs = new _followCameraInputsManager__WEBPACK_IMPORTED_MODULE_6__["FollowCameraInputsManager"](_this); _this.inputs.addKeyboard().addMouseWheel().addPointers(); return _this; // Uncomment the following line when the relevant handlers have been implemented. // this.inputs.addKeyboard().addMouseWheel().addPointers().addVRDeviceOrientation(); } FollowCamera.prototype._follow = function (cameraTarget) { if (!cameraTarget) { return; } var yRotation; if (cameraTarget.rotationQuaternion) { var rotMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"](); cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix); yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]); } else { yRotation = cameraTarget.rotation.y; } var radians = _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].ToRadians(this.rotationOffset) + yRotation; var targetPosition = cameraTarget.getAbsolutePosition(); var targetX = targetPosition.x + Math.sin(radians) * this.radius; var targetZ = targetPosition.z + Math.cos(radians) * this.radius; var dx = targetX - this.position.x; var dy = (targetPosition.y + this.heightOffset) - this.position.y; var dz = (targetZ) - this.position.z; var vx = dx * this.cameraAcceleration * 2; //this is set to .05 var vy = dy * this.cameraAcceleration; var vz = dz * this.cameraAcceleration * 2; if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) { vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed; } if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) { vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed; } if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) { vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed; } this.position = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"](this.position.x + vx, this.position.y + vy, this.position.z + vz); this.setTarget(targetPosition); }; /** * Attached controls to the current camera. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ FollowCamera.prototype.attachControl = function (element, noPreventDefault) { this.inputs.attachElement(element, noPreventDefault); this._reset = function () { }; }; /** * Detach the current controls from the camera. * The camera will stop reacting to inputs. * @param element Defines the element to stop listening the inputs from */ FollowCamera.prototype.detachControl = function (element) { this.inputs.detachElement(element); if (this._reset) { this._reset(); } }; /** @hidden */ FollowCamera.prototype._checkInputs = function () { this.inputs.checkInputs(); this._checkLimits(); _super.prototype._checkInputs.call(this); if (this.lockedTarget) { this._follow(this.lockedTarget); } }; FollowCamera.prototype._checkLimits = function () { if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) { this.radius = this.lowerRadiusLimit; } if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) { this.radius = this.upperRadiusLimit; } if (this.lowerHeightOffsetLimit !== null && this.heightOffset < this.lowerHeightOffsetLimit) { this.heightOffset = this.lowerHeightOffsetLimit; } if (this.upperHeightOffsetLimit !== null && this.heightOffset > this.upperHeightOffsetLimit) { this.heightOffset = this.upperHeightOffsetLimit; } if (this.lowerRotationOffsetLimit !== null && this.rotationOffset < this.lowerRotationOffsetLimit) { this.rotationOffset = this.lowerRotationOffsetLimit; } if (this.upperRotationOffsetLimit !== null && this.rotationOffset > this.upperRotationOffsetLimit) { this.rotationOffset = this.upperRotationOffsetLimit; } }; /** * Gets the camera class name. * @returns the class name */ FollowCamera.prototype.getClassName = function () { return "FollowCamera"; }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCamera.prototype, "radius", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCamera.prototype, "lowerRadiusLimit", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCamera.prototype, "upperRadiusLimit", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCamera.prototype, "rotationOffset", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCamera.prototype, "lowerRotationOffsetLimit", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCamera.prototype, "upperRotationOffsetLimit", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCamera.prototype, "heightOffset", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCamera.prototype, "lowerHeightOffsetLimit", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCamera.prototype, "upperHeightOffsetLimit", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCamera.prototype, "cameraAcceleration", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCamera.prototype, "maxCameraSpeed", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsMeshReference"])("lockedTargetId") ], FollowCamera.prototype, "lockedTarget", void 0); return FollowCamera; }(_targetCamera__WEBPACK_IMPORTED_MODULE_3__["TargetCamera"])); /** * Arc Rotate version of the follow camera. * It still follows a Defined mesh but in an Arc Rotate Camera fashion. * @see http://doc.babylonjs.com/features/cameras#follow-camera */ var ArcFollowCamera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ArcFollowCamera, _super); /** * Instantiates a new ArcFollowCamera * @see http://doc.babylonjs.com/features/cameras#follow-camera * @param name Define the name of the camera * @param alpha Define the rotation angle of the camera around the logitudinal axis * @param beta Define the rotation angle of the camera around the elevation axis * @param radius Define the radius of the camera from its target point * @param target Define the target of the camera * @param scene Define the scene the camera belongs to */ function ArcFollowCamera(name, /** The longitudinal angle of the camera */ alpha, /** The latitudinal angle of the camera */ beta, /** The radius of the camera from its target */ radius, /** Define the camera target (the messh it should follow) */ target, scene) { var _this = _super.call(this, name, _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(), scene) || this; _this.alpha = alpha; _this.beta = beta; _this.radius = radius; _this.target = target; _this._cartesianCoordinates = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(); _this._follow(); return _this; } ArcFollowCamera.prototype._follow = function () { if (!this.target) { return; } this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta); this._cartesianCoordinates.y = this.radius * Math.sin(this.beta); this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta); var targetPosition = this.target.getAbsolutePosition(); this.position = targetPosition.add(this._cartesianCoordinates); this.setTarget(targetPosition); }; /** @hidden */ ArcFollowCamera.prototype._checkInputs = function () { _super.prototype._checkInputs.call(this); this._follow(); }; /** * Returns the class name of the object. * It is mostly used internally for serialization purposes. */ ArcFollowCamera.prototype.getClassName = function () { return "ArcFollowCamera"; }; return ArcFollowCamera; }(_targetCamera__WEBPACK_IMPORTED_MODULE_3__["TargetCamera"])); /***/ }), /***/ "./Cameras/followCameraInputsManager.ts": /*!**********************************************!*\ !*** ./Cameras/followCameraInputsManager.ts ***! \**********************************************/ /*! exports provided: FollowCameraInputsManager */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FollowCameraInputsManager", function() { return FollowCameraInputsManager; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Inputs_followCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Inputs/followCameraKeyboardMoveInput */ "./Cameras/Inputs/followCameraKeyboardMoveInput.ts"); /* harmony import */ var _Inputs_followCameraMouseWheelInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Inputs/followCameraMouseWheelInput */ "./Cameras/Inputs/followCameraMouseWheelInput.ts"); /* harmony import */ var _Inputs_followCameraPointersInput__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Inputs/followCameraPointersInput */ "./Cameras/Inputs/followCameraPointersInput.ts"); /** * Default Inputs manager for the FollowCamera. * It groups all the default supported inputs for ease of use. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FollowCameraInputsManager = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FollowCameraInputsManager, _super); /** * Instantiates a new FollowCameraInputsManager. * @param camera Defines the camera the inputs belong to */ function FollowCameraInputsManager(camera) { return _super.call(this, camera) || this; } /** * Add keyboard input support to the input manager. * @returns the current input manager */ FollowCameraInputsManager.prototype.addKeyboard = function () { this.add(new _Inputs_followCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_2__["FollowCameraKeyboardMoveInput"]()); return this; }; /** * Add mouse wheel input support to the input manager. * @returns the current input manager */ FollowCameraInputsManager.prototype.addMouseWheel = function () { this.add(new _Inputs_followCameraMouseWheelInput__WEBPACK_IMPORTED_MODULE_3__["FollowCameraMouseWheelInput"]()); return this; }; /** * Add pointers input support to the input manager. * @returns the current input manager */ FollowCameraInputsManager.prototype.addPointers = function () { this.add(new _Inputs_followCameraPointersInput__WEBPACK_IMPORTED_MODULE_4__["FollowCameraPointersInput"]()); return this; }; /** * Add orientation input support to the input manager. * @returns the current input manager */ FollowCameraInputsManager.prototype.addVRDeviceOrientation = function () { console.warn("DeviceOrientation support not yet implemented for FollowCamera."); return this; }; return FollowCameraInputsManager; }(_cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__["CameraInputsManager"])); /***/ }), /***/ "./Cameras/freeCamera.ts": /*!*******************************!*\ !*** ./Cameras/freeCamera.ts ***! \*******************************/ /*! exports provided: FreeCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FreeCamera", function() { return FreeCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); /* harmony import */ var _targetCamera__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./targetCamera */ "./Cameras/targetCamera.ts"); /* harmony import */ var _freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./freeCameraInputsManager */ "./Cameras/freeCameraInputsManager.ts"); /** * This represents a free type of camera. It can be useful in First Person Shooter game for instance. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad. * @see http://doc.babylonjs.com/features/cameras#universal-camera */ var FreeCamera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FreeCamera, _super); /** * Instantiates a Free Camera. * This represents a free type of camera. It can be useful in First Person Shooter game for instance. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera. * @see http://doc.babylonjs.com/features/cameras#universal-camera * @param name Define the name of the camera in the scene * @param position Define the start position of the camera in the scene * @param scene Define the scene the camera belongs to * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined */ function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) { if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; } var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this; /** * Define the collision ellipsoid of the camera. * This is helpful to simulate a camera body like the player body around the camera * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera */ _this.ellipsoid = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0.5, 1, 0.5); /** * Define an offset for the position of the ellipsoid around the camera. * This can be helpful to determine the center of the body near the gravity center of the body * instead of its head. */ _this.ellipsoidOffset = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0, 0, 0); /** * Enable or disable collisions of the camera with the rest of the scene objects. */ _this.checkCollisions = false; /** * Enable or disable gravity on the camera. */ _this.applyGravity = false; _this._needMoveForGravity = false; _this._oldPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); _this._diffPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); _this._newPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); // Collisions _this._collisionMask = -1; _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) { if (collidedMesh === void 0) { collidedMesh = null; } var updatePosition = function (newPos) { _this._newPosition.copyFrom(newPos); _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition); if (_this._diffPosition.length() > _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].CollisionsEpsilon) { _this.position.addInPlace(_this._diffPosition); if (_this.onCollide && collidedMesh) { _this.onCollide(collidedMesh); } } }; updatePosition(newPosition); }; _this.inputs = new _freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_5__["FreeCameraInputsManager"](_this); _this.inputs.addKeyboard().addMouse(); return _this; } Object.defineProperty(FreeCamera.prototype, "angularSensibility", { /** * Gets the input sensibility for a mouse input. (default is 2000.0) * Higher values reduce sensitivity. */ get: function () { var mouse = this.inputs.attached["mouse"]; if (mouse) { return mouse.angularSensibility; } return 0; }, /** * Sets the input sensibility for a mouse input. (default is 2000.0) * Higher values reduce sensitivity. */ set: function (value) { var mouse = this.inputs.attached["mouse"]; if (mouse) { mouse.angularSensibility = value; } }, enumerable: true, configurable: true }); Object.defineProperty(FreeCamera.prototype, "keysUp", { /** * Gets or Set the list of keyboard keys used to control the forward move of the camera. */ get: function () { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { return keyboard.keysUp; } return []; }, set: function (value) { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { keyboard.keysUp = value; } }, enumerable: true, configurable: true }); Object.defineProperty(FreeCamera.prototype, "keysDown", { /** * Gets or Set the list of keyboard keys used to control the backward move of the camera. */ get: function () { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { return keyboard.keysDown; } return []; }, set: function (value) { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { keyboard.keysDown = value; } }, enumerable: true, configurable: true }); Object.defineProperty(FreeCamera.prototype, "keysLeft", { /** * Gets or Set the list of keyboard keys used to control the left strafe move of the camera. */ get: function () { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { return keyboard.keysLeft; } return []; }, set: function (value) { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { keyboard.keysLeft = value; } }, enumerable: true, configurable: true }); Object.defineProperty(FreeCamera.prototype, "keysRight", { /** * Gets or Set the list of keyboard keys used to control the right strafe move of the camera. */ get: function () { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { return keyboard.keysRight; } return []; }, set: function (value) { var keyboard = this.inputs.attached["keyboard"]; if (keyboard) { keyboard.keysRight = value; } }, enumerable: true, configurable: true }); /** * Attached controls to the current camera. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ FreeCamera.prototype.attachControl = function (element, noPreventDefault) { this.inputs.attachElement(element, noPreventDefault); }; /** * Detach the current controls from the camera. * The camera will stop reacting to inputs. * @param element Defines the element to stop listening the inputs from */ FreeCamera.prototype.detachControl = function (element) { this.inputs.detachElement(element); this.cameraDirection = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0, 0, 0); this.cameraRotation = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector2"](0, 0); }; Object.defineProperty(FreeCamera.prototype, "collisionMask", { /** * Define a collision mask to limit the list of object the camera can collide with */ get: function () { return this._collisionMask; }, set: function (mask) { this._collisionMask = !isNaN(mask) ? mask : -1; }, enumerable: true, configurable: true }); /** @hidden */ FreeCamera.prototype._collideWithWorld = function (displacement) { var globalPosition; if (this.parent) { globalPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinates(this.position, this.parent.getWorldMatrix()); } else { globalPosition = this.position; } globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition); this._oldPosition.addInPlace(this.ellipsoidOffset); var coordinator = this.getScene().collisionCoordinator; if (!this._collider) { this._collider = coordinator.createCollider(); } this._collider._radius = this.ellipsoid; this._collider.collisionMask = this._collisionMask; //no need for clone, as long as gravity is not on. var actualDisplacement = displacement; //add gravity to the direction to prevent the dual-collision checking if (this.applyGravity) { //this prevents mending with cameraDirection, a global variable of the free camera class. actualDisplacement = displacement.add(this.getScene().gravity); } coordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId); }; /** @hidden */ FreeCamera.prototype._checkInputs = function () { if (!this._localDirection) { this._localDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); this._transformedDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); } this.inputs.checkInputs(); _super.prototype._checkInputs.call(this); }; /** @hidden */ FreeCamera.prototype._decideIfNeedsToMove = function () { return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0; }; /** @hidden */ FreeCamera.prototype._updatePosition = function () { if (this.checkCollisions && this.getScene().collisionsEnabled) { this._collideWithWorld(this.cameraDirection); } else { _super.prototype._updatePosition.call(this); } }; /** * Destroy the camera and release the current resources hold by it. */ FreeCamera.prototype.dispose = function () { this.inputs.clear(); _super.prototype.dispose.call(this); }; /** * Gets the current object class name. * @return the class name */ FreeCamera.prototype.getClassName = function () { return "FreeCamera"; }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])() ], FreeCamera.prototype, "ellipsoid", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])() ], FreeCamera.prototype, "ellipsoidOffset", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FreeCamera.prototype, "checkCollisions", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FreeCamera.prototype, "applyGravity", void 0); return FreeCamera; }(_targetCamera__WEBPACK_IMPORTED_MODULE_4__["TargetCamera"])); /***/ }), /***/ "./Cameras/freeCameraInputsManager.ts": /*!********************************************!*\ !*** ./Cameras/freeCameraInputsManager.ts ***! \********************************************/ /*! exports provided: FreeCameraInputsManager */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FreeCameraInputsManager", function() { return FreeCameraInputsManager; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Cameras_Inputs_freeCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Cameras/Inputs/freeCameraKeyboardMoveInput */ "./Cameras/Inputs/freeCameraKeyboardMoveInput.ts"); /* harmony import */ var _Cameras_Inputs_freeCameraMouseInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Cameras/Inputs/freeCameraMouseInput */ "./Cameras/Inputs/freeCameraMouseInput.ts"); /* harmony import */ var _Cameras_Inputs_freeCameraTouchInput__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Cameras/Inputs/freeCameraTouchInput */ "./Cameras/Inputs/freeCameraTouchInput.ts"); /** * Default Inputs manager for the FreeCamera. * It groups all the default supported inputs for ease of use. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FreeCameraInputsManager = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](FreeCameraInputsManager, _super); /** * Instantiates a new FreeCameraInputsManager. * @param camera Defines the camera the inputs belong to */ function FreeCameraInputsManager(camera) { var _this = _super.call(this, camera) || this; /** * @hidden */ _this._keyboardInput = null; /** * @hidden */ _this._mouseInput = null; return _this; } /** * Add keyboard input support to the input manager. * @returns the current input manager */ FreeCameraInputsManager.prototype.addKeyboard = function () { this.add(new _Cameras_Inputs_freeCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_2__["FreeCameraKeyboardMoveInput"]()); return this; }; /** * Add mouse input support to the input manager. * @param touchEnabled if the FreeCameraMouseInput should support touch (default: true) * @returns the current input manager */ FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) { if (touchEnabled === void 0) { touchEnabled = true; } if (!this._mouseInput) { this._mouseInput = new _Cameras_Inputs_freeCameraMouseInput__WEBPACK_IMPORTED_MODULE_3__["FreeCameraMouseInput"](touchEnabled); this.add(this._mouseInput); } return this; }; /** * Removes the mouse input support from the manager * @returns the current input manager */ FreeCameraInputsManager.prototype.removeMouse = function () { if (this._mouseInput) { this.remove(this._mouseInput); } return this; }; /** * Add touch input support to the input manager. * @returns the current input manager */ FreeCameraInputsManager.prototype.addTouch = function () { this.add(new _Cameras_Inputs_freeCameraTouchInput__WEBPACK_IMPORTED_MODULE_4__["FreeCameraTouchInput"]()); return this; }; return FreeCameraInputsManager; }(_cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__["CameraInputsManager"])); /***/ }), /***/ "./Cameras/gamepadCamera.ts": /*!**********************************!*\ !*** ./Cameras/gamepadCamera.ts ***! \**********************************/ /*! exports provided: GamepadCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GamepadCamera", function() { return GamepadCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _universalCamera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./universalCamera */ "./Cameras/universalCamera.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts"); _node__WEBPACK_IMPORTED_MODULE_3__["Node"].AddNodeConstructor("GamepadCamera", function (name, scene) { return function () { return new GamepadCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), scene); }; }); /** * This represents a FPS type of camera. This is only here for back compat purpose. * Please use the UniversalCamera instead as both are identical. * @see http://doc.babylonjs.com/features/cameras#universal-camera */ var GamepadCamera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GamepadCamera, _super); /** * Instantiates a new Gamepad Camera * This represents a FPS type of camera. This is only here for back compat purpose. * Please use the UniversalCamera instead as both are identical. * @see http://doc.babylonjs.com/features/cameras#universal-camera * @param name Define the name of the camera in the scene * @param position Define the start position of the camera in the scene * @param scene Define the scene the camera belongs to */ function GamepadCamera(name, position, scene) { return _super.call(this, name, position, scene) || this; } /** * Gets the current object class name. * @return the class name */ GamepadCamera.prototype.getClassName = function () { return "GamepadCamera"; }; return GamepadCamera; }(_universalCamera__WEBPACK_IMPORTED_MODULE_1__["UniversalCamera"])); /***/ }), /***/ "./Cameras/index.ts": /*!**************************!*\ !*** ./Cameras/index.ts ***! \**************************/ /*! exports provided: CameraInputTypes, CameraInputsManager, Camera, TargetCamera, FreeCamera, FreeCameraInputsManager, TouchCamera, ArcRotateCamera, ArcRotateCameraInputsManager, DeviceOrientationCamera, FlyCamera, FlyCameraInputsManager, FollowCamera, ArcFollowCamera, GamepadCamera, UniversalCamera, VirtualJoysticksCamera, ArcRotateCameraGamepadInput, ArcRotateCameraKeyboardMoveInput, ArcRotateCameraMouseWheelInput, ArcRotateCameraPointersInput, ArcRotateCameraVRDeviceOrientationInput, FlyCameraKeyboardInput, FlyCameraMouseInput, FollowCameraKeyboardMoveInput, FollowCameraMouseWheelInput, FollowCameraPointersInput, FreeCameraDeviceOrientationInput, FreeCameraGamepadInput, FreeCameraKeyboardMoveInput, FreeCameraMouseInput, FreeCameraTouchInput, FreeCameraVirtualJoystickInput, AnaglyphArcRotateCamera, AnaglyphFreeCamera, AnaglyphGamepadCamera, AnaglyphUniversalCamera, StereoscopicArcRotateCamera, StereoscopicFreeCamera, StereoscopicGamepadCamera, StereoscopicUniversalCamera, VRCameraMetrics, VRDeviceOrientationArcRotateCamera, VRDeviceOrientationFreeCamera, VRDeviceOrientationGamepadCamera, OnAfterEnteringVRObservableEvent, VRExperienceHelper, WebVRFreeCamera, WebXRCamera, WebXREnterExitUIButton, WebXREnterExitUIOptions, WebXREnterExitUI, WebXRState, WebXRExperienceHelper, WebXRController, WebXRInput, WebXRManagedOutputCanvas, WebXRSessionManager */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _Inputs_index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Inputs/index */ "./Cameras/Inputs/index.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraGamepadInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraGamepadInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraKeyboardMoveInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraKeyboardMoveInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraMouseWheelInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraMouseWheelInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraPointersInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraPointersInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraVRDeviceOrientationInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraVRDeviceOrientationInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCameraKeyboardInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FlyCameraKeyboardInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCameraMouseInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FlyCameraMouseInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraKeyboardMoveInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FollowCameraKeyboardMoveInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraMouseWheelInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FollowCameraMouseWheelInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraPointersInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FollowCameraPointersInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraDeviceOrientationInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraDeviceOrientationInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraGamepadInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraGamepadInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraKeyboardMoveInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraKeyboardMoveInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraMouseInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraMouseInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraTouchInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraTouchInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraVirtualJoystickInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraVirtualJoystickInput"]; }); /* harmony import */ var _cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CameraInputTypes", function() { return _cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__["CameraInputTypes"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CameraInputsManager", function() { return _cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__["CameraInputsManager"]; }); /* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./camera */ "./Cameras/camera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Camera", function() { return _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"]; }); /* harmony import */ var _targetCamera__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./targetCamera */ "./Cameras/targetCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TargetCamera", function() { return _targetCamera__WEBPACK_IMPORTED_MODULE_3__["TargetCamera"]; }); /* harmony import */ var _freeCamera__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./freeCamera */ "./Cameras/freeCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCamera", function() { return _freeCamera__WEBPACK_IMPORTED_MODULE_4__["FreeCamera"]; }); /* harmony import */ var _freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./freeCameraInputsManager */ "./Cameras/freeCameraInputsManager.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraInputsManager", function() { return _freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_5__["FreeCameraInputsManager"]; }); /* harmony import */ var _touchCamera__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./touchCamera */ "./Cameras/touchCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TouchCamera", function() { return _touchCamera__WEBPACK_IMPORTED_MODULE_6__["TouchCamera"]; }); /* harmony import */ var _arcRotateCamera__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./arcRotateCamera */ "./Cameras/arcRotateCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCamera", function() { return _arcRotateCamera__WEBPACK_IMPORTED_MODULE_7__["ArcRotateCamera"]; }); /* harmony import */ var _arcRotateCameraInputsManager__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./arcRotateCameraInputsManager */ "./Cameras/arcRotateCameraInputsManager.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraInputsManager", function() { return _arcRotateCameraInputsManager__WEBPACK_IMPORTED_MODULE_8__["ArcRotateCameraInputsManager"]; }); /* harmony import */ var _deviceOrientationCamera__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./deviceOrientationCamera */ "./Cameras/deviceOrientationCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DeviceOrientationCamera", function() { return _deviceOrientationCamera__WEBPACK_IMPORTED_MODULE_9__["DeviceOrientationCamera"]; }); /* harmony import */ var _flyCamera__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./flyCamera */ "./Cameras/flyCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCamera", function() { return _flyCamera__WEBPACK_IMPORTED_MODULE_10__["FlyCamera"]; }); /* harmony import */ var _flyCameraInputsManager__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./flyCameraInputsManager */ "./Cameras/flyCameraInputsManager.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCameraInputsManager", function() { return _flyCameraInputsManager__WEBPACK_IMPORTED_MODULE_11__["FlyCameraInputsManager"]; }); /* harmony import */ var _followCamera__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./followCamera */ "./Cameras/followCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCamera", function() { return _followCamera__WEBPACK_IMPORTED_MODULE_12__["FollowCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcFollowCamera", function() { return _followCamera__WEBPACK_IMPORTED_MODULE_12__["ArcFollowCamera"]; }); /* harmony import */ var _gamepadCamera__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./gamepadCamera */ "./Cameras/gamepadCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GamepadCamera", function() { return _gamepadCamera__WEBPACK_IMPORTED_MODULE_13__["GamepadCamera"]; }); /* harmony import */ var _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Stereoscopic/index */ "./Cameras/Stereoscopic/index.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphArcRotateCamera", function() { return _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_14__["AnaglyphArcRotateCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphFreeCamera", function() { return _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_14__["AnaglyphFreeCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphGamepadCamera", function() { return _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_14__["AnaglyphGamepadCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphUniversalCamera", function() { return _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_14__["AnaglyphUniversalCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicArcRotateCamera", function() { return _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_14__["StereoscopicArcRotateCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicFreeCamera", function() { return _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_14__["StereoscopicFreeCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicGamepadCamera", function() { return _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_14__["StereoscopicGamepadCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicUniversalCamera", function() { return _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_14__["StereoscopicUniversalCamera"]; }); /* harmony import */ var _universalCamera__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./universalCamera */ "./Cameras/universalCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UniversalCamera", function() { return _universalCamera__WEBPACK_IMPORTED_MODULE_15__["UniversalCamera"]; }); /* harmony import */ var _virtualJoysticksCamera__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./virtualJoysticksCamera */ "./Cameras/virtualJoysticksCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VirtualJoysticksCamera", function() { return _virtualJoysticksCamera__WEBPACK_IMPORTED_MODULE_16__["VirtualJoysticksCamera"]; }); /* harmony import */ var _VR_index__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./VR/index */ "./Cameras/VR/index.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRCameraMetrics", function() { return _VR_index__WEBPACK_IMPORTED_MODULE_17__["VRCameraMetrics"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationArcRotateCamera", function() { return _VR_index__WEBPACK_IMPORTED_MODULE_17__["VRDeviceOrientationArcRotateCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationFreeCamera", function() { return _VR_index__WEBPACK_IMPORTED_MODULE_17__["VRDeviceOrientationFreeCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationGamepadCamera", function() { return _VR_index__WEBPACK_IMPORTED_MODULE_17__["VRDeviceOrientationGamepadCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OnAfterEnteringVRObservableEvent", function() { return _VR_index__WEBPACK_IMPORTED_MODULE_17__["OnAfterEnteringVRObservableEvent"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRExperienceHelper", function() { return _VR_index__WEBPACK_IMPORTED_MODULE_17__["VRExperienceHelper"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebVRFreeCamera", function() { return _VR_index__WEBPACK_IMPORTED_MODULE_17__["WebVRFreeCamera"]; }); /* harmony import */ var _XR_index__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./XR/index */ "./Cameras/XR/index.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRCamera", function() { return _XR_index__WEBPACK_IMPORTED_MODULE_18__["WebXRCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUIButton", function() { return _XR_index__WEBPACK_IMPORTED_MODULE_18__["WebXREnterExitUIButton"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUIOptions", function() { return _XR_index__WEBPACK_IMPORTED_MODULE_18__["WebXREnterExitUIOptions"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUI", function() { return _XR_index__WEBPACK_IMPORTED_MODULE_18__["WebXREnterExitUI"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRState", function() { return _XR_index__WEBPACK_IMPORTED_MODULE_18__["WebXRState"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRExperienceHelper", function() { return _XR_index__WEBPACK_IMPORTED_MODULE_18__["WebXRExperienceHelper"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRController", function() { return _XR_index__WEBPACK_IMPORTED_MODULE_18__["WebXRController"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRInput", function() { return _XR_index__WEBPACK_IMPORTED_MODULE_18__["WebXRInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRManagedOutputCanvas", function() { return _XR_index__WEBPACK_IMPORTED_MODULE_18__["WebXRManagedOutputCanvas"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRSessionManager", function() { return _XR_index__WEBPACK_IMPORTED_MODULE_18__["WebXRSessionManager"]; }); /***/ }), /***/ "./Cameras/targetCamera.ts": /*!*********************************!*\ !*** ./Cameras/targetCamera.ts ***! \*********************************/ /*! exports provided: TargetCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TargetCamera", function() { return TargetCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./camera */ "./Cameras/camera.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /** * A target camera takes a mesh or position as a target and continues to look at it while it moves. * This is the base of the follow, arc rotate cameras and Free camera * @see http://doc.babylonjs.com/features/cameras */ var TargetCamera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TargetCamera, _super); /** * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves. * This is the base of the follow, arc rotate cameras and Free camera * @see http://doc.babylonjs.com/features/cameras * @param name Defines the name of the camera in the scene * @param position Defines the start position of the camera in the scene * @param scene Defines the scene the camera belongs to * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined */ function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) { if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; } var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this; /** * Define the current direction the camera is moving to */ _this.cameraDirection = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); /** * Define the current rotation the camera is rotating to */ _this.cameraRotation = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector2"](0, 0); /** * When set, the up vector of the camera will be updated by the rotation of the camera */ _this.updateUpVectorFromRotation = false; _this._tmpQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); /** * Define the current rotation of the camera */ _this.rotation = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); /** * Define the current speed of the camera */ _this.speed = 2.0; /** * Add cconstraint to the camera to prevent it to move freely in all directions and * around all axis. */ _this.noRotationConstraint = false; /** * Define the current target of the camera as an object or a position. */ _this.lockedTarget = null; /** @hidden */ _this._currentTarget = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); /** @hidden */ _this._initialFocalDistance = 1; /** @hidden */ _this._viewMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Zero(); /** @hidden */ _this._camMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Zero(); /** @hidden */ _this._cameraTransformMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Zero(); /** @hidden */ _this._cameraRotationMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Zero(); /** @hidden */ _this._referencePoint = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 1); /** @hidden */ _this._transformedReferencePoint = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); _this._globalCurrentTarget = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); _this._globalCurrentUpVector = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); _this._defaultUp = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Up(); _this._cachedRotationZ = 0; _this._cachedQuaternionRotationZ = 0; return _this; } /** * Gets the position in front of the camera at a given distance. * @param distance The distance from the camera we want the position to be * @returns the position */ TargetCamera.prototype.getFrontPosition = function (distance) { this.getWorldMatrix(); var direction = this.getTarget().subtract(this.position); direction.normalize(); direction.scaleInPlace(distance); return this.globalPosition.add(direction); }; /** @hidden */ TargetCamera.prototype._getLockedTargetPosition = function () { if (!this.lockedTarget) { return null; } if (this.lockedTarget.absolutePosition) { this.lockedTarget.computeWorldMatrix(); } return this.lockedTarget.absolutePosition || this.lockedTarget; }; /** * Store current camera state of the camera (fov, position, rotation, etc..) * @returns the camera */ TargetCamera.prototype.storeState = function () { this._storedPosition = this.position.clone(); this._storedRotation = this.rotation.clone(); if (this.rotationQuaternion) { this._storedRotationQuaternion = this.rotationQuaternion.clone(); } return _super.prototype.storeState.call(this); }; /** * Restored camera state. You must call storeState() first * @returns whether it was successful or not * @hidden */ TargetCamera.prototype._restoreStateValues = function () { if (!_super.prototype._restoreStateValues.call(this)) { return false; } this.position = this._storedPosition.clone(); this.rotation = this._storedRotation.clone(); if (this.rotationQuaternion) { this.rotationQuaternion = this._storedRotationQuaternion.clone(); } this.cameraDirection.copyFromFloats(0, 0, 0); this.cameraRotation.copyFromFloats(0, 0); return true; }; /** @hidden */ TargetCamera.prototype._initCache = function () { _super.prototype._initCache.call(this); this._cache.lockedTarget = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); this._cache.rotation = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); this._cache.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); }; /** @hidden */ TargetCamera.prototype._updateCache = function (ignoreParentClass) { if (!ignoreParentClass) { _super.prototype._updateCache.call(this); } var lockedTargetPosition = this._getLockedTargetPosition(); if (!lockedTargetPosition) { this._cache.lockedTarget = null; } else { if (!this._cache.lockedTarget) { this._cache.lockedTarget = lockedTargetPosition.clone(); } else { this._cache.lockedTarget.copyFrom(lockedTargetPosition); } } this._cache.rotation.copyFrom(this.rotation); if (this.rotationQuaternion) { this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion); } }; // Synchronized /** @hidden */ TargetCamera.prototype._isSynchronizedViewMatrix = function () { if (!_super.prototype._isSynchronizedViewMatrix.call(this)) { return false; } var lockedTargetPosition = this._getLockedTargetPosition(); return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation)); }; // Methods /** @hidden */ TargetCamera.prototype._computeLocalCameraSpeed = function () { var engine = this.getEngine(); return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0))); }; // Target /** * Defines the target the camera should look at. * This will automatically adapt alpha beta and radius to fit within the new target. * @param target Defines the new target as a Vector or a mesh */ TargetCamera.prototype.setTarget = function (target) { this.upVector.normalize(); this._initialFocalDistance = target.subtract(this.position).length(); if (this.position.z === target.z) { this.position.z += _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]; } _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix); this._camMatrix.invert(); this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]); var vDir = target.subtract(this.position); if (vDir.x >= 0.0) { this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0); } else { this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0); } this.rotation.z = 0; if (isNaN(this.rotation.x)) { this.rotation.x = 0; } if (isNaN(this.rotation.y)) { this.rotation.y = 0; } if (isNaN(this.rotation.z)) { this.rotation.z = 0; } if (this.rotationQuaternion) { _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion); } }; /** * Return the current target position of the camera. This value is expressed in local space. * @returns the target position */ TargetCamera.prototype.getTarget = function () { return this._currentTarget; }; /** @hidden */ TargetCamera.prototype._decideIfNeedsToMove = function () { return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0; }; /** @hidden */ TargetCamera.prototype._updatePosition = function () { if (this.parent) { this.parent.getWorldMatrix().invertToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_3__["Tmp"].Matrix[0]); _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformNormalToRef(this.cameraDirection, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Tmp"].Matrix[0], _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Tmp"].Vector3[0]); this.position.addInPlace(_Maths_math__WEBPACK_IMPORTED_MODULE_3__["Tmp"].Vector3[0]); return; } this.position.addInPlace(this.cameraDirection); }; /** @hidden */ TargetCamera.prototype._checkInputs = function () { var needToMove = this._decideIfNeedsToMove(); var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0; // Move if (needToMove) { this._updatePosition(); } // Rotate if (needToRotate) { this.rotation.x += this.cameraRotation.x; this.rotation.y += this.cameraRotation.y; //rotate, if quaternion is set and rotation was used if (this.rotationQuaternion) { var len = this.rotation.lengthSquared(); if (len) { _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion); } } if (!this.noRotationConstraint) { var limit = (Math.PI / 2) * 0.95; if (this.rotation.x > limit) { this.rotation.x = limit; } if (this.rotation.x < -limit) { this.rotation.x = -limit; } } } // Inertia if (needToMove) { if (Math.abs(this.cameraDirection.x) < this.speed * _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]) { this.cameraDirection.x = 0; } if (Math.abs(this.cameraDirection.y) < this.speed * _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]) { this.cameraDirection.y = 0; } if (Math.abs(this.cameraDirection.z) < this.speed * _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]) { this.cameraDirection.z = 0; } this.cameraDirection.scaleInPlace(this.inertia); } if (needToRotate) { if (Math.abs(this.cameraRotation.x) < this.speed * _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]) { this.cameraRotation.x = 0; } if (Math.abs(this.cameraRotation.y) < this.speed * _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]) { this.cameraRotation.y = 0; } this.cameraRotation.scaleInPlace(this.inertia); } _super.prototype._checkInputs.call(this); }; TargetCamera.prototype._updateCameraRotationMatrix = function () { if (this.rotationQuaternion) { this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix); } else { _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix); } }; /** * Update the up vector to apply the rotation of the camera (So if you changed the camera rotation.z this will let you update the up vector as well) * @returns the current camera */ TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () { _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector); return this; }; /** @hidden */ TargetCamera.prototype._getViewMatrix = function () { if (this.lockedTarget) { this.setTarget(this._getLockedTargetPosition()); } // Compute this._updateCameraRotationMatrix(); // Apply the changed rotation to the upVector if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) { this._rotateUpVectorWithCameraRotationMatrix(); this._cachedQuaternionRotationZ = this.rotationQuaternion.z; } else if (this._cachedRotationZ != this.rotation.z) { this._rotateUpVectorWithCameraRotationMatrix(); this._cachedRotationZ = this.rotation.z; } _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint); // Computing target and final matrix this.position.addToRef(this._transformedReferencePoint, this._currentTarget); if (this.updateUpVectorFromRotation) { if (this.rotationQuaternion) { _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Axis"].Y.rotateByQuaternionToRef(this.rotationQuaternion, this.upVector); } else { _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].FromEulerVectorToRef(this.rotation, this._tmpQuaternion); _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Axis"].Y.rotateByQuaternionToRef(this._tmpQuaternion, this.upVector); } } this._computeViewMatrix(this.position, this._currentTarget, this.upVector); return this._viewMatrix; }; TargetCamera.prototype._computeViewMatrix = function (position, target, up) { if (this.parent) { var parentWorldMatrix = this.parent.getWorldMatrix(); _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition); _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget); _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector); this._markSyncedWithParent(); } else { this._globalPosition.copyFrom(position); this._globalCurrentTarget.copyFrom(target); this._globalCurrentUpVector.copyFrom(up); } if (this.getScene().useRightHandedSystem) { _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix); } else { _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix); } }; /** * @hidden */ TargetCamera.prototype.createRigCamera = function (name, cameraIndex) { if (this.cameraRigMode !== _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_NONE) { var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene()); if (this.cameraRigMode === _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_VR || this.cameraRigMode === _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_WEBVR) { if (!this.rotationQuaternion) { this.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); } rigCamera._cameraRigParams = {}; rigCamera.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); } return rigCamera; } return null; }; /** * @hidden */ TargetCamera.prototype._updateRigCameras = function () { var camLeft = this._rigCameras[0]; var camRight = this._rigCameras[1]; this.computeWorldMatrix(); switch (this.cameraRigMode) { case _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_STEREOSCOPIC_ANAGLYPH: case _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL: case _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED: case _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_STEREOSCOPIC_OVERUNDER: //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance: var leftSign = (this.cameraRigMode === _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1; var rightSign = (this.cameraRigMode === _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1; this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft); this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle * rightSign, camRight); break; case _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_VR: if (camLeft.rotationQuaternion) { camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion); camRight.rotationQuaternion.copyFrom(this.rotationQuaternion); } else { camLeft.rotation.copyFrom(this.rotation); camRight.rotation.copyFrom(this.rotation); } camLeft.position.copyFrom(this.position); camRight.position.copyFrom(this.position); break; } _super.prototype._updateRigCameras.call(this); }; TargetCamera.prototype._getRigCamPositionAndTarget = function (halfSpace, rigCamera) { var target = this.getTarget(); target.subtractToRef(this.position, TargetCamera._TargetFocalPoint); TargetCamera._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance); var newFocalTarget = TargetCamera._TargetFocalPoint.addInPlace(this.position); _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].TranslationToRef(-newFocalTarget.x, -newFocalTarget.y, -newFocalTarget.z, TargetCamera._TargetTransformMatrix); TargetCamera._TargetTransformMatrix.multiplyToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].RotationY(halfSpace), TargetCamera._RigCamTransformMatrix); _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].TranslationToRef(newFocalTarget.x, newFocalTarget.y, newFocalTarget.z, TargetCamera._TargetTransformMatrix); TargetCamera._RigCamTransformMatrix.multiplyToRef(TargetCamera._TargetTransformMatrix, TargetCamera._RigCamTransformMatrix); _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(this.position, TargetCamera._RigCamTransformMatrix, rigCamera.position); rigCamera.setTarget(newFocalTarget); }; /** * Gets the current object class name. * @return the class name */ TargetCamera.prototype.getClassName = function () { return "TargetCamera"; }; TargetCamera._RigCamTransformMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"](); TargetCamera._TargetTransformMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"](); TargetCamera._TargetFocalPoint = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])() ], TargetCamera.prototype, "rotation", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], TargetCamera.prototype, "speed", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsMeshReference"])("lockedTargetId") ], TargetCamera.prototype, "lockedTarget", void 0); return TargetCamera; }(_camera__WEBPACK_IMPORTED_MODULE_2__["Camera"])); /***/ }), /***/ "./Cameras/touchCamera.ts": /*!********************************!*\ !*** ./Cameras/touchCamera.ts ***! \********************************/ /*! exports provided: TouchCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TouchCamera", function() { return TouchCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _freeCamera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./freeCamera */ "./Cameras/freeCamera.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts"); _node__WEBPACK_IMPORTED_MODULE_3__["Node"].AddNodeConstructor("TouchCamera", function (name, scene) { return function () { return new TouchCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), scene); }; }); /** * This represents a FPS type of camera controlled by touch. * This is like a universal camera minus the Gamepad controls. * @see http://doc.babylonjs.com/features/cameras#universal-camera */ var TouchCamera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](TouchCamera, _super); /** * Instantiates a new touch camera. * This represents a FPS type of camera controlled by touch. * This is like a universal camera minus the Gamepad controls. * @see http://doc.babylonjs.com/features/cameras#universal-camera * @param name Define the name of the camera in the scene * @param position Define the start position of the camera in the scene * @param scene Define the scene the camera belongs to */ function TouchCamera(name, position, scene) { var _this = _super.call(this, name, position, scene) || this; _this.inputs.addTouch(); _this._setupInputs(); return _this; } Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", { /** * Defines the touch sensibility for rotation. * The higher the faster. */ get: function () { var touch = this.inputs.attached["touch"]; if (touch) { return touch.touchAngularSensibility; } return 0; }, set: function (value) { var touch = this.inputs.attached["touch"]; if (touch) { touch.touchAngularSensibility = value; } }, enumerable: true, configurable: true }); Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", { /** * Defines the touch sensibility for move. * The higher the faster. */ get: function () { var touch = this.inputs.attached["touch"]; if (touch) { return touch.touchMoveSensibility; } return 0; }, set: function (value) { var touch = this.inputs.attached["touch"]; if (touch) { touch.touchMoveSensibility = value; } }, enumerable: true, configurable: true }); /** * Gets the current object class name. * @return the class name */ TouchCamera.prototype.getClassName = function () { return "TouchCamera"; }; /** @hidden */ TouchCamera.prototype._setupInputs = function () { var mouse = this.inputs.attached["mouse"]; if (mouse) { mouse.touchEnabled = false; } }; return TouchCamera; }(_freeCamera__WEBPACK_IMPORTED_MODULE_1__["FreeCamera"])); /***/ }), /***/ "./Cameras/universalCamera.ts": /*!************************************!*\ !*** ./Cameras/universalCamera.ts ***! \************************************/ /*! exports provided: UniversalCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UniversalCamera", function() { return UniversalCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _touchCamera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./touchCamera */ "./Cameras/touchCamera.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../node */ "./node.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./camera */ "./Cameras/camera.ts"); _node__WEBPACK_IMPORTED_MODULE_2__["Node"].AddNodeConstructor("FreeCamera", function (name, scene) { // Forcing to use the Universal camera return function () { return new UniversalCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), scene); }; }); /** * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera, * which still works and will still be found in many Playgrounds. * @see http://doc.babylonjs.com/features/cameras#universal-camera */ var UniversalCamera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](UniversalCamera, _super); /** * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera, * which still works and will still be found in many Playgrounds. * @see http://doc.babylonjs.com/features/cameras#universal-camera * @param name Define the name of the camera in the scene * @param position Define the start position of the camera in the scene * @param scene Define the scene the camera belongs to */ function UniversalCamera(name, position, scene) { var _this = _super.call(this, name, position, scene) || this; _this.inputs.addGamepad(); return _this; } Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", { /** * Defines the gamepad rotation sensiblity. * This is the threshold from when rotation starts to be accounted for to prevent jittering. */ get: function () { var gamepad = this.inputs.attached["gamepad"]; if (gamepad) { return gamepad.gamepadAngularSensibility; } return 0; }, set: function (value) { var gamepad = this.inputs.attached["gamepad"]; if (gamepad) { gamepad.gamepadAngularSensibility = value; } }, enumerable: true, configurable: true }); Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", { /** * Defines the gamepad move sensiblity. * This is the threshold from when moving starts to be accounted for for to prevent jittering. */ get: function () { var gamepad = this.inputs.attached["gamepad"]; if (gamepad) { return gamepad.gamepadMoveSensibility; } return 0; }, set: function (value) { var gamepad = this.inputs.attached["gamepad"]; if (gamepad) { gamepad.gamepadMoveSensibility = value; } }, enumerable: true, configurable: true }); /** * Gets the current object class name. * @return the class name */ UniversalCamera.prototype.getClassName = function () { return "UniversalCamera"; }; return UniversalCamera; }(_touchCamera__WEBPACK_IMPORTED_MODULE_1__["TouchCamera"])); _camera__WEBPACK_IMPORTED_MODULE_4__["Camera"]._createDefaultParsedCamera = function (name, scene) { return new UniversalCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), scene); }; /***/ }), /***/ "./Cameras/virtualJoysticksCamera.ts": /*!*******************************************!*\ !*** ./Cameras/virtualJoysticksCamera.ts ***! \*******************************************/ /*! exports provided: VirtualJoysticksCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VirtualJoysticksCamera", function() { return VirtualJoysticksCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _freeCamera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./freeCamera */ "./Cameras/freeCamera.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts"); /* harmony import */ var _Inputs_freeCameraVirtualJoystickInput__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Inputs/freeCameraVirtualJoystickInput */ "./Cameras/Inputs/freeCameraVirtualJoystickInput.ts"); _node__WEBPACK_IMPORTED_MODULE_3__["Node"].AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) { return function () { return new VirtualJoysticksCamera(name, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), scene); }; }); /** * This represents a free type of camera. It can be useful in First Person Shooter game for instance. * It is identical to the Free Camera and simply adds by default a virtual joystick. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera */ var VirtualJoysticksCamera = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](VirtualJoysticksCamera, _super); /** * Intantiates a VirtualJoysticksCamera. It can be useful in First Person Shooter game for instance. * It is identical to the Free Camera and simply adds by default a virtual joystick. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera * @param name Define the name of the camera in the scene * @param position Define the start position of the camera in the scene * @param scene Define the scene the camera belongs to */ function VirtualJoysticksCamera(name, position, scene) { var _this = _super.call(this, name, position, scene) || this; _this.inputs.addVirtualJoystick(); return _this; } /** * Gets the current object class name. * @return the class name */ VirtualJoysticksCamera.prototype.getClassName = function () { return "VirtualJoysticksCamera"; }; return VirtualJoysticksCamera; }(_freeCamera__WEBPACK_IMPORTED_MODULE_1__["FreeCamera"])); /***/ }), /***/ "./Collisions/collider.ts": /*!********************************!*\ !*** ./Collisions/collider.ts ***! \********************************/ /*! exports provided: Collider */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Collider", function() { return Collider; }); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) { if (boxMin.x > sphereCenter.x + sphereRadius) { return false; } if (sphereCenter.x - sphereRadius > boxMax.x) { return false; } if (boxMin.y > sphereCenter.y + sphereRadius) { return false; } if (sphereCenter.y - sphereRadius > boxMax.y) { return false; } if (boxMin.z > sphereCenter.z + sphereRadius) { return false; } if (sphereCenter.z - sphereRadius > boxMax.z) { return false; } return true; }; var getLowestRoot = (function () { var result = { root: 0, found: false }; return function (a, b, c, maxR) { result.root = 0; result.found = false; var determinant = b * b - 4.0 * a * c; if (determinant < 0) { return result; } var sqrtD = Math.sqrt(determinant); var r1 = (-b - sqrtD) / (2.0 * a); var r2 = (-b + sqrtD) / (2.0 * a); if (r1 > r2) { var temp = r2; r2 = r1; r1 = temp; } if (r1 > 0 && r1 < maxR) { result.root = r1; result.found = true; return result; } if (r2 > 0 && r2 < maxR) { result.root = r2; result.found = true; return result; } return result; }; })(); /** @hidden */ var Collider = /** @class */ (function () { function Collider() { this._collisionPoint = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); this._planeIntersectionPoint = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); this._tempVector = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); this._tempVector2 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); this._tempVector3 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); this._tempVector4 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); this._edge = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); this._baseToVertex = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); this._destinationPoint = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); this._slidePlaneNormal = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); this._displacementVector = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); /** @hidden */ this._radius = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].One(); /** @hidden */ this._retry = 0; /** @hidden */ this._basePointWorld = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); this._velocityWorld = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); this._normalizedVelocity = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); this._collisionMask = -1; } Object.defineProperty(Collider.prototype, "collisionMask", { get: function () { return this._collisionMask; }, set: function (mask) { this._collisionMask = !isNaN(mask) ? mask : -1; }, enumerable: true, configurable: true }); Object.defineProperty(Collider.prototype, "slidePlaneNormal", { /** * Gets the plane normal used to compute the sliding response (in local space) */ get: function () { return this._slidePlaneNormal; }, enumerable: true, configurable: true }); // Methods /** @hidden */ Collider.prototype._initialize = function (source, dir, e) { this._velocity = dir; _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].NormalizeToRef(dir, this._normalizedVelocity); this._basePoint = source; source.multiplyToRef(this._radius, this._basePointWorld); dir.multiplyToRef(this._radius, this._velocityWorld); this._velocityWorldLength = this._velocityWorld.length(); this._epsilon = e; this.collisionFound = false; }; /** @hidden */ Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) { pa.subtractToRef(point, this._tempVector); pb.subtractToRef(point, this._tempVector2); _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].CrossToRef(this._tempVector, this._tempVector2, this._tempVector4); var d = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._tempVector4, n); if (d < 0) { return false; } pc.subtractToRef(point, this._tempVector3); _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4); d = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._tempVector4, n); if (d < 0) { return false; } _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].CrossToRef(this._tempVector3, this._tempVector, this._tempVector4); d = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._tempVector4, n); return d >= 0; }; /** @hidden */ Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) { var distance = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Distance(this._basePointWorld, sphereCenter); var max = Math.max(this._radius.x, this._radius.y, this._radius.z); if (distance > this._velocityWorldLength + max + sphereRadius) { return false; } if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max)) { return false; } return true; }; /** @hidden */ Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) { var t0; var embeddedInPlane = false; //defensive programming, actually not needed. if (!trianglePlaneArray) { trianglePlaneArray = []; } if (!trianglePlaneArray[faceIndex]) { trianglePlaneArray[faceIndex] = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Plane"](0, 0, 0, 0); trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3); } var trianglePlane = trianglePlaneArray[faceIndex]; if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0)) { return; } var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint); var normalDotVelocity = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(trianglePlane.normal, this._velocity); if (normalDotVelocity == 0) { if (Math.abs(signedDistToTrianglePlane) >= 1.0) { return; } embeddedInPlane = true; t0 = 0; } else { t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity; var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity; if (t0 > t1) { var temp = t1; t1 = t0; t0 = temp; } if (t0 > 1.0 || t1 < 0.0) { return; } if (t0 < 0) { t0 = 0; } if (t0 > 1.0) { t0 = 1.0; } } this._collisionPoint.copyFromFloats(0, 0, 0); var found = false; var t = 1.0; if (!embeddedInPlane) { this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint); this._velocity.scaleToRef(t0, this._tempVector); this._planeIntersectionPoint.addInPlace(this._tempVector); if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) { found = true; t = t0; this._collisionPoint.copyFrom(this._planeIntersectionPoint); } } if (!found) { var velocitySquaredLength = this._velocity.lengthSquared(); var a = velocitySquaredLength; this._basePoint.subtractToRef(p1, this._tempVector); var b = 2.0 * (_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._velocity, this._tempVector)); var c = this._tempVector.lengthSquared() - 1.0; var lowestRoot = getLowestRoot(a, b, c, t); if (lowestRoot.found) { t = lowestRoot.root; found = true; this._collisionPoint.copyFrom(p1); } this._basePoint.subtractToRef(p2, this._tempVector); b = 2.0 * (_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._velocity, this._tempVector)); c = this._tempVector.lengthSquared() - 1.0; lowestRoot = getLowestRoot(a, b, c, t); if (lowestRoot.found) { t = lowestRoot.root; found = true; this._collisionPoint.copyFrom(p2); } this._basePoint.subtractToRef(p3, this._tempVector); b = 2.0 * (_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._velocity, this._tempVector)); c = this._tempVector.lengthSquared() - 1.0; lowestRoot = getLowestRoot(a, b, c, t); if (lowestRoot.found) { t = lowestRoot.root; found = true; this._collisionPoint.copyFrom(p3); } p2.subtractToRef(p1, this._edge); p1.subtractToRef(this._basePoint, this._baseToVertex); var edgeSquaredLength = this._edge.lengthSquared(); var edgeDotVelocity = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._edge, this._velocity); var edgeDotBaseToVertex = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._edge, this._baseToVertex); a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity; b = edgeSquaredLength * (2.0 * _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex; c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex; lowestRoot = getLowestRoot(a, b, c, t); if (lowestRoot.found) { var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength; if (f >= 0.0 && f <= 1.0) { t = lowestRoot.root; found = true; this._edge.scaleInPlace(f); p1.addToRef(this._edge, this._collisionPoint); } } p3.subtractToRef(p2, this._edge); p2.subtractToRef(this._basePoint, this._baseToVertex); edgeSquaredLength = this._edge.lengthSquared(); edgeDotVelocity = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._edge, this._velocity); edgeDotBaseToVertex = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._edge, this._baseToVertex); a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity; b = edgeSquaredLength * (2.0 * _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex; c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex; lowestRoot = getLowestRoot(a, b, c, t); if (lowestRoot.found) { f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength; if (f >= 0.0 && f <= 1.0) { t = lowestRoot.root; found = true; this._edge.scaleInPlace(f); p2.addToRef(this._edge, this._collisionPoint); } } p1.subtractToRef(p3, this._edge); p3.subtractToRef(this._basePoint, this._baseToVertex); edgeSquaredLength = this._edge.lengthSquared(); edgeDotVelocity = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._edge, this._velocity); edgeDotBaseToVertex = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._edge, this._baseToVertex); a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity; b = edgeSquaredLength * (2.0 * _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex; c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex; lowestRoot = getLowestRoot(a, b, c, t); if (lowestRoot.found) { f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength; if (f >= 0.0 && f <= 1.0) { t = lowestRoot.root; found = true; this._edge.scaleInPlace(f); p3.addToRef(this._edge, this._collisionPoint); } } } if (found) { var distToCollision = t * this._velocity.length(); if (!this.collisionFound || distToCollision < this._nearestDistance) { if (!this.intersectionPoint) { this.intersectionPoint = this._collisionPoint.clone(); } else { this.intersectionPoint.copyFrom(this._collisionPoint); } this._nearestDistance = distToCollision; this.collisionFound = true; } } }; /** @hidden */ Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) { for (var i = indexStart; i < indexEnd; i += 3) { var p1 = pts[indices[i] - decal]; var p2 = pts[indices[i + 1] - decal]; var p3 = pts[indices[i + 2] - decal]; this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial); } }; /** @hidden */ Collider.prototype._getResponse = function (pos, vel) { pos.addToRef(vel, this._destinationPoint); vel.scaleInPlace((this._nearestDistance / vel.length())); this._basePoint.addToRef(vel, pos); pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal); this._slidePlaneNormal.normalize(); this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector); pos.addInPlace(this._displacementVector); this.intersectionPoint.addInPlace(this._displacementVector); this._slidePlaneNormal.scaleInPlace(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Plane"].SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint)); this._destinationPoint.subtractInPlace(this._slidePlaneNormal); this._destinationPoint.subtractToRef(this.intersectionPoint, vel); }; return Collider; }()); /***/ }), /***/ "./Collisions/collisionCoordinator.ts": /*!********************************************!*\ !*** ./Collisions/collisionCoordinator.ts ***! \********************************************/ /*! exports provided: DefaultCollisionCoordinator */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DefaultCollisionCoordinator", function() { return DefaultCollisionCoordinator; }); /* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../scene */ "./scene.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); /* harmony import */ var _collider__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./collider */ "./Collisions/collider.ts"); /** @hidden */ var DefaultCollisionCoordinator = /** @class */ (function () { function DefaultCollisionCoordinator() { this._scaledPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); this._scaledVelocity = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); this._finalPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); } DefaultCollisionCoordinator.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) { position.divideToRef(collider._radius, this._scaledPosition); displacement.divideToRef(collider._radius, this._scaledVelocity); collider.collidedMesh = null; collider._retry = 0; collider._initialVelocity = this._scaledVelocity; collider._initialPosition = this._scaledPosition; this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh); this._finalPosition.multiplyInPlace(collider._radius); //run the callback onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh); }; DefaultCollisionCoordinator.prototype.createCollider = function () { return new _collider__WEBPACK_IMPORTED_MODULE_3__["Collider"](); }; DefaultCollisionCoordinator.prototype.init = function (scene) { this._scene = scene; }; DefaultCollisionCoordinator.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) { if (excludedMesh === void 0) { excludedMesh = null; } var closeDistance = _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].CollisionsEpsilon * 10.0; if (collider._retry >= maximumRetry) { finalPosition.copyFrom(position); return; } // Check if this is a mesh else camera or -1 var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask); collider._initialize(position, velocity, closeDistance); // Check all meshes for (var index = 0; index < this._scene.meshes.length; index++) { var mesh = this._scene.meshes[index]; if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) { mesh._checkCollision(collider); } } if (!collider.collisionFound) { position.addToRef(velocity, finalPosition); return; } if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) { collider._getResponse(position, velocity); } if (velocity.length() <= closeDistance) { finalPosition.copyFrom(position); return; } collider._retry++; this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh); }; return DefaultCollisionCoordinator; }()); _scene__WEBPACK_IMPORTED_MODULE_0__["Scene"].CollisionCoordinatorFactory = function () { return new DefaultCollisionCoordinator(); }; /***/ }), /***/ "./Collisions/index.ts": /*!*****************************!*\ !*** ./Collisions/index.ts ***! \*****************************/ /*! exports provided: Collider, DefaultCollisionCoordinator, PickingInfo, IntersectionInfo */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _collider__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./collider */ "./Collisions/collider.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Collider", function() { return _collider__WEBPACK_IMPORTED_MODULE_0__["Collider"]; }); /* harmony import */ var _collisionCoordinator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./collisionCoordinator */ "./Collisions/collisionCoordinator.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DefaultCollisionCoordinator", function() { return _collisionCoordinator__WEBPACK_IMPORTED_MODULE_1__["DefaultCollisionCoordinator"]; }); /* harmony import */ var _pickingInfo__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./pickingInfo */ "./Collisions/pickingInfo.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PickingInfo", function() { return _pickingInfo__WEBPACK_IMPORTED_MODULE_2__["PickingInfo"]; }); /* harmony import */ var _intersectionInfo__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./intersectionInfo */ "./Collisions/intersectionInfo.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IntersectionInfo", function() { return _intersectionInfo__WEBPACK_IMPORTED_MODULE_3__["IntersectionInfo"]; }); /***/ }), /***/ "./Collisions/intersectionInfo.ts": /*!****************************************!*\ !*** ./Collisions/intersectionInfo.ts ***! \****************************************/ /*! exports provided: IntersectionInfo */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IntersectionInfo", function() { return IntersectionInfo; }); /** * @hidden */ var IntersectionInfo = /** @class */ (function () { function IntersectionInfo(bu, bv, distance) { this.bu = bu; this.bv = bv; this.distance = distance; this.faceId = 0; this.subMeshId = 0; } return IntersectionInfo; }()); /***/ }), /***/ "./Collisions/pickingInfo.ts": /*!***********************************!*\ !*** ./Collisions/pickingInfo.ts ***! \***********************************/ /*! exports provided: PickingInfo */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PickingInfo", function() { return PickingInfo; }); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Meshes/buffer */ "./Meshes/buffer.ts"); /** * Information about the result of picking within a scene * @see https://doc.babylonjs.com/babylon101/picking_collisions */ var PickingInfo = /** @class */ (function () { function PickingInfo() { /** @hidden */ this._pickingUnavailable = false; /** * If the pick collided with an object */ this.hit = false; /** * Distance away where the pick collided */ this.distance = 0; /** * The location of pick collision */ this.pickedPoint = null; /** * The mesh corresponding the the pick collision */ this.pickedMesh = null; /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/ this.bu = 0; /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/ this.bv = 0; /** The index of the face on the mesh that was picked, or the index of the Line if the picked Mesh is a LinesMesh */ this.faceId = -1; /** Id of the the submesh that was picked */ this.subMeshId = 0; /** If a sprite was picked, this will be the sprite the pick collided with */ this.pickedSprite = null; /** * If a mesh was used to do the picking (eg. 6dof controller) this will be populated. */ this.originMesh = null; /** * The ray that was used to perform the picking. */ this.ray = null; } /** * Gets the normal correspodning 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 * @returns The normal correspodning to the face the pick collided with */ PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) { if (useWorldCoordinates === void 0) { useWorldCoordinates = false; } if (useVerticesNormals === void 0) { useVerticesNormals = true; } if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_1__["VertexBuffer"].NormalKind)) { return null; } var indices = this.pickedMesh.getIndices(); if (!indices) { return null; } var result; if (useVerticesNormals) { var normals = this.pickedMesh.getVerticesData(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_1__["VertexBuffer"].NormalKind); var normal0 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(normals, indices[this.faceId * 3] * 3); var normal1 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(normals, indices[this.faceId * 3 + 1] * 3); var normal2 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(normals, indices[this.faceId * 3 + 2] * 3); normal0 = normal0.scale(this.bu); normal1 = normal1.scale(this.bv); normal2 = normal2.scale(1.0 - this.bu - this.bv); result = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z); } else { var positions = this.pickedMesh.getVerticesData(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_1__["VertexBuffer"].PositionKind); var vertex1 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(positions, indices[this.faceId * 3] * 3); var vertex2 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(positions, indices[this.faceId * 3 + 1] * 3); var vertex3 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(positions, indices[this.faceId * 3 + 2] * 3); var p1p2 = vertex1.subtract(vertex2); var p3p2 = vertex3.subtract(vertex2); result = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Cross(p1p2, p3p2); } if (useWorldCoordinates) { var wm = this.pickedMesh.getWorldMatrix(); if (this.pickedMesh.nonUniformScaling) { _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tmp"].Matrix[0].copyFrom(wm); wm = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tmp"].Matrix[0]; wm.setTranslationFromFloats(0, 0, 0); wm.invert(); wm.transposeToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tmp"].Matrix[1]); wm = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tmp"].Matrix[1]; } result = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].TransformNormal(result, wm); } result.normalize(); return result; }; /** * Gets the texture coordinates of where the pick occured * @returns the vector containing the coordnates of the texture */ PickingInfo.prototype.getTextureCoordinates = function () { if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_1__["VertexBuffer"].UVKind)) { return null; } var indices = this.pickedMesh.getIndices(); if (!indices) { return null; } var uvs = this.pickedMesh.getVerticesData(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_1__["VertexBuffer"].UVKind); if (!uvs) { return null; } var uv0 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"].FromArray(uvs, indices[this.faceId * 3] * 2); var uv1 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"].FromArray(uvs, indices[this.faceId * 3 + 1] * 2); var uv2 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"].FromArray(uvs, indices[this.faceId * 3 + 2] * 2); uv0 = uv0.scale(1.0 - this.bu - this.bv); uv1 = uv1.scale(this.bu); uv2 = uv2.scale(this.bv); return new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"](uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y); }; return PickingInfo; }()); /***/ }), /***/ "./Culling/Octrees/index.ts": /*!**********************************!*\ !*** ./Culling/Octrees/index.ts ***! \**********************************/ /*! exports provided: Octree, OctreeBlock, OctreeSceneComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _octree__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./octree */ "./Culling/Octrees/octree.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Octree", function() { return _octree__WEBPACK_IMPORTED_MODULE_0__["Octree"]; }); /* harmony import */ var _octreeBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./octreeBlock */ "./Culling/Octrees/octreeBlock.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OctreeBlock", function() { return _octreeBlock__WEBPACK_IMPORTED_MODULE_1__["OctreeBlock"]; }); /* harmony import */ var _octreeSceneComponent__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./octreeSceneComponent */ "./Culling/Octrees/octreeSceneComponent.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OctreeSceneComponent", function() { return _octreeSceneComponent__WEBPACK_IMPORTED_MODULE_2__["OctreeSceneComponent"]; }); /***/ }), /***/ "./Culling/Octrees/octree.ts": /*!***********************************!*\ !*** ./Culling/Octrees/octree.ts ***! \***********************************/ /*! exports provided: Octree */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Octree", function() { return Octree; }); /* harmony import */ var _Misc_smartArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Misc/smartArray */ "./Misc/smartArray.ts"); /* harmony import */ var _octreeBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./octreeBlock */ "./Culling/Octrees/octreeBlock.ts"); /** * Octrees are a really powerful data structure that can quickly select entities based on space coordinates. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees */ var Octree = /** @class */ (function () { /** * Creates a octree * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees * @param creationFunc function to be used to instatiate the octree * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64) * @param maxDepth defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.) */ function Octree(creationFunc, maxBlockCapacity, /** Defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.) */ maxDepth) { if (maxDepth === void 0) { maxDepth = 2; } this.maxDepth = maxDepth; /** * Content stored in the octree */ this.dynamicContent = new Array(); this._maxBlockCapacity = maxBlockCapacity || 64; this._selectionContent = new _Misc_smartArray__WEBPACK_IMPORTED_MODULE_0__["SmartArrayNoDuplicate"](1024); this._creationFunc = creationFunc; } // Methods /** * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters * @param worldMin worldMin for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2); * @param worldMax worldMax for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2); * @param entries meshes to be added to the octree blocks */ Octree.prototype.update = function (worldMin, worldMax, entries) { _octreeBlock__WEBPACK_IMPORTED_MODULE_1__["OctreeBlock"]._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc); }; /** * Adds a mesh to the octree * @param entry Mesh to add to the octree */ Octree.prototype.addMesh = function (entry) { for (var index = 0; index < this.blocks.length; index++) { var block = this.blocks[index]; block.addEntry(entry); } }; /** * Remove an element from the octree * @param entry defines the element to remove */ Octree.prototype.removeMesh = function (entry) { for (var index = 0; index < this.blocks.length; index++) { var block = this.blocks[index]; block.removeEntry(entry); } }; /** * Selects an array of meshes within the frustum * @param frustumPlanes The frustum planes to use which will select all meshes within it * @param allowDuplicate If duplicate objects are allowed in the resulting object array * @returns array of meshes within the frustum */ Octree.prototype.select = function (frustumPlanes, allowDuplicate) { this._selectionContent.reset(); for (var index = 0; index < this.blocks.length; index++) { var block = this.blocks[index]; block.select(frustumPlanes, this._selectionContent, allowDuplicate); } if (allowDuplicate) { this._selectionContent.concat(this.dynamicContent); } else { this._selectionContent.concatWithNoDuplicate(this.dynamicContent); } return this._selectionContent; }; /** * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array * @param sphereCenter defines the bounding sphere center * @param sphereRadius defines the bounding sphere radius * @param allowDuplicate defines if the selection array can contains duplicated entries * @returns an array of objects that intersect the sphere */ Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) { this._selectionContent.reset(); for (var index = 0; index < this.blocks.length; index++) { var block = this.blocks[index]; block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate); } if (allowDuplicate) { this._selectionContent.concat(this.dynamicContent); } else { this._selectionContent.concatWithNoDuplicate(this.dynamicContent); } return this._selectionContent; }; /** * Test if the octree intersect with the given ray and if yes, then add its content to resulting array * @param ray defines the ray to test with * @returns array of intersected objects */ Octree.prototype.intersectsRay = function (ray) { this._selectionContent.reset(); for (var index = 0; index < this.blocks.length; index++) { var block = this.blocks[index]; block.intersectsRay(ray, this._selectionContent); } this._selectionContent.concatWithNoDuplicate(this.dynamicContent); return this._selectionContent; }; /** * Adds a mesh into the octree block if it intersects the block */ Octree.CreationFuncForMeshes = function (entry, block) { var boundingInfo = entry.getBoundingInfo(); if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) { block.entries.push(entry); } }; /** * Adds a submesh into the octree block if it intersects the block */ Octree.CreationFuncForSubMeshes = function (entry, block) { var boundingInfo = entry.getBoundingInfo(); if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) { block.entries.push(entry); } }; return Octree; }()); /***/ }), /***/ "./Culling/Octrees/octreeBlock.ts": /*!****************************************!*\ !*** ./Culling/Octrees/octreeBlock.ts ***! \****************************************/ /*! exports provided: OctreeBlock */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OctreeBlock", function() { return OctreeBlock; }); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Culling_boundingBox__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Culling/boundingBox */ "./Culling/boundingBox.ts"); /** * Class used to store a cell in an octree * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees */ var OctreeBlock = /** @class */ (function () { /** * Creates a new block * @param minPoint defines the minimum vector (in world space) of the block's bounding box * @param maxPoint defines the maximum vector (in world space) of the block's bounding box * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks) * @param depth defines the current depth of this block in the octree * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored) * @param creationFunc defines a callback to call when an element is added to the block */ function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) { /** * Gets the content of the current block */ this.entries = new Array(); this._boundingVectors = new Array(); this._capacity = capacity; this._depth = depth; this._maxDepth = maxDepth; this._creationFunc = creationFunc; this._minPoint = minPoint; this._maxPoint = maxPoint; this._boundingVectors.push(minPoint.clone()); this._boundingVectors.push(maxPoint.clone()); this._boundingVectors.push(minPoint.clone()); this._boundingVectors[2].x = maxPoint.x; this._boundingVectors.push(minPoint.clone()); this._boundingVectors[3].y = maxPoint.y; this._boundingVectors.push(minPoint.clone()); this._boundingVectors[4].z = maxPoint.z; this._boundingVectors.push(maxPoint.clone()); this._boundingVectors[5].z = minPoint.z; this._boundingVectors.push(maxPoint.clone()); this._boundingVectors[6].x = minPoint.x; this._boundingVectors.push(maxPoint.clone()); this._boundingVectors[7].y = minPoint.y; } Object.defineProperty(OctreeBlock.prototype, "capacity", { // Property /** * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks) */ get: function () { return this._capacity; }, enumerable: true, configurable: true }); Object.defineProperty(OctreeBlock.prototype, "minPoint", { /** * Gets the minimum vector (in world space) of the block's bounding box */ get: function () { return this._minPoint; }, enumerable: true, configurable: true }); Object.defineProperty(OctreeBlock.prototype, "maxPoint", { /** * Gets the maximum vector (in world space) of the block's bounding box */ get: function () { return this._maxPoint; }, enumerable: true, configurable: true }); // Methods /** * Add a new element to this block * @param entry defines the element to add */ OctreeBlock.prototype.addEntry = function (entry) { if (this.blocks) { for (var index = 0; index < this.blocks.length; index++) { var block = this.blocks[index]; block.addEntry(entry); } return; } this._creationFunc(entry, this); if (this.entries.length > this.capacity && this._depth < this._maxDepth) { this.createInnerBlocks(); } }; /** * Remove an element from this block * @param entry defines the element to remove */ OctreeBlock.prototype.removeEntry = function (entry) { if (this.blocks) { for (var index = 0; index < this.blocks.length; index++) { var block = this.blocks[index]; block.removeEntry(entry); } return; } var entryIndex = this.entries.indexOf(entry); if (entryIndex > -1) { this.entries.splice(entryIndex, 1); } }; /** * Add an array of elements to this block * @param entries defines the array of elements to add */ OctreeBlock.prototype.addEntries = function (entries) { for (var index = 0; index < entries.length; index++) { var mesh = entries[index]; this.addEntry(mesh); } }; /** * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array * @param frustumPlanes defines the frustum planes to test * @param selection defines the array to store current content if selection is positive * @param allowDuplicate defines if the selection array can contains duplicated entries */ OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) { if (_Culling_boundingBox__WEBPACK_IMPORTED_MODULE_1__["BoundingBox"].IsInFrustum(this._boundingVectors, frustumPlanes)) { if (this.blocks) { for (var index = 0; index < this.blocks.length; index++) { var block = this.blocks[index]; block.select(frustumPlanes, selection, allowDuplicate); } return; } if (allowDuplicate) { selection.concat(this.entries); } else { selection.concatWithNoDuplicate(this.entries); } } }; /** * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array * @param sphereCenter defines the bounding sphere center * @param sphereRadius defines the bounding sphere radius * @param selection defines the array to store current content if selection is positive * @param allowDuplicate defines if the selection array can contains duplicated entries */ OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) { if (_Culling_boundingBox__WEBPACK_IMPORTED_MODULE_1__["BoundingBox"].IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) { if (this.blocks) { for (var index = 0; index < this.blocks.length; index++) { var block = this.blocks[index]; block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate); } return; } if (allowDuplicate) { selection.concat(this.entries); } else { selection.concatWithNoDuplicate(this.entries); } } }; /** * Test if the current block intersect with the given ray and if yes, then add its content to the selection array * @param ray defines the ray to test with * @param selection defines the array to store current content if selection is positive */ OctreeBlock.prototype.intersectsRay = function (ray, selection) { if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) { if (this.blocks) { for (var index = 0; index < this.blocks.length; index++) { var block = this.blocks[index]; block.intersectsRay(ray, selection); } return; } selection.concatWithNoDuplicate(this.entries); } }; /** * Subdivide the content into child blocks (this block will then be empty) */ OctreeBlock.prototype.createInnerBlocks = function () { OctreeBlock._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc); }; /** * @hidden */ OctreeBlock._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) { target.blocks = new Array(); var blockSize = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"]((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2); // Segmenting space for (var x = 0; x < 2; x++) { for (var y = 0; y < 2; y++) { for (var z = 0; z < 2; z++) { var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z)); var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1)); var block = new OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc); block.addEntries(entries); target.blocks.push(block); } } } }; return OctreeBlock; }()); /***/ }), /***/ "./Culling/Octrees/octreeSceneComponent.ts": /*!*************************************************!*\ !*** ./Culling/Octrees/octreeSceneComponent.ts ***! \*************************************************/ /*! exports provided: OctreeSceneComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OctreeSceneComponent", function() { return OctreeSceneComponent; }); /* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../scene */ "./scene.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts"); /* harmony import */ var _Culling_ray__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Culling/ray */ "./Culling/ray.ts"); /* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../sceneComponent */ "./sceneComponent.ts"); /* harmony import */ var _octree__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./octree */ "./Culling/Octrees/octree.ts"); _scene__WEBPACK_IMPORTED_MODULE_0__["Scene"].prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) { if (maxCapacity === void 0) { maxCapacity = 64; } if (maxDepth === void 0) { maxDepth = 2; } var component = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_OCTREE); if (!component) { component = new OctreeSceneComponent(this); this._addComponent(component); } if (!this._selectionOctree) { this._selectionOctree = new _octree__WEBPACK_IMPORTED_MODULE_5__["Octree"](_octree__WEBPACK_IMPORTED_MODULE_5__["Octree"].CreationFuncForMeshes, maxCapacity, maxDepth); } var worldExtends = this.getWorldExtends(); // Update octree this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes); return this._selectionOctree; }; Object.defineProperty(_scene__WEBPACK_IMPORTED_MODULE_0__["Scene"].prototype, "selectionOctree", { get: function () { return this._selectionOctree; }, enumerable: true, configurable: true }); /** * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree * @param maxCapacity defines the maximum size of each block (64 by default) * @param maxDepth defines the maximum depth to use (no more than 2 levels by default) * @returns the new octree * @see https://www.babylonjs-playground.com/#NA4OQ#12 * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees */ _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_2__["AbstractMesh"].prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) { if (maxCapacity === void 0) { maxCapacity = 64; } if (maxDepth === void 0) { maxDepth = 2; } var scene = this.getScene(); var component = scene._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_OCTREE); if (!component) { component = new OctreeSceneComponent(scene); scene._addComponent(component); } if (!this._submeshesOctree) { this._submeshesOctree = new _octree__WEBPACK_IMPORTED_MODULE_5__["Octree"](_octree__WEBPACK_IMPORTED_MODULE_5__["Octree"].CreationFuncForSubMeshes, maxCapacity, maxDepth); } this.computeWorldMatrix(true); var boundingInfo = this.getBoundingInfo(); // Update octree var bbox = boundingInfo.boundingBox; this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes); return this._submeshesOctree; }; /** * Defines the octree scene component responsible to manage any octrees * in a given scene. */ var OctreeSceneComponent = /** @class */ (function () { /** * Creates a new instance of the component for the given scene * @param scene Defines the scene to register the component in */ function OctreeSceneComponent(scene) { /** * The component name helpfull to identify the component in the list of scene components. */ this.name = _sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_OCTREE; /** * Indicates if the meshes have been checked to make sure they are isEnabled() */ this.checksIsEnabled = true; this._tempRay = new _Culling_ray__WEBPACK_IMPORTED_MODULE_3__["Ray"](_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(), new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](1, 1, 1)); this.scene = scene; this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this); this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this); this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this); this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this); } /** * Registers the component in a given scene */ OctreeSceneComponent.prototype.register = function () { var _this = this; this.scene.onMeshRemovedObservable.add(function (mesh) { var sceneOctree = _this.scene.selectionOctree; if (sceneOctree !== undefined && sceneOctree !== null) { var index = sceneOctree.dynamicContent.indexOf(mesh); if (index !== -1) { sceneOctree.dynamicContent.splice(index, 1); } } }); this.scene.onMeshImportedObservable.add(function (mesh) { var sceneOctree = _this.scene.selectionOctree; if (sceneOctree !== undefined && sceneOctree !== null) { sceneOctree.addMesh(mesh); } }); }; /** * Return the list of active meshes * @returns the list of active meshes */ OctreeSceneComponent.prototype.getActiveMeshCandidates = function () { if (this.scene._selectionOctree) { var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes); return selection; } return this.scene._getDefaultMeshCandidates(); }; /** * Return the list of active sub meshes * @param mesh The mesh to get the candidates sub meshes from * @returns the list of active sub meshes */ OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) { if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) { var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes); return intersections; } return this.scene._getDefaultSubMeshCandidates(mesh); }; /** * Return the list of sub meshes intersecting with a given local ray * @param mesh defines the mesh to find the submesh for * @param localRay defines the ray in local space * @returns the list of intersecting sub meshes */ OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) { if (mesh._submeshesOctree && mesh.useOctreeForPicking) { _Culling_ray__WEBPACK_IMPORTED_MODULE_3__["Ray"].TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay); var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay); return intersections; } return this.scene._getDefaultSubMeshCandidates(mesh); }; /** * Return the list of sub meshes colliding with a collider * @param mesh defines the mesh to find the submesh for * @param collider defines the collider to evaluate the collision against * @returns the list of colliding sub meshes */ OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) { if (mesh._submeshesOctree && mesh.useOctreeForCollisions) { var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z); var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius); return intersections; } return this.scene._getDefaultSubMeshCandidates(mesh); }; /** * Rebuilds the elements related to this component in case of * context lost for instance. */ OctreeSceneComponent.prototype.rebuild = function () { // Nothing to do here. }; /** * Disposes the component and the associated ressources. */ OctreeSceneComponent.prototype.dispose = function () { // Nothing to do here. }; return OctreeSceneComponent; }()); /***/ }), /***/ "./Culling/boundingBox.ts": /*!********************************!*\ !*** ./Culling/boundingBox.ts ***! \********************************/ /*! exports provided: BoundingBox */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoundingBox", function() { return BoundingBox; }); /* harmony import */ var _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/arrayTools */ "./Misc/arrayTools.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /** * Class used to store bounding box information */ var BoundingBox = /** @class */ (function () { /** * 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 */ function BoundingBox(min, max, worldMatrix) { /** * Gets the 8 vectors representing the bounding box in local space */ this.vectors = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(8, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero); /** * Gets the center of the bounding box in local space */ this.center = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); /** * Gets the center of the bounding box in world space */ this.centerWorld = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); /** * Gets the extend size in local space */ this.extendSize = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); /** * Gets the extend size in world space */ this.extendSizeWorld = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); /** * Gets the OBB (object bounding box) directions */ this.directions = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(3, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero); /** * Gets the 8 vectors representing the bounding box in world space */ this.vectorsWorld = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(8, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero); /** * Gets the minimum vector in world space */ this.minimumWorld = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); /** * Gets the maximum vector in world space */ this.maximumWorld = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); /** * Gets the minimum vector in local space */ this.minimum = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); /** * Gets the maximum vector in local space */ this.maximum = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); 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 */ BoundingBox.prototype.reConstruct = function (min, max, worldMatrix) { var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z; var vectors = this.vectors; this.minimum.copyFromFloats(minX, minY, minZ); this.maximum.copyFromFloats(maxX, maxY, maxZ); vectors[0].copyFromFloats(minX, minY, minZ); vectors[1].copyFromFloats(maxX, maxY, maxZ); vectors[2].copyFromFloats(maxX, minY, minZ); vectors[3].copyFromFloats(minX, maxY, minZ); vectors[4].copyFromFloats(minX, minY, maxZ); vectors[5].copyFromFloats(maxX, maxY, minZ); vectors[6].copyFromFloats(minX, maxY, maxZ); vectors[7].copyFromFloats(maxX, minY, maxZ); // OBB max.addToRef(min, this.center).scaleInPlace(0.5); max.subtractToRef(min, this.extendSize).scaleInPlace(0.5); this._update(worldMatrix || _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].IdentityReadOnly); }; /** * Scale the current bounding box by applying a scale factor * @param factor defines the scale factor to apply * @returns the current bounding box */ BoundingBox.prototype.scale = function (factor) { var tmpVectors = BoundingBox.TmpVector3; var diff = this.maximum.subtractToRef(this.minimum, tmpVectors[0]); var len = diff.length(); diff.normalizeFromLength(len); var distance = len * factor; var newRadius = diff.scaleInPlace(distance * 0.5); var min = this.center.subtractToRef(newRadius, tmpVectors[1]); var 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 */ BoundingBox.prototype.getWorldMatrix = function () { return this._worldMatrix; }; /** @hidden */ BoundingBox.prototype._update = function (world) { var minWorld = this.minimumWorld; var maxWorld = this.maximumWorld; var directions = this.directions; var vectorsWorld = this.vectorsWorld; var vectors = this.vectors; if (!world.isIdentity()) { minWorld.setAll(Number.MAX_VALUE); maxWorld.setAll(-Number.MAX_VALUE); for (var index = 0; index < 8; ++index) { var v = vectorsWorld[index]; _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(vectors[index], world, v); minWorld.minimizeInPlace(v); maxWorld.maximizeInPlace(v); } // Extend maxWorld.subtractToRef(minWorld, this.extendSizeWorld).scaleInPlace(0.5); maxWorld.addToRef(minWorld, this.centerWorld).scaleInPlace(0.5); } else { minWorld.copyFrom(this.minimum); maxWorld.copyFrom(this.maximum); for (var index = 0; index < 8; ++index) { vectorsWorld[index].copyFrom(vectors[index]); } // Extend this.extendSizeWorld.copyFrom(this.extendSize); this.centerWorld.copyFrom(this.center); } _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].FromArrayToRef(world.m, 0, directions[0]); _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].FromArrayToRef(world.m, 4, directions[1]); _Maths_math__WEBPACK_IMPORTED_MODULE_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 */ BoundingBox.prototype.isInFrustum = function (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 */ BoundingBox.prototype.isCompletelyInFrustum = function (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 */ BoundingBox.prototype.intersectsPoint = function (point) { var min = this.minimumWorld; var max = this.maximumWorld; var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z; var pointX = point.x, pointY = point.y, pointZ = point.z; var delta = -_Maths_math__WEBPACK_IMPORTED_MODULE_1__["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 */ BoundingBox.prototype.intersectsSphere = function (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 */ BoundingBox.prototype.intersectsMinMax = function (min, max) { var myMin = this.minimumWorld; var myMax = this.maximumWorld; var myMinX = myMin.x, myMinY = myMin.y, myMinZ = myMin.z, myMaxX = myMax.x, myMaxY = myMax.y, myMaxZ = myMax.z; var 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; }; // 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 */ BoundingBox.Intersects = function (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 */ BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) { var vector = BoundingBox.TmpVector3[0]; _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].ClampToRef(sphereCenter, minPoint, maxPoint, vector); var num = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["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 * @return true if there is an inclusion */ BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) { for (var p = 0; p < 6; ++p) { var frustumPlane = frustumPlanes[p]; for (var 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 * @return true if there is an intersection */ BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) { for (var p = 0; p < 6; ++p) { var canReturnFalse = true; var frustumPlane = frustumPlanes[p]; for (var i = 0; i < 8; ++i) { if (frustumPlane.dotCoordinate(boundingVectors[i]) >= 0) { canReturnFalse = false; break; } } if (canReturnFalse) { return false; } } return true; }; BoundingBox.TmpVector3 = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(3, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero); return BoundingBox; }()); /***/ }), /***/ "./Culling/boundingInfo.ts": /*!*********************************!*\ !*** ./Culling/boundingInfo.ts ***! \*********************************/ /*! exports provided: BoundingInfo */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoundingInfo", function() { return BoundingInfo; }); /* harmony import */ var _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/arrayTools */ "./Misc/arrayTools.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); /* harmony import */ var _boundingBox__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./boundingBox */ "./Culling/boundingBox.ts"); /* harmony import */ var _boundingSphere__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./boundingSphere */ "./Culling/boundingSphere.ts"); var _result0 = { min: 0, max: 0 }; var _result1 = { min: 0, max: 0 }; var computeBoxExtents = function (axis, box, result) { var p = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(box.centerWorld, axis); var r0 = Math.abs(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(box.directions[0], axis)) * box.extendSize.x; var r1 = Math.abs(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(box.directions[1], axis)) * box.extendSize.y; var r2 = Math.abs(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(box.directions[2], axis)) * box.extendSize.z; var r = r0 + r1 + r2; result.min = p - r; result.max = p + r; }; var axisOverlap = function (axis, box0, box1) { computeBoxExtents(axis, box0, _result0); computeBoxExtents(axis, box1, _result1); return !(_result0.min > _result1.max || _result1.min > _result0.max); }; /** * Info for a bounding data of a mesh */ var BoundingInfo = /** @class */ (function () { /** * 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 */ function BoundingInfo(minimum, maximum, worldMatrix) { this._isLocked = false; this.boundingBox = new _boundingBox__WEBPACK_IMPORTED_MODULE_3__["BoundingBox"](minimum, maximum, worldMatrix); this.boundingSphere = new _boundingSphere__WEBPACK_IMPORTED_MODULE_4__["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 */ BoundingInfo.prototype.reConstruct = function (min, max, worldMatrix) { this.boundingBox.reConstruct(min, max, worldMatrix); this.boundingSphere.reConstruct(min, max, worldMatrix); }; Object.defineProperty(BoundingInfo.prototype, "minimum", { /** * min vector of the bounding box/sphere */ get: function () { return this.boundingBox.minimum; }, enumerable: true, configurable: true }); Object.defineProperty(BoundingInfo.prototype, "maximum", { /** * max vector of the bounding box/sphere */ get: function () { return this.boundingBox.maximum; }, enumerable: true, configurable: true }); Object.defineProperty(BoundingInfo.prototype, "isLocked", { /** * If the info is locked and won't be updated to avoid perf overhead */ get: function () { return this._isLocked; }, set: function (value) { this._isLocked = value; }, enumerable: true, configurable: true }); // Methods /** * Updates the bounding sphere and box * @param world world matrix to be used to update */ BoundingInfo.prototype.update = function (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 */ BoundingInfo.prototype.centerOn = function (center, extend) { var minimum = BoundingInfo.TmpVector3[0].copyFrom(center).subtractInPlace(extend); var 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; }; /** * Scale the current bounding info by applying a scale factor * @param factor defines the scale factor to apply * @returns the current bounding info */ BoundingInfo.prototype.scale = function (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) * @returns true if the bounding info is in the frustum planes */ BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) { if (strategy === void 0) { strategy = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].MESHES_CULLINGSTRATEGY_STANDARD; } var inclusionTest = (strategy === _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION || strategy === _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY); if (inclusionTest) { if (this.boundingSphere.isCenterInFrustum(frustumPlanes)) { return true; } } if (!this.boundingSphere.isInFrustum(frustumPlanes)) { return false; } var bSphereOnlyTest = (strategy === _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY || strategy === _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY); if (bSphereOnlyTest) { return true; } return this.boundingBox.isInFrustum(frustumPlanes); }; Object.defineProperty(BoundingInfo.prototype, "diagonalLength", { /** * Gets the world distance between the min and max points of the bounding box */ get: function () { var boundingBox = this.boundingBox; var diag = boundingBox.maximumWorld.subtractToRef(boundingBox.minimumWorld, BoundingInfo.TmpVector3[0]); return diag.length(); }, enumerable: true, configurable: true }); /** * Checks if a cullable object (mesh...) is in the camera frustum * Unlike isInFrustum this cheks the full bounding box * @param frustumPlanes Camera near/planes * @returns true if the object is in frustum otherwise false */ BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) { return this.boundingBox.isCompletelyInFrustum(frustumPlanes); }; /** @hidden */ BoundingInfo.prototype._checkCollision = function (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/babylon101/intersect_collisions_-_mesh * @param point the point to check intersection with * @returns if the point intersects */ BoundingInfo.prototype.intersectsPoint = function (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/babylon101/intersect_collisions_-_mesh * @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 */ BoundingInfo.prototype.intersects = function (boundingInfo, precise) { if (!_boundingSphere__WEBPACK_IMPORTED_MODULE_4__["BoundingSphere"].Intersects(this.boundingSphere, boundingInfo.boundingSphere)) { return false; } if (!_boundingBox__WEBPACK_IMPORTED_MODULE_3__["BoundingBox"].Intersects(this.boundingBox, boundingInfo.boundingBox)) { return false; } if (!precise) { return true; } var box0 = this.boundingBox; var 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(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[0], box1.directions[0]), box0, box1)) { return false; } if (!axisOverlap(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[0], box1.directions[1]), box0, box1)) { return false; } if (!axisOverlap(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[0], box1.directions[2]), box0, box1)) { return false; } if (!axisOverlap(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[1], box1.directions[0]), box0, box1)) { return false; } if (!axisOverlap(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[1], box1.directions[1]), box0, box1)) { return false; } if (!axisOverlap(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[1], box1.directions[2]), box0, box1)) { return false; } if (!axisOverlap(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[2], box1.directions[0]), box0, box1)) { return false; } if (!axisOverlap(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[2], box1.directions[1]), box0, box1)) { return false; } if (!axisOverlap(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[2], box1.directions[2]), box0, box1)) { return false; } return true; }; BoundingInfo.TmpVector3 = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(2, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero); return BoundingInfo; }()); /***/ }), /***/ "./Culling/boundingSphere.ts": /*!***********************************!*\ !*** ./Culling/boundingSphere.ts ***! \***********************************/ /*! exports provided: BoundingSphere */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoundingSphere", function() { return BoundingSphere; }); /* harmony import */ var _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/arrayTools */ "./Misc/arrayTools.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /** * Class used to store bounding sphere information */ var BoundingSphere = /** @class */ (function () { /** * 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 */ function BoundingSphere(min, max, worldMatrix) { /** * Gets the center of the bounding sphere in local space */ this.center = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); /** * Gets the center of the bounding sphere in world space */ this.centerWorld = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); /** * Gets the minimum vector in local space */ this.minimum = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); /** * Gets the maximum vector in local space */ this.maximum = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["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 */ BoundingSphere.prototype.reConstruct = function (min, max, worldMatrix) { this.minimum.copyFrom(min); this.maximum.copyFrom(max); var distance = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Distance(min, max); max.addToRef(min, this.center).scaleInPlace(0.5); this.radius = distance * 0.5; this._update(worldMatrix || _Maths_math__WEBPACK_IMPORTED_MODULE_1__["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 */ BoundingSphere.prototype.scale = function (factor) { var newRadius = this.radius * factor; var tmpVectors = BoundingSphere.TmpVector3; var tempRadiusVector = tmpVectors[0].setAll(newRadius); var min = this.center.subtractToRef(tempRadiusVector, tmpVectors[1]); var 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 */ BoundingSphere.prototype.getWorldMatrix = function () { return this._worldMatrix; }; // Methods /** @hidden */ BoundingSphere.prototype._update = function (worldMatrix) { if (!worldMatrix.isIdentity()) { _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(this.center, worldMatrix, this.centerWorld); var tempVector = BoundingSphere.TmpVector3[0]; _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, worldMatrix, tempVector); this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius; } else { this.centerWorld.copyFrom(this.center); this.radiusWorld = this.radius; } }; /** * Tests if the bounding sphere is intersecting the frustum planes * @param frustumPlanes defines the frustum planes to test * @returns true if there is an intersection */ BoundingSphere.prototype.isInFrustum = function (frustumPlanes) { var center = this.centerWorld; var radius = this.radiusWorld; for (var 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 */ BoundingSphere.prototype.isCenterInFrustum = function (frustumPlanes) { var center = this.centerWorld; for (var 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 */ BoundingSphere.prototype.intersectsPoint = function (point) { var squareDistance = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].DistanceSquared(this.centerWorld, point); if (this.radiusWorld * this.radiusWorld < squareDistance) { return false; } return true; }; // Statics /** * Checks if two sphere intersct * @param sphere0 sphere 0 * @param sphere1 sphere 1 * @returns true if the speres intersect */ BoundingSphere.Intersects = function (sphere0, sphere1) { var squareDistance = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].DistanceSquared(sphere0.centerWorld, sphere1.centerWorld); var radiusSum = sphere0.radiusWorld + sphere1.radiusWorld; if (radiusSum * radiusSum < squareDistance) { return false; } return true; }; BoundingSphere.TmpVector3 = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(3, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero); return BoundingSphere; }()); /***/ }), /***/ "./Culling/index.ts": /*!**************************!*\ !*** ./Culling/index.ts ***! \**************************/ /*! exports provided: BoundingBox, BoundingInfo, BoundingSphere, Ray, Octree, OctreeBlock, OctreeSceneComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _boundingBox__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./boundingBox */ "./Culling/boundingBox.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingBox", function() { return _boundingBox__WEBPACK_IMPORTED_MODULE_0__["BoundingBox"]; }); /* harmony import */ var _boundingInfo__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./boundingInfo */ "./Culling/boundingInfo.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingInfo", function() { return _boundingInfo__WEBPACK_IMPORTED_MODULE_1__["BoundingInfo"]; }); /* harmony import */ var _boundingSphere__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./boundingSphere */ "./Culling/boundingSphere.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingSphere", function() { return _boundingSphere__WEBPACK_IMPORTED_MODULE_2__["BoundingSphere"]; }); /* harmony import */ var _Octrees_index__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Octrees/index */ "./Culling/Octrees/index.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Octree", function() { return _Octrees_index__WEBPACK_IMPORTED_MODULE_3__["Octree"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OctreeBlock", function() { return _Octrees_index__WEBPACK_IMPORTED_MODULE_3__["OctreeBlock"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OctreeSceneComponent", function() { return _Octrees_index__WEBPACK_IMPORTED_MODULE_3__["OctreeSceneComponent"]; }); /* harmony import */ var _ray__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./ray */ "./Culling/ray.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Ray", function() { return _ray__WEBPACK_IMPORTED_MODULE_4__["Ray"]; }); /***/ }), /***/ "./Culling/ray.ts": /*!************************!*\ !*** ./Culling/ray.ts ***! \************************/ /*! exports provided: Ray */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Ray", function() { return Ray; }); /* harmony import */ var _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/arrayTools */ "./Misc/arrayTools.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Collisions_pickingInfo__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Collisions/pickingInfo */ "./Collisions/pickingInfo.ts"); /* harmony import */ var _Collisions_intersectionInfo__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Collisions/intersectionInfo */ "./Collisions/intersectionInfo.ts"); /* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../scene */ "./scene.ts"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Cameras/camera */ "./Cameras/camera.ts"); /** * Class representing a ray with position and direction */ var Ray = /** @class */ (function () { /** * Creates a new ray * @param origin origin point * @param direction direction * @param length length of the ray */ function Ray( /** origin point */ origin, /** direction */ direction, /** length of the ray */ length) { if (length === void 0) { length = Number.MAX_VALUE; } this.origin = origin; this.direction = direction; this.length = length; } // Methods /** * Checks if the ray intersects a box * @param minimum bound of the box * @param maximum bound of the box * @param intersectionTreshold extra extend to be added to the box in all direction * @returns if the box was hit */ Ray.prototype.intersectsBoxMinMax = function (minimum, maximum, intersectionTreshold) { if (intersectionTreshold === void 0) { intersectionTreshold = 0; } var newMinimum = Ray.TmpVector3[0].copyFromFloats(minimum.x - intersectionTreshold, minimum.y - intersectionTreshold, minimum.z - intersectionTreshold); var newMaximum = Ray.TmpVector3[1].copyFromFloats(maximum.x + intersectionTreshold, maximum.y + intersectionTreshold, maximum.z + intersectionTreshold); var d = 0.0; var maxValue = Number.MAX_VALUE; var inv; var min; var max; var temp; if (Math.abs(this.direction.x) < 0.0000001) { if (this.origin.x < newMinimum.x || this.origin.x > newMaximum.x) { return false; } } else { inv = 1.0 / this.direction.x; min = (newMinimum.x - this.origin.x) * inv; max = (newMaximum.x - this.origin.x) * inv; if (max === -Infinity) { max = Infinity; } if (min > max) { temp = min; min = max; max = temp; } d = Math.max(min, d); maxValue = Math.min(max, maxValue); if (d > maxValue) { return false; } } if (Math.abs(this.direction.y) < 0.0000001) { if (this.origin.y < newMinimum.y || this.origin.y > newMaximum.y) { return false; } } else { inv = 1.0 / this.direction.y; min = (newMinimum.y - this.origin.y) * inv; max = (newMaximum.y - this.origin.y) * inv; if (max === -Infinity) { max = Infinity; } if (min > max) { temp = min; min = max; max = temp; } d = Math.max(min, d); maxValue = Math.min(max, maxValue); if (d > maxValue) { return false; } } if (Math.abs(this.direction.z) < 0.0000001) { if (this.origin.z < newMinimum.z || this.origin.z > newMaximum.z) { return false; } } else { inv = 1.0 / this.direction.z; min = (newMinimum.z - this.origin.z) * inv; max = (newMaximum.z - this.origin.z) * inv; if (max === -Infinity) { max = Infinity; } if (min > max) { temp = min; min = max; max = temp; } d = Math.max(min, d); maxValue = Math.min(max, maxValue); if (d > maxValue) { return false; } } return true; }; /** * Checks if the ray intersects a box * @param box the bounding box to check * @param intersectionTreshold extra extend to be added to the BoundingBox in all direction * @returns if the box was hit */ Ray.prototype.intersectsBox = function (box, intersectionTreshold) { if (intersectionTreshold === void 0) { intersectionTreshold = 0; } return this.intersectsBoxMinMax(box.minimum, box.maximum, intersectionTreshold); }; /** * If the ray hits a sphere * @param sphere the bounding sphere to check * @param intersectionTreshold extra extend to be added to the BoundingSphere in all direction * @returns true if it hits the sphere */ Ray.prototype.intersectsSphere = function (sphere, intersectionTreshold) { if (intersectionTreshold === void 0) { intersectionTreshold = 0; } var x = sphere.center.x - this.origin.x; var y = sphere.center.y - this.origin.y; var z = sphere.center.z - this.origin.z; var pyth = (x * x) + (y * y) + (z * z); var radius = sphere.radius + intersectionTreshold; var rr = radius * radius; if (pyth <= rr) { return true; } var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z); if (dot < 0.0) { return false; } var temp = pyth - (dot * dot); return temp <= rr; }; /** * If the ray hits a triange * @param vertex0 triangle vertex * @param vertex1 triangle vertex * @param vertex2 triangle vertex * @returns intersection information if hit */ Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) { var edge1 = Ray.TmpVector3[0]; var edge2 = Ray.TmpVector3[1]; var pvec = Ray.TmpVector3[2]; var tvec = Ray.TmpVector3[3]; var qvec = Ray.TmpVector3[4]; vertex1.subtractToRef(vertex0, edge1); vertex2.subtractToRef(vertex0, edge2); _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].CrossToRef(this.direction, edge2, pvec); var det = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(edge1, pvec); if (det === 0) { return null; } var invdet = 1 / det; this.origin.subtractToRef(vertex0, tvec); var bu = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(tvec, pvec) * invdet; if (bu < 0 || bu > 1.0) { return null; } _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].CrossToRef(tvec, edge1, qvec); var bv = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(this.direction, qvec) * invdet; if (bv < 0 || bu + bv > 1.0) { return null; } //check if the distance is longer than the predefined length. var distance = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(edge2, qvec) * invdet; if (distance > this.length) { return null; } return new _Collisions_intersectionInfo__WEBPACK_IMPORTED_MODULE_3__["IntersectionInfo"](bu, bv, distance); }; /** * Checks if ray intersects a plane * @param plane the plane to check * @returns the distance away it was hit */ Ray.prototype.intersectsPlane = function (plane) { var distance; var result1 = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(plane.normal, this.direction); if (Math.abs(result1) < 9.99999997475243E-07) { return null; } else { var result2 = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(plane.normal, this.origin); distance = (-plane.d - result2) / result1; if (distance < 0.0) { if (distance < -9.99999997475243E-07) { return null; } else { return 0; } } return distance; } }; /** * Checks if ray intersects a mesh * @param mesh the mesh to check * @param fastCheck if only the bounding box should checked * @returns picking info of the intersecton */ Ray.prototype.intersectsMesh = function (mesh, fastCheck) { var tm = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Matrix[0]; mesh.getWorldMatrix().invertToRef(tm); if (this._tmpRay) { Ray.TransformToRef(this, tm, this._tmpRay); } else { this._tmpRay = Ray.Transform(this, tm); } return mesh.intersects(this._tmpRay, fastCheck); }; /** * Checks if ray intersects a mesh * @param meshes the meshes to check * @param fastCheck if only the bounding box should checked * @param results array to store result in * @returns Array of picking infos */ Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) { if (results) { results.length = 0; } else { results = []; } for (var i = 0; i < meshes.length; i++) { var pickInfo = this.intersectsMesh(meshes[i], fastCheck); if (pickInfo.hit) { results.push(pickInfo); } } results.sort(this._comparePickingInfo); return results; }; Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) { if (pickingInfoA.distance < pickingInfoB.distance) { return -1; } else if (pickingInfoA.distance > pickingInfoB.distance) { return 1; } else { return 0; } }; /** * Intersection test between the ray and a given segment whithin a given tolerance (threshold) * @param sega the first point of the segment to test the intersection against * @param segb the second point of the segment to test the intersection against * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection */ Ray.prototype.intersectionSegment = function (sega, segb, threshold) { var o = this.origin; var u = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[0]; var rsegb = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[1]; var v = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[2]; var w = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[3]; segb.subtractToRef(sega, u); this.direction.scaleToRef(Ray.rayl, v); o.addToRef(v, rsegb); sega.subtractToRef(o, w); var a = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(u, u); // always >= 0 var b = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(u, v); var c = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(v, v); // always >= 0 var d = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(u, w); var e = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(v, w); var D = a * c - b * b; // always >= 0 var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0 var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0 // compute the line parameters of the two closest points if (D < Ray.smallnum) { // the lines are almost parallel sN = 0.0; // force using point P0 on segment S1 sD = 1.0; // to prevent possible division by 0.0 later tN = e; tD = c; } else { // get the closest points on the infinite lines sN = (b * e - c * d); tN = (a * e - b * d); if (sN < 0.0) { // sc < 0 => the s=0 edge is visible sN = 0.0; tN = e; tD = c; } else if (sN > sD) { // sc > 1 => the s=1 edge is visible sN = sD; tN = e + b; tD = c; } } if (tN < 0.0) { // tc < 0 => the t=0 edge is visible tN = 0.0; // recompute sc for this edge if (-d < 0.0) { sN = 0.0; } else if (-d > a) { sN = sD; } else { sN = -d; sD = a; } } else if (tN > tD) { // tc > 1 => the t=1 edge is visible tN = tD; // recompute sc for this edge if ((-d + b) < 0.0) { sN = 0; } else if ((-d + b) > a) { sN = sD; } else { sN = (-d + b); sD = a; } } // finally do the division to get sc and tc sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD); tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD); // get the difference of the two closest points var qtc = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[4]; v.scaleToRef(tc, qtc); var qsc = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[5]; u.scaleToRef(sc, qsc); qsc.addInPlace(w); var dP = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[6]; qsc.subtractToRef(qtc, dP); // = S1(sc) - S2(tc) var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result if (isIntersected) { return qsc.length(); } return -1; }; /** * Update the ray from viewport position * @param x position * @param y y position * @param viewportWidth viewport width * @param viewportHeight viewport height * @param world world matrix * @param view view matrix * @param projection projection matrix * @returns this ray updated */ Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) { this.unprojectRayToRef(x, y, viewportWidth, viewportHeight, world, view, projection); return this; }; // Statics /** * Creates a ray with origin and direction of 0,0,0 * @returns the new ray */ Ray.Zero = function () { return new Ray(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(), _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero()); }; /** * Creates a new ray from screen space and viewport * @param x position * @param y y position * @param viewportWidth viewport width * @param viewportHeight viewport height * @param world world matrix * @param view view matrix * @param projection projection matrix * @returns new ray */ Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) { var result = Ray.Zero(); return result.update(x, y, viewportWidth, viewportHeight, world, view, projection); }; /** * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be * transformed to the given world matrix. * @param origin The origin point * @param end The end point * @param world a matrix to transform the ray to. Default is the identity matrix. * @returns the new ray */ Ray.CreateNewFromTo = function (origin, end, world) { if (world === void 0) { world = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].IdentityReadOnly; } var direction = end.subtract(origin); var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z)); direction.normalize(); return Ray.Transform(new Ray(origin, direction, length), world); }; /** * Transforms a ray by a matrix * @param ray ray to transform * @param matrix matrix to apply * @returns the resulting new ray */ Ray.Transform = function (ray, matrix) { var result = new Ray(new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, 0), new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, 0)); Ray.TransformToRef(ray, matrix, result); return result; }; /** * Transforms a ray by a matrix * @param ray ray to transform * @param matrix matrix to apply * @param result ray to store result in */ Ray.TransformToRef = function (ray, matrix, result) { _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(ray.origin, matrix, result.origin); _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformNormalToRef(ray.direction, matrix, result.direction); result.length = ray.length; var dir = result.direction; var len = dir.length(); if (!(len === 0 || len === 1)) { var num = 1.0 / len; dir.x *= num; dir.y *= num; dir.z *= num; result.length *= len; } }; /** * Unproject a ray from screen space to object space * @param sourceX defines the screen space x coordinate to use * @param sourceY defines the screen space y 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 */ Ray.prototype.unprojectRayToRef = function (sourceX, sourceY, viewportWidth, viewportHeight, world, view, projection) { var matrix = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Matrix[0]; world.multiplyToRef(view, matrix); matrix.multiplyToRef(projection, matrix); matrix.invert(); var nearScreenSource = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[0]; nearScreenSource.x = sourceX / viewportWidth * 2 - 1; nearScreenSource.y = -(sourceY / viewportHeight * 2 - 1); nearScreenSource.z = -1.0; var farScreenSource = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[1].copyFromFloats(nearScreenSource.x, nearScreenSource.y, 1.0); var nearVec3 = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[2]; var farVec3 = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Tmp"].Vector3[3]; _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"]._UnprojectFromInvertedMatrixToRef(nearScreenSource, matrix, nearVec3); _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"]._UnprojectFromInvertedMatrixToRef(farScreenSource, matrix, farVec3); this.origin.copyFrom(nearVec3); farVec3.subtractToRef(nearVec3, this.direction); this.direction.normalize(); }; Ray.TmpVector3 = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(6, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero); Ray.smallnum = 0.00000001; Ray.rayl = 10e8; return Ray; }()); _scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) { if (cameraViewSpace === void 0) { cameraViewSpace = false; } var result = Ray.Zero(); this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace); return result; }; _scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) { if (cameraViewSpace === void 0) { cameraViewSpace = false; } var engine = this.getEngine(); if (!camera) { if (!this.activeCamera) { throw new Error("Active camera not set"); } camera = this.activeCamera; } var cameraViewport = camera.viewport; var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight()); // Moving coordinates to local viewport world x = x / engine.getHardwareScalingLevel() - viewport.x; y = y / engine.getHardwareScalingLevel() - (engine.getRenderHeight() - viewport.y - viewport.height); result.update(x, y, viewport.width, viewport.height, world ? world : _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].IdentityReadOnly, cameraViewSpace ? _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].IdentityReadOnly : camera.getViewMatrix(), camera.getProjectionMatrix()); return this; }; _scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.createPickingRayInCameraSpace = function (x, y, camera) { var result = Ray.Zero(); this.createPickingRayInCameraSpaceToRef(x, y, result, camera); return result; }; _scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) { if (!_Collisions_pickingInfo__WEBPACK_IMPORTED_MODULE_2__["PickingInfo"]) { return this; } var engine = this.getEngine(); if (!camera) { if (!this.activeCamera) { throw new Error("Active camera not set"); } camera = this.activeCamera; } var cameraViewport = camera.viewport; var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight()); var identity = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(); // Moving coordinates to local viewport world x = x / engine.getHardwareScalingLevel() - viewport.x; y = y / engine.getHardwareScalingLevel() - (engine.getRenderHeight() - viewport.y - viewport.height); result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix()); return this; }; _scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype._internalPick = function (rayFunction, predicate, fastCheck, trianglePredicate) { if (!_Collisions_pickingInfo__WEBPACK_IMPORTED_MODULE_2__["PickingInfo"]) { return null; } var pickingInfo = null; for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) { var mesh = this.meshes[meshIndex]; if (predicate) { if (!predicate(mesh)) { continue; } } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) { continue; } var world = mesh.getWorldMatrix(); var ray = rayFunction(world); var result = mesh.intersects(ray, fastCheck, trianglePredicate); if (!result || !result.hit) { continue; } if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) { continue; } pickingInfo = result; if (fastCheck) { break; } } return pickingInfo || new _Collisions_pickingInfo__WEBPACK_IMPORTED_MODULE_2__["PickingInfo"](); }; _scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype._internalMultiPick = function (rayFunction, predicate, trianglePredicate) { if (!_Collisions_pickingInfo__WEBPACK_IMPORTED_MODULE_2__["PickingInfo"]) { return null; } var pickingInfos = new Array(); for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) { var mesh = this.meshes[meshIndex]; if (predicate) { if (!predicate(mesh)) { continue; } } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) { continue; } var world = mesh.getWorldMatrix(); var ray = rayFunction(world); var result = mesh.intersects(ray, false, trianglePredicate); if (!result || !result.hit) { continue; } pickingInfos.push(result); } return pickingInfos; }; _scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.pick = function (x, y, predicate, fastCheck, camera, trianglePredicate) { var _this = this; if (!_Collisions_pickingInfo__WEBPACK_IMPORTED_MODULE_2__["PickingInfo"]) { return null; } var result = this._internalPick(function (world) { if (!_this._tempPickingRay) { _this._tempPickingRay = Ray.Zero(); } _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null); return _this._tempPickingRay; }, predicate, fastCheck, trianglePredicate); if (result) { result.ray = this.createPickingRay(x, y, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(), camera || null); } return result; }; _scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.pickWithRay = function (ray, predicate, fastCheck, trianglePredicate) { var _this = this; var result = this._internalPick(function (world) { if (!_this._pickWithRayInverseMatrix) { _this._pickWithRayInverseMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(); } world.invertToRef(_this._pickWithRayInverseMatrix); if (!_this._cachedRayForTransform) { _this._cachedRayForTransform = Ray.Zero(); } Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform); return _this._cachedRayForTransform; }, predicate, fastCheck, trianglePredicate); if (result) { result.ray = ray; } return result; }; _scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.multiPick = function (x, y, predicate, camera, trianglePredicate) { var _this = this; return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate, trianglePredicate); }; _scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.multiPickWithRay = function (ray, predicate, trianglePredicate) { var _this = this; return this._internalMultiPick(function (world) { if (!_this._pickWithRayInverseMatrix) { _this._pickWithRayInverseMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(); } world.invertToRef(_this._pickWithRayInverseMatrix); if (!_this._cachedRayForTransform) { _this._cachedRayForTransform = Ray.Zero(); } Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform); return _this._cachedRayForTransform; }, predicate, trianglePredicate); }; _Cameras_camera__WEBPACK_IMPORTED_MODULE_5__["Camera"].prototype.getForwardRay = function (length, transform, origin) { if (length === void 0) { length = 100; } if (!transform) { transform = this.getWorldMatrix(); } if (!origin) { origin = this.position; } var forward = this._scene.useRightHandedSystem ? new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, -1) : new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, 1); var forwardWorld = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformNormal(forward, transform); var direction = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Normalize(forwardWorld); return new Ray(origin, direction, length); }; /***/ }), /***/ "./Debug/axesViewer.ts": /*!*****************************!*\ !*** ./Debug/axesViewer.ts ***! \*****************************/ /*! exports provided: AxesViewer */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AxesViewer", function() { return AxesViewer; }); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts"); /* harmony import */ var _Gizmos_axisDragGizmo__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Gizmos/axisDragGizmo */ "./Gizmos/axisDragGizmo.ts"); /** * The Axes viewer will show 3 axes in a specific point in space */ var AxesViewer = /** @class */ (function () { /** * Creates a new AxesViewer * @param scene defines the hosting scene * @param scaleLines defines a number used to scale line length (1 by default) * @param renderingGroupId defines a number used to set the renderingGroupId of the meshes (2 by default) * @param xAxis defines the node hierarchy used to render the x-axis * @param yAxis defines the node hierarchy used to render the y-axis * @param zAxis defines the node hierarchy used to render the z-axis */ function AxesViewer(scene, scaleLines, renderingGroupId, xAxis, yAxis, zAxis) { if (scaleLines === void 0) { scaleLines = 1; } if (renderingGroupId === void 0) { renderingGroupId = 2; } this._scaleLinesFactor = 4; this._instanced = false; /** * Gets or sets a number used to scale line length */ this.scaleLines = 1; this.scaleLines = scaleLines; if (!xAxis) { var redColoredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_1__["StandardMaterial"]("", scene); redColoredMaterial.disableLighting = true; redColoredMaterial.emissiveColor = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].Red().scale(0.5); xAxis = _Gizmos_axisDragGizmo__WEBPACK_IMPORTED_MODULE_2__["AxisDragGizmo"]._CreateArrow(scene, redColoredMaterial); } if (!yAxis) { var greenColoredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_1__["StandardMaterial"]("", scene); greenColoredMaterial.disableLighting = true; greenColoredMaterial.emissiveColor = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].Green().scale(0.5); yAxis = _Gizmos_axisDragGizmo__WEBPACK_IMPORTED_MODULE_2__["AxisDragGizmo"]._CreateArrow(scene, greenColoredMaterial); } if (!zAxis) { var blueColoredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_1__["StandardMaterial"]("", scene); blueColoredMaterial.disableLighting = true; blueColoredMaterial.emissiveColor = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].Blue().scale(0.5); zAxis = _Gizmos_axisDragGizmo__WEBPACK_IMPORTED_MODULE_2__["AxisDragGizmo"]._CreateArrow(scene, blueColoredMaterial); } this._xAxis = xAxis; this._xAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor); this._yAxis = yAxis; this._yAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor); this._zAxis = zAxis; this._zAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor); if (renderingGroupId != null) { AxesViewer._SetRenderingGroupId(this._xAxis, renderingGroupId); AxesViewer._SetRenderingGroupId(this._yAxis, renderingGroupId); AxesViewer._SetRenderingGroupId(this._zAxis, renderingGroupId); } this.scene = scene; this.update(new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](), _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Right(), _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Up(), _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Forward()); } Object.defineProperty(AxesViewer.prototype, "xAxis", { /** Gets the node hierarchy used to render x-axis */ get: function () { return this._xAxis; }, enumerable: true, configurable: true }); Object.defineProperty(AxesViewer.prototype, "yAxis", { /** Gets the node hierarchy used to render y-axis */ get: function () { return this._yAxis; }, enumerable: true, configurable: true }); Object.defineProperty(AxesViewer.prototype, "zAxis", { /** Gets the node hierarchy used to render z-axis */ get: function () { return this._zAxis; }, enumerable: true, configurable: true }); /** * Force the viewer to update * @param position defines the position of the viewer * @param xaxis defines the x axis of the viewer * @param yaxis defines the y axis of the viewer * @param zaxis defines the z axis of the viewer */ AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) { this._xAxis.position.copyFrom(position); this._xAxis.setDirection(xaxis); this._xAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor); this._yAxis.position.copyFrom(position); this._yAxis.setDirection(yaxis); this._yAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor); this._zAxis.position.copyFrom(position); this._zAxis.setDirection(zaxis); this._zAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor); }; /** * Creates an instance of this axes viewer. * @returns a new axes viewer with instanced meshes */ AxesViewer.prototype.createInstance = function () { var xAxis = _Gizmos_axisDragGizmo__WEBPACK_IMPORTED_MODULE_2__["AxisDragGizmo"]._CreateArrowInstance(this.scene, this._xAxis); var yAxis = _Gizmos_axisDragGizmo__WEBPACK_IMPORTED_MODULE_2__["AxisDragGizmo"]._CreateArrowInstance(this.scene, this._yAxis); var zAxis = _Gizmos_axisDragGizmo__WEBPACK_IMPORTED_MODULE_2__["AxisDragGizmo"]._CreateArrowInstance(this.scene, this._zAxis); var axesViewer = new AxesViewer(this.scene, this.scaleLines, null, xAxis, yAxis, zAxis); axesViewer._instanced = true; return axesViewer; }; /** Releases resources */ AxesViewer.prototype.dispose = function () { if (this._xAxis) { this._xAxis.dispose(false, !this._instanced); delete this._xAxis; } if (this._yAxis) { this._yAxis.dispose(false, !this._instanced); delete this._yAxis; } if (this._zAxis) { this._zAxis.dispose(false, !this._instanced); delete this._zAxis; } delete this.scene; }; AxesViewer._SetRenderingGroupId = function (node, id) { node.getChildMeshes().forEach(function (mesh) { mesh.renderingGroupId = id; }); }; return AxesViewer; }()); /***/ }), /***/ "./Debug/boneAxesViewer.ts": /*!*********************************!*\ !*** ./Debug/boneAxesViewer.ts ***! \*********************************/ /*! exports provided: BoneAxesViewer */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoneAxesViewer", function() { return BoneAxesViewer; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Debug_axesViewer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Debug/axesViewer */ "./Debug/axesViewer.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /** * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8 */ var BoneAxesViewer = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BoneAxesViewer, _super); /** * Creates a new BoneAxesViewer * @param scene defines the hosting scene * @param bone defines the target bone * @param mesh defines the target mesh * @param scaleLines defines a scaling factor for line length (1 by default) */ function BoneAxesViewer(scene, bone, mesh, scaleLines) { if (scaleLines === void 0) { scaleLines = 1; } var _this = _super.call(this, scene, scaleLines) || this; /** Gets current position */ _this.pos = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); /** Gets direction of X axis */ _this.xaxis = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); /** Gets direction of Y axis */ _this.yaxis = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); /** Gets direction of Z axis */ _this.zaxis = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); _this.mesh = mesh; _this.bone = bone; return _this; } /** * Force the viewer to update */ BoneAxesViewer.prototype.update = function () { if (!this.mesh || !this.bone) { return; } var bone = this.bone; bone.getAbsolutePositionToRef(this.mesh, this.pos); bone.getDirectionToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Axis"].X, this.mesh, this.xaxis); bone.getDirectionToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Axis"].Y, this.mesh, this.yaxis); bone.getDirectionToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Axis"].Z, this.mesh, this.zaxis); _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis); }; /** Releases resources */ BoneAxesViewer.prototype.dispose = function () { if (this.mesh) { this.mesh = null; this.bone = null; _super.prototype.dispose.call(this); } }; return BoneAxesViewer; }(_Debug_axesViewer__WEBPACK_IMPORTED_MODULE_1__["AxesViewer"])); /***/ }), /***/ "./Debug/debugLayer.ts": /*!*****************************!*\ !*** ./Debug/debugLayer.ts ***! \*****************************/ /*! exports provided: DebugLayer */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DebugLayer", function() { return DebugLayer; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../scene */ "./scene.ts"); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); Object.defineProperty(_scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype, "debugLayer", { get: function () { if (!this._debugLayer) { this._debugLayer = new DebugLayer(this); } return this._debugLayer; }, enumerable: true, configurable: true }); /** * The debug layer (aka Inspector) is the go to tool in order to better understand * what is happening in your scene * @see http://doc.babylonjs.com/features/playground_debuglayer */ var DebugLayer = /** @class */ (function () { /** * Instantiates a new debug layer. * The debug layer (aka Inspector) is the go to tool in order to better understand * what is happening in your scene * @see http://doc.babylonjs.com/features/playground_debuglayer * @param scene Defines the scene to inspect */ function DebugLayer(scene) { var _this = this; this.BJSINSPECTOR = this._getGlobalInspector(); /** * Observable triggered when a property is changed through the inspector. */ this.onPropertyChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); this._scene = scene; this._scene.onDisposeObservable.add(function () { // Debug layer if (_this._scene._debugLayer) { _this._scene._debugLayer.hide(); } }); } /** Creates the inspector window. */ DebugLayer.prototype._createInspector = function (config) { if (this.isVisible()) { return; } var userOptions = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ overlay: false, showExplorer: true, showInspector: true, embedMode: false, handleResize: true, enablePopup: true }, config); this.BJSINSPECTOR = this.BJSINSPECTOR || this._getGlobalInspector(); this.BJSINSPECTOR.Inspector.Show(this._scene, userOptions); }; /** * Select a specific entity in the scene explorer and highlight a specific block in that entity property grid * @param entity defines the entity to select * @param lineContainerTitle defines the specific block to highlight */ DebugLayer.prototype.select = function (entity, lineContainerTitle) { if (this.BJSINSPECTOR) { this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(lineContainerTitle); this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(entity); } }; /** Get the inspector from bundle or global */ DebugLayer.prototype._getGlobalInspector = function () { // UMD Global name detection from Webpack Bundle UMD Name. if (typeof INSPECTOR !== 'undefined') { return INSPECTOR; } // In case of module let s check the global emitted from the Inspector entry point. if (typeof BABYLON !== 'undefined' && typeof BABYLON.Inspector !== 'undefined') { return BABYLON; } return undefined; }; /** * Get if the inspector is visible or not. * @returns true if visible otherwise, false */ DebugLayer.prototype.isVisible = function () { return this.BJSINSPECTOR && this.BJSINSPECTOR.Inspector.IsVisible; }; /** * Hide the inspector and close its window. */ DebugLayer.prototype.hide = function () { if (this.BJSINSPECTOR) { this.BJSINSPECTOR.Inspector.Hide(); } }; /** * Launch the debugLayer. * @param config Define the configuration of the inspector * @return a promise fulfilled when the debug layer is visible */ DebugLayer.prototype.show = function (config) { var _this = this; return new Promise(function (resolve, reject) { if (typeof _this.BJSINSPECTOR == 'undefined') { var inspectorUrl = config && config.inspectorURL ? config.inspectorURL : DebugLayer.InspectorURL; // Load inspector and add it to the DOM _Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Tools"].LoadScript(inspectorUrl, function () { _this._createInspector(config); resolve(_this); }); } else { // Otherwise creates the inspector _this._createInspector(config); resolve(_this); } }); }; /** * Define the url to get the inspector script from. * By default it uses the babylonjs CDN. * @ignoreNaming */ DebugLayer.InspectorURL = "https://unpkg.com/babylonjs-inspector@" + _Engines_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].Version + "/babylon.inspector.bundle.js"; return DebugLayer; }()); /***/ }), /***/ "./Debug/index.ts": /*!************************!*\ !*** ./Debug/index.ts ***! \************************/ /*! exports provided: AxesViewer, BoneAxesViewer, DebugLayer, PhysicsViewer, RayHelper, SkeletonViewer */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _axesViewer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./axesViewer */ "./Debug/axesViewer.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AxesViewer", function() { return _axesViewer__WEBPACK_IMPORTED_MODULE_0__["AxesViewer"]; }); /* harmony import */ var _boneAxesViewer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./boneAxesViewer */ "./Debug/boneAxesViewer.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoneAxesViewer", function() { return _boneAxesViewer__WEBPACK_IMPORTED_MODULE_1__["BoneAxesViewer"]; }); /* harmony import */ var _debugLayer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./debugLayer */ "./Debug/debugLayer.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DebugLayer", function() { return _debugLayer__WEBPACK_IMPORTED_MODULE_2__["DebugLayer"]; }); /* harmony import */ var _physicsViewer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./physicsViewer */ "./Debug/physicsViewer.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsViewer", function() { return _physicsViewer__WEBPACK_IMPORTED_MODULE_3__["PhysicsViewer"]; }); /* harmony import */ var _rayHelper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./rayHelper */ "./Debug/rayHelper.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RayHelper", function() { return _rayHelper__WEBPACK_IMPORTED_MODULE_4__["RayHelper"]; }); /* harmony import */ var _skeletonViewer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./skeletonViewer */ "./Debug/skeletonViewer.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SkeletonViewer", function() { return _skeletonViewer__WEBPACK_IMPORTED_MODULE_5__["SkeletonViewer"]; }); /***/ }), /***/ "./Debug/physicsViewer.ts": /*!********************************!*\ !*** ./Debug/physicsViewer.ts ***! \********************************/ /*! exports provided: PhysicsViewer */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PhysicsViewer", function() { return PhysicsViewer; }); /* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts"); /* harmony import */ var _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Meshes/Builders/boxBuilder */ "./Meshes/Builders/boxBuilder.ts"); /* harmony import */ var _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Meshes/Builders/sphereBuilder */ "./Meshes/Builders/sphereBuilder.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts"); /* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts"); /* harmony import */ var _Physics_physicsImpostor__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Physics/physicsImpostor */ "./Physics/physicsImpostor.ts"); /* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts"); /* harmony import */ var _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Meshes/Builders/cylinderBuilder */ "./Meshes/Builders/cylinderBuilder.ts"); /** * Used to show the physics impostor around the specific mesh */ var PhysicsViewer = /** @class */ (function () { /** * Creates a new PhysicsViewer * @param scene defines the hosting scene */ function PhysicsViewer(scene) { /** @hidden */ this._impostors = []; /** @hidden */ this._meshes = []; /** @hidden */ this._numMeshes = 0; this._debugMeshMeshes = new Array(); this._scene = scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_4__["EngineStore"].LastCreatedScene; var physicEngine = this._scene.getPhysicsEngine(); if (physicEngine) { this._physicsEnginePlugin = physicEngine.getPhysicsPlugin(); } this._utilityLayer = new _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_7__["UtilityLayerRenderer"](this._scene, false); this._utilityLayer.pickUtilitySceneFirst = false; this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil = true; } /** @hidden */ PhysicsViewer.prototype._updateDebugMeshes = function () { var plugin = this._physicsEnginePlugin; for (var i = 0; i < this._numMeshes; i++) { var impostor = this._impostors[i]; if (!impostor) { continue; } if (impostor.isDisposed) { this.hideImpostor(this._impostors[i--]); } else { if (impostor.type === _Physics_physicsImpostor__WEBPACK_IMPORTED_MODULE_6__["PhysicsImpostor"].MeshImpostor) { continue; } var mesh = this._meshes[i]; if (mesh && plugin) { plugin.syncMeshWithImpostor(mesh, impostor); } } } }; /** * Renders a specified physic impostor * @param impostor defines the impostor to render * @param targetMesh defines the mesh represented by the impostor * @returns the new debug mesh used to render the impostor */ PhysicsViewer.prototype.showImpostor = function (impostor, targetMesh) { if (!this._scene) { return null; } for (var i = 0; i < this._numMeshes; i++) { if (this._impostors[i] == impostor) { return null; } } var debugMesh = this._getDebugMesh(impostor, targetMesh); if (debugMesh) { this._impostors[this._numMeshes] = impostor; this._meshes[this._numMeshes] = debugMesh; if (this._numMeshes === 0) { this._renderFunction = this._updateDebugMeshes.bind(this); this._scene.registerBeforeRender(this._renderFunction); } this._numMeshes++; } return debugMesh; }; /** * Hides a specified physic impostor * @param impostor defines the impostor to hide */ PhysicsViewer.prototype.hideImpostor = function (impostor) { if (!impostor || !this._scene || !this._utilityLayer) { return; } var removed = false; var utilityLayerScene = this._utilityLayer.utilityLayerScene; for (var i = 0; i < this._numMeshes; i++) { if (this._impostors[i] == impostor) { var mesh = this._meshes[i]; if (!mesh) { continue; } utilityLayerScene.removeMesh(mesh); mesh.dispose(); var index = this._debugMeshMeshes.indexOf(mesh); if (index > -1) { this._debugMeshMeshes.splice(index, 1); } this._numMeshes--; if (this._numMeshes > 0) { this._meshes[i] = this._meshes[this._numMeshes]; this._impostors[i] = this._impostors[this._numMeshes]; this._meshes[this._numMeshes] = null; this._impostors[this._numMeshes] = null; } else { this._meshes[0] = null; this._impostors[0] = null; } removed = true; break; } } if (removed && this._numMeshes === 0) { this._scene.unregisterBeforeRender(this._renderFunction); } }; PhysicsViewer.prototype._getDebugMaterial = function (scene) { if (!this._debugMaterial) { this._debugMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_5__["StandardMaterial"]('', scene); this._debugMaterial.wireframe = true; this._debugMaterial.emissiveColor = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].White(); this._debugMaterial.disableLighting = true; } return this._debugMaterial; }; PhysicsViewer.prototype._getDebugBoxMesh = function (scene) { if (!this._debugBoxMesh) { this._debugBoxMesh = _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_1__["BoxBuilder"].CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene); this._debugBoxMesh.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].Identity(); this._debugBoxMesh.material = this._getDebugMaterial(scene); this._debugBoxMesh.setEnabled(false); } return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance'); }; PhysicsViewer.prototype._getDebugSphereMesh = function (scene) { if (!this._debugSphereMesh) { this._debugSphereMesh = _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_2__["SphereBuilder"].CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene); this._debugSphereMesh.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].Identity(); this._debugSphereMesh.material = this._getDebugMaterial(scene); this._debugSphereMesh.setEnabled(false); } return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance'); }; PhysicsViewer.prototype._getDebugCylinderMesh = function (scene) { if (!this._debugCylinderMesh) { this._debugCylinderMesh = _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_8__["CylinderBuilder"].CreateCylinder('physicsBodyCylinderViewMesh', { diameterTop: 1, diameterBottom: 1, height: 1 }, scene); this._debugCylinderMesh.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].Identity(); this._debugCylinderMesh.material = this._getDebugMaterial(scene); this._debugCylinderMesh.setEnabled(false); } return this._debugCylinderMesh.createInstance('physicsBodyBoxViewInstance'); }; PhysicsViewer.prototype._getDebugMeshMesh = function (mesh, scene) { var wireframeOver = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_0__["Mesh"](mesh.name, scene, null, mesh); wireframeOver.position = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); wireframeOver.setParent(mesh); wireframeOver.material = this._getDebugMaterial(scene); this._debugMeshMeshes.push(wireframeOver); return wireframeOver; }; PhysicsViewer.prototype._getDebugMesh = function (impostor, targetMesh) { var _this = this; if (!this._utilityLayer) { return null; } // Only create child impostor debug meshes when evaluating the parent if (targetMesh && targetMesh.parent && targetMesh.parent.physicsImpostor) { return null; } var mesh = null; var utilityLayerScene = this._utilityLayer.utilityLayerScene; switch (impostor.type) { case _Physics_physicsImpostor__WEBPACK_IMPORTED_MODULE_6__["PhysicsImpostor"].BoxImpostor: mesh = this._getDebugBoxMesh(utilityLayerScene); impostor.getBoxSizeToRef(mesh.scaling); break; case _Physics_physicsImpostor__WEBPACK_IMPORTED_MODULE_6__["PhysicsImpostor"].SphereImpostor: mesh = this._getDebugSphereMesh(utilityLayerScene); var radius = impostor.getRadius(); mesh.scaling.x = radius * 2; mesh.scaling.y = radius * 2; mesh.scaling.z = radius * 2; break; case _Physics_physicsImpostor__WEBPACK_IMPORTED_MODULE_6__["PhysicsImpostor"].MeshImpostor: if (targetMesh) { mesh = this._getDebugMeshMesh(targetMesh, utilityLayerScene); } break; case _Physics_physicsImpostor__WEBPACK_IMPORTED_MODULE_6__["PhysicsImpostor"].NoImpostor: if (targetMesh) { // Handle compound impostors var childMeshes = targetMesh.getChildMeshes().filter(function (c) { return c.physicsImpostor ? 1 : 0; }); childMeshes.forEach(function (m) { var a = _this._getDebugBoxMesh(utilityLayerScene); a.parent = m; }); } break; case _Physics_physicsImpostor__WEBPACK_IMPORTED_MODULE_6__["PhysicsImpostor"].CylinderImpostor: mesh = this._getDebugCylinderMesh(utilityLayerScene); var bi = impostor.object.getBoundingInfo(); mesh.scaling.x = bi.boundingBox.maximum.x - bi.boundingBox.minimum.x; mesh.scaling.y = bi.boundingBox.maximum.y - bi.boundingBox.minimum.y; mesh.scaling.z = bi.boundingBox.maximum.z - bi.boundingBox.minimum.z; break; } return mesh; }; /** Releases all resources */ PhysicsViewer.prototype.dispose = function () { var count = this._numMeshes; for (var index = 0; index < count; index++) { this.hideImpostor(this._impostors[0]); } if (this._debugBoxMesh) { this._debugBoxMesh.dispose(); } if (this._debugSphereMesh) { this._debugSphereMesh.dispose(); } if (this._debugCylinderMesh) { this._debugCylinderMesh.dispose(); } if (this._debugMaterial) { this._debugMaterial.dispose(); } this._impostors.length = 0; this._scene = null; this._physicsEnginePlugin = null; if (this._utilityLayer) { this._utilityLayer.dispose(); this._utilityLayer = null; } }; return PhysicsViewer; }()); /***/ }), /***/ "./Debug/rayHelper.ts": /*!****************************!*\ !*** ./Debug/rayHelper.ts ***! \****************************/ /*! exports provided: RayHelper */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RayHelper", function() { return RayHelper; }); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts"); /* harmony import */ var _Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Meshes/Builders/linesBuilder */ "./Meshes/Builders/linesBuilder.ts"); /** * As raycast might be hard to debug, the RayHelper can help rendering the different rays * in order to better appreciate the issue one might have. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging */ var RayHelper = /** @class */ (function () { /** * Instantiate a new ray helper. * As raycast might be hard to debug, the RayHelper can help rendering the different rays * in order to better appreciate the issue one might have. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging * @param ray Defines the ray we are currently tryin to visualize */ function RayHelper(ray) { this.ray = ray; } /** * Helper function to create a colored helper in a scene in one line. * @param ray Defines the ray we are currently tryin to visualize * @param scene Defines the scene the ray is used in * @param color Defines the color we want to see the ray in * @returns The newly created ray helper. */ RayHelper.CreateAndShow = function (ray, scene, color) { var helper = new RayHelper(ray); helper.show(scene, color); return helper; }; /** * Shows the ray we are willing to debug. * @param scene Defines the scene the ray needs to be rendered in * @param color Defines the color the ray needs to be rendered in */ RayHelper.prototype.show = function (scene, color) { if (!this._renderFunction && this.ray) { var ray = this.ray; this._renderFunction = this._render.bind(this); this._scene = scene; this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))]; this._renderLine = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_1__["Mesh"].CreateLines("ray", this._renderPoints, scene, true); if (this._renderFunction) { this._scene.registerBeforeRender(this._renderFunction); } } if (color && this._renderLine) { this._renderLine.color.copyFrom(color); } }; /** * Hides the ray we are debugging. */ RayHelper.prototype.hide = function () { if (this._renderFunction && this._scene) { this._scene.unregisterBeforeRender(this._renderFunction); this._scene = null; this._renderFunction = null; if (this._renderLine) { this._renderLine.dispose(); this._renderLine = null; } this._renderPoints = []; } }; RayHelper.prototype._render = function () { var ray = this.ray; if (!ray) { return; } var point = this._renderPoints[1]; var len = Math.min(ray.length, 1000000); point.copyFrom(ray.direction); point.scaleInPlace(len); point.addInPlace(ray.origin); _Meshes_mesh__WEBPACK_IMPORTED_MODULE_1__["Mesh"].CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine); }; /** * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals. * @param mesh Defines the mesh we want the helper attached to * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node) * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node) * @param length Defines the length of the ray */ RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) { this._attachedToMesh = mesh; var ray = this.ray; if (!ray) { return; } if (!ray.direction) { ray.direction = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); } if (!ray.origin) { ray.origin = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); } if (length) { ray.length = length; } if (!meshSpaceOrigin) { meshSpaceOrigin = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); } if (!meshSpaceDirection) { // -1 so that this will work with Mesh.lookAt meshSpaceDirection = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0, 0, -1); } if (!this._meshSpaceDirection) { this._meshSpaceDirection = meshSpaceDirection.clone(); this._meshSpaceOrigin = meshSpaceOrigin.clone(); } else { this._meshSpaceDirection.copyFrom(meshSpaceDirection); this._meshSpaceOrigin.copyFrom(meshSpaceOrigin); } if (!this._updateToMeshFunction) { this._updateToMeshFunction = this._updateToMesh.bind(this); this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction); } this._updateToMesh(); }; /** * Detach the ray helper from the mesh it has previously been attached to. */ RayHelper.prototype.detachFromMesh = function () { if (this._attachedToMesh) { if (this._updateToMeshFunction) { this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction); } this._attachedToMesh = null; this._updateToMeshFunction = null; } }; RayHelper.prototype._updateToMesh = function () { var ray = this.ray; if (!this._attachedToMesh || !ray) { return; } if (this._attachedToMesh._isDisposed) { this.detachFromMesh(); return; } this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction); _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin); }; /** * Dispose the helper and release its associated resources. */ RayHelper.prototype.dispose = function () { this.hide(); this.detachFromMesh(); this.ray = null; }; return RayHelper; }()); /***/ }), /***/ "./Debug/skeletonViewer.ts": /*!*********************************!*\ !*** ./Debug/skeletonViewer.ts ***! \*********************************/ /*! exports provided: SkeletonViewer */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SkeletonViewer", function() { return SkeletonViewer; }); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Meshes/Builders/linesBuilder */ "./Meshes/Builders/linesBuilder.ts"); /* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts"); /** * Class used to render a debug view of a given skeleton * @see http://www.babylonjs-playground.com/#1BZJVJ#8 */ var SkeletonViewer = /** @class */ (function () { /** * Creates a new SkeletonViewer * @param skeleton defines the skeleton to render * @param mesh defines the mesh attached to the skeleton * @param scene defines the hosting scene * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) * @param renderingGroupId defines the rendering group id to use with the viewer */ function SkeletonViewer( /** defines the skeleton to render */ skeleton, /** defines the mesh attached to the skeleton */ mesh, scene, /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */ autoUpdateBonesMatrices, /** defines the rendering group id to use with the viewer */ renderingGroupId) { if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; } if (renderingGroupId === void 0) { renderingGroupId = 1; } this.skeleton = skeleton; this.mesh = mesh; this.autoUpdateBonesMatrices = autoUpdateBonesMatrices; this.renderingGroupId = renderingGroupId; /** Gets or sets the color used to render the skeleton */ this.color = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].White(); this._debugLines = new Array(); this._isEnabled = false; this._scene = scene; this._utilityLayer = new _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_2__["UtilityLayerRenderer"](this._scene, false); this._utilityLayer.pickUtilitySceneFirst = false; this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil = true; this.update(); this._renderFunction = this.update.bind(this); } Object.defineProperty(SkeletonViewer.prototype, "debugMesh", { /** * Returns the mesh used to render the bones */ get: function () { return this._debugMesh; }, enumerable: true, configurable: true }); Object.defineProperty(SkeletonViewer.prototype, "isEnabled", { get: function () { return this._isEnabled; }, /** Gets or sets a boolean indicating if the viewer is enabled */ set: function (value) { if (this._isEnabled === value) { return; } this._isEnabled = value; if (value) { this._scene.registerBeforeRender(this._renderFunction); } else { this._scene.unregisterBeforeRender(this._renderFunction); } }, enumerable: true, configurable: true }); SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) { if (x === void 0) { x = 0; } if (y === void 0) { y = 0; } if (z === void 0) { z = 0; } var tmat = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tmp"].Matrix[0]; var parentBone = bone.getParent(); tmat.copyFrom(bone.getLocalMatrix()); if (x !== 0 || y !== 0 || z !== 0) { var tmat2 = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tmp"].Matrix[1]; _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].IdentityToRef(tmat2); tmat2.setTranslationFromFloats(x, y, z); tmat2.multiplyToRef(tmat, tmat); } if (parentBone) { tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat); } tmat.multiplyToRef(meshMat, tmat); position.x = tmat.m[12]; position.y = tmat.m[13]; position.z = tmat.m[14]; }; SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) { var len = bones.length; var mesh = this.mesh._effectiveMesh; var meshPos = mesh.position; for (var i = 0; i < len; i++) { var bone = bones[i]; var points = this._debugLines[i]; if (!points) { points = [_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero()]; this._debugLines[i] = points; } this._getBonePosition(points[0], bone, meshMat); this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0); points[0].subtractInPlace(meshPos); points[1].subtractInPlace(meshPos); } }; SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) { var len = bones.length; var boneNum = 0; var mesh = this.mesh._effectiveMesh; var meshPos = mesh.position; for (var i = len - 1; i >= 0; i--) { var childBone = bones[i]; var parentBone = childBone.getParent(); if (!parentBone) { continue; } var points = this._debugLines[boneNum]; if (!points) { points = [_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero()]; this._debugLines[boneNum] = points; } childBone.getAbsolutePositionToRef(mesh, points[0]); parentBone.getAbsolutePositionToRef(mesh, points[1]); points[0].subtractInPlace(meshPos); points[1].subtractInPlace(meshPos); boneNum++; } }; /** Update the viewer to sync with current skeleton state */ SkeletonViewer.prototype.update = function () { if (!this._utilityLayer) { return; } if (this.autoUpdateBonesMatrices) { this.skeleton.computeAbsoluteTransforms(); } var mesh = this.mesh._effectiveMesh; if (this.skeleton.bones[0].length === undefined) { this._getLinesForBonesNoLength(this.skeleton.bones, mesh.getWorldMatrix()); } else { this._getLinesForBonesWithLength(this.skeleton.bones, mesh.getWorldMatrix()); } var targetScene = this._utilityLayer.utilityLayerScene; if (!this._debugMesh) { this._debugMesh = _Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_1__["LinesBuilder"].CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, targetScene); this._debugMesh.renderingGroupId = this.renderingGroupId; } else { _Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_1__["LinesBuilder"].CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, targetScene); } this._debugMesh.position.copyFrom(this.mesh.position); this._debugMesh.color = this.color; }; /** Release associated resources */ SkeletonViewer.prototype.dispose = function () { this.isEnabled = false; if (this._debugMesh) { this.isEnabled = false; this._debugMesh.dispose(); this._debugMesh = null; } if (this._utilityLayer) { this._utilityLayer.dispose(); this._utilityLayer = null; } }; return SkeletonViewer; }()); /***/ }), /***/ "./Engines/Extensions/engine.multiview.ts": /*!************************************************!*\ !*** ./Engines/Extensions/engine.multiview.ts ***! \************************************************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Engines/engine */ "./Engines/engine.ts"); /* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../scene */ "./scene.ts"); /* harmony import */ var _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Materials/Textures/internalTexture */ "./Materials/Textures/internalTexture.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Materials_uniformBuffer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Materials/uniformBuffer */ "./Materials/uniformBuffer.ts"); /* harmony import */ var _Materials_Textures_MultiviewRenderTarget__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Materials/Textures/MultiviewRenderTarget */ "./Materials/Textures/MultiviewRenderTarget.ts"); _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype.createMultiviewRenderTargetTexture = function (width, height) { var gl = this._gl; if (!this.getCaps().multiview) { throw "Multiview is not supported"; } var internalTexture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_3__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_3__["InternalTexture"].DATASOURCE_UNKNOWN, true); internalTexture.width = width; internalTexture.height = height; internalTexture._framebuffer = gl.createFramebuffer(); internalTexture._colorTextureArray = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D_ARRAY, internalTexture._colorTextureArray); gl.texStorage3D(gl.TEXTURE_2D_ARRAY, 1, gl.RGBA8, width, height, 2); internalTexture._depthStencilTextureArray = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D_ARRAY, internalTexture._depthStencilTextureArray); gl.texStorage3D(gl.TEXTURE_2D_ARRAY, 1, gl.DEPTH32F_STENCIL8, width, height, 2); internalTexture.isReady = true; return internalTexture; }; _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype.bindMultiviewFramebuffer = function (multiviewTexture) { var gl = this._gl; var ext = this.getCaps().multiview; this.bindFramebuffer(multiviewTexture, undefined, undefined, undefined, true); gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, multiviewTexture._framebuffer); if (multiviewTexture._colorTextureArray && multiviewTexture._depthStencilTextureArray) { ext.framebufferTextureMultiviewWEBGL(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, multiviewTexture._colorTextureArray, 0, 0, 2); ext.framebufferTextureMultiviewWEBGL(gl.DRAW_FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, multiviewTexture._depthStencilTextureArray, 0, 0, 2); } else { throw "Invalid multiview frame buffer"; } }; _Cameras_camera__WEBPACK_IMPORTED_MODULE_0__["Camera"].prototype._useMultiviewToSingleView = false; _Cameras_camera__WEBPACK_IMPORTED_MODULE_0__["Camera"].prototype._multiviewTexture = null; _Cameras_camera__WEBPACK_IMPORTED_MODULE_0__["Camera"].prototype._resizeOrCreateMultiviewTexture = function (width, height) { if (!this._multiviewTexture) { this._multiviewTexture = new _Materials_Textures_MultiviewRenderTarget__WEBPACK_IMPORTED_MODULE_6__["MultiviewRenderTarget"](this.getScene(), { width: width, height: height }); } else if (this._multiviewTexture.getRenderWidth() != width || this._multiviewTexture.getRenderHeight() != height) { this._multiviewTexture.dispose(); this._multiviewTexture = new _Materials_Textures_MultiviewRenderTarget__WEBPACK_IMPORTED_MODULE_6__["MultiviewRenderTarget"](this.getScene(), { width: width, height: height }); } }; _scene__WEBPACK_IMPORTED_MODULE_2__["Scene"].prototype._transformMatrixR = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].Zero(); _scene__WEBPACK_IMPORTED_MODULE_2__["Scene"].prototype._multiviewSceneUbo = null; _scene__WEBPACK_IMPORTED_MODULE_2__["Scene"].prototype._createMultiviewUbo = function () { this._multiviewSceneUbo = new _Materials_uniformBuffer__WEBPACK_IMPORTED_MODULE_5__["UniformBuffer"](this.getEngine(), undefined, true); this._multiviewSceneUbo.addUniform("viewProjection", 16); this._multiviewSceneUbo.addUniform("viewProjectionR", 16); this._multiviewSceneUbo.addUniform("view", 16); }; _scene__WEBPACK_IMPORTED_MODULE_2__["Scene"].prototype._updateMultiviewUbo = function (viewR, projectionR) { if (viewR && projectionR) { viewR.multiplyToRef(projectionR, this._transformMatrixR); } if (viewR && projectionR) { viewR.multiplyToRef(projectionR, _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Tmp"].Matrix[0]); _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Frustum"].GetRightPlaneToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_4__["Tmp"].Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane } if (this._multiviewSceneUbo) { this._multiviewSceneUbo.updateMatrix("viewProjection", this.getTransformMatrix()); this._multiviewSceneUbo.updateMatrix("viewProjectionR", this._transformMatrixR); this._multiviewSceneUbo.updateMatrix("view", this._viewMatrix); this._multiviewSceneUbo.update(); } }; _scene__WEBPACK_IMPORTED_MODULE_2__["Scene"].prototype._renderMultiviewToSingleView = function (camera) { // Multiview is only able to be displayed directly for API's such as webXR // This displays a multiview image by rendering to the multiview image and then // copying the result into the sub cameras instead of rendering them and proceeding as normal from there // Render to a multiview texture camera._resizeOrCreateMultiviewTexture((camera._rigPostProcess && camera._rigPostProcess && camera._rigPostProcess.width > 0) ? camera._rigPostProcess.width / 2 : this.getEngine().getRenderWidth(true) / 2, (camera._rigPostProcess && camera._rigPostProcess && camera._rigPostProcess.height > 0) ? camera._rigPostProcess.height : this.getEngine().getRenderHeight(true)); if (!this._multiviewSceneUbo) { this._createMultiviewUbo(); } camera.outputRenderTarget = camera._multiviewTexture; this._renderForCamera(camera); camera.outputRenderTarget = null; // Consume the multiview texture through a shader for each eye for (var index = 0; index < camera._rigCameras.length; index++) { var engine = this.getEngine(); this._activeCamera = camera._rigCameras[index]; engine.setViewport(this._activeCamera.viewport); if (this.postProcessManager) { this.postProcessManager._prepareFrame(); this.postProcessManager._finalizeFrame(this._activeCamera.isIntermediate); } } }; /***/ }), /***/ "./Engines/Extensions/engine.occlusionQuery.ts": /*!*****************************************************!*\ !*** ./Engines/Extensions/engine.occlusionQuery.ts ***! \*****************************************************/ /*! exports provided: _OcclusionDataStorage */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_OcclusionDataStorage", function() { return _OcclusionDataStorage; }); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Engines/engine */ "./Engines/engine.ts"); /* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts"); /* harmony import */ var _Instrumentation_timeToken__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Instrumentation/timeToken */ "./Instrumentation/timeToken.ts"); /** @hidden */ var _OcclusionDataStorage = /** @class */ (function () { function _OcclusionDataStorage() { /** @hidden */ this.occlusionInternalRetryCounter = 0; /** @hidden */ this.isOcclusionQueryInProgress = false; /** @hidden */ this.isOccluded = false; /** @hidden */ this.occlusionRetryCount = -1; /** @hidden */ this.occlusionType = _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].OCCLUSION_TYPE_NONE; /** @hidden */ this.occlusionQueryAlgorithmType = _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE; } return _OcclusionDataStorage; }()); _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.createQuery = function () { return this._gl.createQuery(); }; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.deleteQuery = function (query) { this._gl.deleteQuery(query); return this; }; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.isQueryResultAvailable = function (query) { return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE); }; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.getQueryResult = function (query) { return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT); }; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.beginOcclusionQuery = function (algorithmType, query) { var glAlgorithm = this._getGlAlgorithmType(algorithmType); this._gl.beginQuery(glAlgorithm, query); return this; }; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.endOcclusionQuery = function (algorithmType) { var glAlgorithm = this._getGlAlgorithmType(algorithmType); this._gl.endQuery(glAlgorithm); return this; }; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype._createTimeQuery = function () { var timerQuery = this.getCaps().timerQuery; if (timerQuery.createQueryEXT) { return timerQuery.createQueryEXT(); } return this.createQuery(); }; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype._deleteTimeQuery = function (query) { var timerQuery = this.getCaps().timerQuery; if (timerQuery.deleteQueryEXT) { timerQuery.deleteQueryEXT(query); return; } this.deleteQuery(query); }; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype._getTimeQueryResult = function (query) { var timerQuery = this.getCaps().timerQuery; if (timerQuery.getQueryObjectEXT) { return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT); } return this.getQueryResult(query); }; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype._getTimeQueryAvailability = function (query) { var timerQuery = this.getCaps().timerQuery; if (timerQuery.getQueryObjectEXT) { return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT); } return this.isQueryResultAvailable(query); }; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.startTimeQuery = function () { var caps = this.getCaps(); var timerQuery = caps.timerQuery; if (!timerQuery) { return null; } var token = new _Instrumentation_timeToken__WEBPACK_IMPORTED_MODULE_2__["_TimeToken"](); this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT); if (caps.canUseTimestampForTimerQuery) { token._startTimeQuery = this._createTimeQuery(); timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT); } else { if (this._currentNonTimestampToken) { return this._currentNonTimestampToken; } token._timeElapsedQuery = this._createTimeQuery(); if (timerQuery.beginQueryEXT) { timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery); } else { this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery); } this._currentNonTimestampToken = token; } return token; }; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.endTimeQuery = function (token) { var caps = this.getCaps(); var timerQuery = caps.timerQuery; if (!timerQuery || !token) { return -1; } if (caps.canUseTimestampForTimerQuery) { if (!token._startTimeQuery) { return -1; } if (!token._endTimeQuery) { token._endTimeQuery = this._createTimeQuery(); timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT); } } else if (!token._timeElapsedQueryEnded) { if (!token._timeElapsedQuery) { return -1; } if (timerQuery.endQueryEXT) { timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT); } else { this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT); } token._timeElapsedQueryEnded = true; } var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT); var available = false; if (token._endTimeQuery) { available = this._getTimeQueryAvailability(token._endTimeQuery); } else if (token._timeElapsedQuery) { available = this._getTimeQueryAvailability(token._timeElapsedQuery); } if (available && !disjoint) { var result = 0; if (caps.canUseTimestampForTimerQuery) { if (!token._startTimeQuery || !token._endTimeQuery) { return -1; } var timeStart = this._getTimeQueryResult(token._startTimeQuery); var timeEnd = this._getTimeQueryResult(token._endTimeQuery); result = timeEnd - timeStart; this._deleteTimeQuery(token._startTimeQuery); this._deleteTimeQuery(token._endTimeQuery); token._startTimeQuery = null; token._endTimeQuery = null; } else { if (!token._timeElapsedQuery) { return -1; } result = this._getTimeQueryResult(token._timeElapsedQuery); this._deleteTimeQuery(token._timeElapsedQuery); token._timeElapsedQuery = null; token._timeElapsedQueryEnded = false; this._currentNonTimestampToken = null; } return result; } return -1; }; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype._getGlAlgorithmType = function (algorithmType) { return algorithmType === _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED; }; Object.defineProperty(_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].prototype, "isOcclusionQueryInProgress", { get: function () { return this._occlusionDataStorage.isOcclusionQueryInProgress; }, enumerable: false, configurable: true }); Object.defineProperty(_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].prototype, "_occlusionDataStorage", { get: function () { if (!this.__occlusionDataStorage) { this.__occlusionDataStorage = new _OcclusionDataStorage(); } return this.__occlusionDataStorage; }, enumerable: false, configurable: true }); Object.defineProperty(_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].prototype, "isOccluded", { get: function () { return this._occlusionDataStorage.isOccluded; }, set: function (value) { this._occlusionDataStorage.isOccluded = value; }, enumerable: true, configurable: true }); Object.defineProperty(_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].prototype, "occlusionQueryAlgorithmType", { get: function () { return this._occlusionDataStorage.occlusionQueryAlgorithmType; }, set: function (value) { this._occlusionDataStorage.occlusionQueryAlgorithmType = value; }, enumerable: true, configurable: true }); Object.defineProperty(_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].prototype, "occlusionType", { get: function () { return this._occlusionDataStorage.occlusionType; }, set: function (value) { this._occlusionDataStorage.occlusionType = value; }, enumerable: true, configurable: true }); Object.defineProperty(_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].prototype, "occlusionRetryCount", { get: function () { return this._occlusionDataStorage.occlusionRetryCount; }, set: function (value) { this._occlusionDataStorage.occlusionRetryCount = value; }, enumerable: true, configurable: true }); // We also need to update AbstractMesh as there is a portion of the code there _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].prototype._checkOcclusionQuery = function () { var dataStorage = this._occlusionDataStorage; if (dataStorage.occlusionType === _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].OCCLUSION_TYPE_NONE) { dataStorage.isOccluded = false; return false; } var engine = this.getEngine(); if (engine.webGLVersion < 2) { dataStorage.isOccluded = false; return false; } if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced dataStorage.isOccluded = false; return false; } if (this.isOcclusionQueryInProgress && this._occlusionQuery) { var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery); if (isOcclusionQueryAvailable) { var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery); dataStorage.isOcclusionQueryInProgress = false; dataStorage.occlusionInternalRetryCounter = 0; dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true; } else { dataStorage.occlusionInternalRetryCounter++; if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) { dataStorage.isOcclusionQueryInProgress = false; dataStorage.occlusionInternalRetryCounter = 0; // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop) // if strict continue the last state of the object. dataStorage.isOccluded = dataStorage.occlusionType === _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded; } else { return false; } } } var scene = this.getScene(); if (scene.getBoundingBoxRenderer) { var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer(); if (!this._occlusionQuery) { this._occlusionQuery = engine.createQuery(); } engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery); occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this); engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType); this._occlusionDataStorage.isOcclusionQueryInProgress = true; } return dataStorage.isOccluded; }; /***/ }), /***/ "./Engines/Extensions/engine.transformFeedback.ts": /*!********************************************************!*\ !*** ./Engines/Extensions/engine.transformFeedback.ts ***! \********************************************************/ /*! exports provided: _forceTransformFeedbackToBundle */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_forceTransformFeedbackToBundle", function() { return _forceTransformFeedbackToBundle; }); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Engines/engine */ "./Engines/engine.ts"); /** @hidden */ var _forceTransformFeedbackToBundle = true; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.createTransformFeedback = function () { return this._gl.createTransformFeedback(); }; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.deleteTransformFeedback = function (value) { this._gl.deleteTransformFeedback(value); }; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.bindTransformFeedback = function (value) { this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value); }; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.beginTransformFeedback = function (usePoints) { if (usePoints === void 0) { usePoints = true; } this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES); }; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.endTransformFeedback = function () { this._gl.endTransformFeedback(); }; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.setTranformFeedbackVaryings = function (program, value) { this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS); }; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.bindTransformFeedbackBuffer = function (value) { this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value); }; /***/ }), /***/ "./Engines/Extensions/index.ts": /*!*************************************!*\ !*** ./Engines/Extensions/index.ts ***! \*************************************/ /*! exports provided: _OcclusionDataStorage, _forceTransformFeedbackToBundle */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _engine_occlusionQuery__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./engine.occlusionQuery */ "./Engines/Extensions/engine.occlusionQuery.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_OcclusionDataStorage", function() { return _engine_occlusionQuery__WEBPACK_IMPORTED_MODULE_0__["_OcclusionDataStorage"]; }); /* harmony import */ var _engine_transformFeedback__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine.transformFeedback */ "./Engines/Extensions/engine.transformFeedback.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_forceTransformFeedbackToBundle", function() { return _engine_transformFeedback__WEBPACK_IMPORTED_MODULE_1__["_forceTransformFeedbackToBundle"]; }); /***/ }), /***/ "./Engines/constants.ts": /*!******************************!*\ !*** ./Engines/constants.ts ***! \******************************/ /*! exports provided: Constants */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Constants", function() { return Constants; }); /** Defines the cross module used constants to avoid circular dependncies */ var Constants = /** @class */ (function () { function Constants() { } /** Defines that alpha blending is disabled */ Constants.ALPHA_DISABLE = 0; /** Defines that alpha blending to SRC ALPHA * SRC + DEST */ Constants.ALPHA_ADD = 1; /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */ Constants.ALPHA_COMBINE = 2; /** Defines that alpha blending to DEST - SRC * DEST */ Constants.ALPHA_SUBTRACT = 3; /** Defines that alpha blending to SRC * DEST */ Constants.ALPHA_MULTIPLY = 4; /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */ Constants.ALPHA_MAXIMIZED = 5; /** Defines that alpha blending to SRC + DEST */ Constants.ALPHA_ONEONE = 6; /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */ Constants.ALPHA_PREMULTIPLIED = 7; /** * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA */ Constants.ALPHA_PREMULTIPLIED_PORTERDUFF = 8; /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */ Constants.ALPHA_INTERPOLATE = 9; /** * Defines that alpha blending to SRC + (1 - SRC) * DEST * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA */ Constants.ALPHA_SCREENMODE = 10; /** Defines that the ressource is not delayed*/ Constants.DELAYLOADSTATE_NONE = 0; /** Defines that the ressource was successfully delay loaded */ Constants.DELAYLOADSTATE_LOADED = 1; /** Defines that the ressource is currently delay loading */ Constants.DELAYLOADSTATE_LOADING = 2; /** Defines that the ressource is delayed and has not started loading */ Constants.DELAYLOADSTATE_NOTLOADED = 4; // Depht or Stencil test Constants. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */ Constants.NEVER = 0x0200; /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */ Constants.ALWAYS = 0x0207; /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */ Constants.LESS = 0x0201; /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */ Constants.EQUAL = 0x0202; /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */ Constants.LEQUAL = 0x0203; /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */ Constants.GREATER = 0x0204; /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */ Constants.GEQUAL = 0x0206; /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */ Constants.NOTEQUAL = 0x0205; // Stencil Actions Constants. /** Passed to stencilOperation to specify that stencil value must be kept */ Constants.KEEP = 0x1E00; /** Passed to stencilOperation to specify that stencil value must be replaced */ Constants.REPLACE = 0x1E01; /** Passed to stencilOperation to specify that stencil value must be incremented */ Constants.INCR = 0x1E02; /** Passed to stencilOperation to specify that stencil value must be decremented */ Constants.DECR = 0x1E03; /** Passed to stencilOperation to specify that stencil value must be inverted */ Constants.INVERT = 0x150A; /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */ Constants.INCR_WRAP = 0x8507; /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */ Constants.DECR_WRAP = 0x8508; /** Texture is not repeating outside of 0..1 UVs */ Constants.TEXTURE_CLAMP_ADDRESSMODE = 0; /** Texture is repeating outside of 0..1 UVs */ Constants.TEXTURE_WRAP_ADDRESSMODE = 1; /** Texture is repeating and mirrored */ Constants.TEXTURE_MIRROR_ADDRESSMODE = 2; /** ALPHA */ Constants.TEXTUREFORMAT_ALPHA = 0; /** LUMINANCE */ Constants.TEXTUREFORMAT_LUMINANCE = 1; /** LUMINANCE_ALPHA */ Constants.TEXTUREFORMAT_LUMINANCE_ALPHA = 2; /** RGB */ Constants.TEXTUREFORMAT_RGB = 4; /** RGBA */ Constants.TEXTUREFORMAT_RGBA = 5; /** RED */ Constants.TEXTUREFORMAT_RED = 6; /** RED (2nd reference) */ Constants.TEXTUREFORMAT_R = 6; /** RG */ Constants.TEXTUREFORMAT_RG = 7; /** RED_INTEGER */ Constants.TEXTUREFORMAT_RED_INTEGER = 8; /** RED_INTEGER (2nd reference) */ Constants.TEXTUREFORMAT_R_INTEGER = 8; /** RG_INTEGER */ Constants.TEXTUREFORMAT_RG_INTEGER = 9; /** RGB_INTEGER */ Constants.TEXTUREFORMAT_RGB_INTEGER = 10; /** RGBA_INTEGER */ Constants.TEXTUREFORMAT_RGBA_INTEGER = 11; /** UNSIGNED_BYTE */ Constants.TEXTURETYPE_UNSIGNED_BYTE = 0; /** UNSIGNED_BYTE (2nd reference) */ Constants.TEXTURETYPE_UNSIGNED_INT = 0; /** FLOAT */ Constants.TEXTURETYPE_FLOAT = 1; /** HALF_FLOAT */ Constants.TEXTURETYPE_HALF_FLOAT = 2; /** BYTE */ Constants.TEXTURETYPE_BYTE = 3; /** SHORT */ Constants.TEXTURETYPE_SHORT = 4; /** UNSIGNED_SHORT */ Constants.TEXTURETYPE_UNSIGNED_SHORT = 5; /** INT */ Constants.TEXTURETYPE_INT = 6; /** UNSIGNED_INT */ Constants.TEXTURETYPE_UNSIGNED_INTEGER = 7; /** UNSIGNED_SHORT_4_4_4_4 */ Constants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8; /** UNSIGNED_SHORT_5_5_5_1 */ Constants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9; /** UNSIGNED_SHORT_5_6_5 */ Constants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10; /** UNSIGNED_INT_2_10_10_10_REV */ Constants.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11; /** UNSIGNED_INT_24_8 */ Constants.TEXTURETYPE_UNSIGNED_INT_24_8 = 12; /** UNSIGNED_INT_10F_11F_11F_REV */ Constants.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13; /** UNSIGNED_INT_5_9_9_9_REV */ Constants.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14; /** FLOAT_32_UNSIGNED_INT_24_8_REV */ Constants.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15; /** nearest is mag = nearest and min = nearest and mip = linear */ Constants.TEXTURE_NEAREST_SAMPLINGMODE = 1; /** Bilinear is mag = linear and min = linear and mip = nearest */ Constants.TEXTURE_BILINEAR_SAMPLINGMODE = 2; /** Trilinear is mag = linear and min = linear and mip = linear */ Constants.TEXTURE_TRILINEAR_SAMPLINGMODE = 3; /** nearest is mag = nearest and min = nearest and mip = linear */ Constants.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1; /** Bilinear is mag = linear and min = linear and mip = nearest */ Constants.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2; /** Trilinear is mag = linear and min = linear and mip = linear */ Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3; /** mag = nearest and min = nearest and mip = nearest */ Constants.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4; /** mag = nearest and min = linear and mip = nearest */ Constants.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5; /** mag = nearest and min = linear and mip = linear */ Constants.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6; /** mag = nearest and min = linear and mip = none */ Constants.TEXTURE_NEAREST_LINEAR = 7; /** mag = nearest and min = nearest and mip = none */ Constants.TEXTURE_NEAREST_NEAREST = 8; /** mag = linear and min = nearest and mip = nearest */ Constants.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9; /** mag = linear and min = nearest and mip = linear */ Constants.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10; /** mag = linear and min = linear and mip = none */ Constants.TEXTURE_LINEAR_LINEAR = 11; /** mag = linear and min = nearest and mip = none */ Constants.TEXTURE_LINEAR_NEAREST = 12; /** Explicit coordinates mode */ Constants.TEXTURE_EXPLICIT_MODE = 0; /** Spherical coordinates mode */ Constants.TEXTURE_SPHERICAL_MODE = 1; /** Planar coordinates mode */ Constants.TEXTURE_PLANAR_MODE = 2; /** Cubic coordinates mode */ Constants.TEXTURE_CUBIC_MODE = 3; /** Projection coordinates mode */ Constants.TEXTURE_PROJECTION_MODE = 4; /** Skybox coordinates mode */ Constants.TEXTURE_SKYBOX_MODE = 5; /** Inverse Cubic coordinates mode */ Constants.TEXTURE_INVCUBIC_MODE = 6; /** Equirectangular coordinates mode */ Constants.TEXTURE_EQUIRECTANGULAR_MODE = 7; /** Equirectangular Fixed coordinates mode */ Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8; /** Equirectangular Fixed Mirrored coordinates mode */ Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9; // Texture rescaling mode /** Defines that texture rescaling will use a floor to find the closer power of 2 size */ Constants.SCALEMODE_FLOOR = 1; /** Defines that texture rescaling will look for the nearest power of 2 size */ Constants.SCALEMODE_NEAREST = 2; /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */ Constants.SCALEMODE_CEILING = 3; /** * The dirty texture flag value */ Constants.MATERIAL_TextureDirtyFlag = 1; /** * The dirty light flag value */ Constants.MATERIAL_LightDirtyFlag = 2; /** * The dirty fresnel flag value */ Constants.MATERIAL_FresnelDirtyFlag = 4; /** * The dirty attribute flag value */ Constants.MATERIAL_AttributesDirtyFlag = 8; /** * The dirty misc flag value */ Constants.MATERIAL_MiscDirtyFlag = 16; /** * The all dirty flag value */ Constants.MATERIAL_AllDirtyFlag = 31; /** * Returns the triangle fill mode */ Constants.MATERIAL_TriangleFillMode = 0; /** * Returns the wireframe mode */ Constants.MATERIAL_WireFrameFillMode = 1; /** * Returns the point fill mode */ Constants.MATERIAL_PointFillMode = 2; /** * Returns the point list draw mode */ Constants.MATERIAL_PointListDrawMode = 3; /** * Returns the line list draw mode */ Constants.MATERIAL_LineListDrawMode = 4; /** * Returns the line loop draw mode */ Constants.MATERIAL_LineLoopDrawMode = 5; /** * Returns the line strip draw mode */ Constants.MATERIAL_LineStripDrawMode = 6; /** * Returns the triangle strip draw mode */ Constants.MATERIAL_TriangleStripDrawMode = 7; /** * Returns the triangle fan draw mode */ Constants.MATERIAL_TriangleFanDrawMode = 8; /** * Stores the clock-wise side orientation */ Constants.MATERIAL_ClockWiseSideOrientation = 0; /** * Stores the counter clock-wise side orientation */ Constants.MATERIAL_CounterClockWiseSideOrientation = 1; /** * Nothing * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ Constants.ACTION_NothingTrigger = 0; /** * On pick * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ Constants.ACTION_OnPickTrigger = 1; /** * On left pick * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ Constants.ACTION_OnLeftPickTrigger = 2; /** * On right pick * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ Constants.ACTION_OnRightPickTrigger = 3; /** * On center pick * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ Constants.ACTION_OnCenterPickTrigger = 4; /** * On pick down * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ Constants.ACTION_OnPickDownTrigger = 5; /** * On double pick * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ Constants.ACTION_OnDoublePickTrigger = 6; /** * On pick up * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ Constants.ACTION_OnPickUpTrigger = 7; /** * On pick out. * This trigger will only be raised if you also declared a OnPickDown * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ Constants.ACTION_OnPickOutTrigger = 16; /** * On long press * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ Constants.ACTION_OnLongPressTrigger = 8; /** * On pointer over * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ Constants.ACTION_OnPointerOverTrigger = 9; /** * On pointer out * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ Constants.ACTION_OnPointerOutTrigger = 10; /** * On every frame * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ Constants.ACTION_OnEveryFrameTrigger = 11; /** * On intersection enter * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ Constants.ACTION_OnIntersectionEnterTrigger = 12; /** * On intersection exit * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ Constants.ACTION_OnIntersectionExitTrigger = 13; /** * On key down * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ Constants.ACTION_OnKeyDownTrigger = 14; /** * On key up * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ Constants.ACTION_OnKeyUpTrigger = 15; /** * Billboard mode will only apply to Y axis */ Constants.PARTICLES_BILLBOARDMODE_Y = 2; /** * Billboard mode will apply to all axes */ Constants.PARTICLES_BILLBOARDMODE_ALL = 7; /** * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction */ Constants.PARTICLES_BILLBOARDMODE_STRETCHED = 8; /** * Gets or sets base Assets URL */ Constants.PARTICLES_BaseAssetsUrl = "https://assets.babylonjs.com/particles"; /** Default culling strategy : this is an exclusion test and it's the more accurate. * Test order : * Is the bounding sphere outside the frustum ? * If not, are the bounding box vertices outside the frustum ? * It not, then the cullable object is in the frustum. */ Constants.MESHES_CULLINGSTRATEGY_STANDARD = 0; /** Culling strategy : Bounding Sphere Only. * This is an exclusion test. It's faster than the standard strategy because the bounding box is not tested. * It's also less accurate than the standard because some not visible objects can still be selected. * Test : is the bounding sphere outside the frustum ? * If not, then the cullable object is in the frustum. */ Constants.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1; /** Culling strategy : Optimistic Inclusion. * This in an inclusion test first, then the standard exclusion test. * This can be faster when a cullable object is expected to be almost always in the camera frustum. * This could also be a little slower than the standard test when the tested object center is not the frustum but one of its bounding box vertex is still inside. * Anyway, it's as accurate as the standard strategy. * Test : * Is the cullable object bounding sphere center in the frustum ? * If not, apply the default culling strategy. */ Constants.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION = 2; /** Culling strategy : Optimistic Inclusion then Bounding Sphere Only. * This in an inclusion test first, then the bounding sphere only exclusion test. * This can be the fastest test when a cullable object is expected to be almost always in the camera frustum. * This could also be a little slower than the BoundingSphereOnly strategy when the tested object center is not in the frustum but its bounding sphere still intersects it. * It's less accurate than the standard strategy and as accurate as the BoundingSphereOnly strategy. * Test : * Is the cullable object bounding sphere center in the frustum ? * If not, apply the Bounding Sphere Only strategy. No Bounding Box is tested here. */ Constants.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY = 3; /** * No logging while loading */ Constants.SCENELOADER_NO_LOGGING = 0; /** * Minimal logging while loading */ Constants.SCENELOADER_MINIMAL_LOGGING = 1; /** * Summary logging while loading */ Constants.SCENELOADER_SUMMARY_LOGGING = 2; /** * Detailled logging while loading */ Constants.SCENELOADER_DETAILED_LOGGING = 3; return Constants; }()); /***/ }), /***/ "./Engines/engine.ts": /*!***************************!*\ !*** ./Engines/engine.ts ***! \***************************/ /*! exports provided: InstancingAttributeInfo, DepthTextureCreationOptions, EngineCapabilities, Engine */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InstancingAttributeInfo", function() { return InstancingAttributeInfo; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DepthTextureCreationOptions", function() { return DepthTextureCreationOptions; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EngineCapabilities", function() { return EngineCapabilities; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Engine", function() { return Engine; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Misc_performanceMonitor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/performanceMonitor */ "./Misc/performanceMonitor.ts"); /* harmony import */ var _Misc_stringDictionary__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/stringDictionary */ "./Misc/stringDictionary.ts"); /* harmony import */ var _Misc_promise__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Misc/promise */ "./Misc/promise.ts"); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Maths/math.scalar */ "./Maths/math.scalar.ts"); /* harmony import */ var _Materials_effect__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Materials/effect */ "./Materials/effect.ts"); /* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Materials/material */ "./Materials/material.ts"); /* harmony import */ var _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Materials/Textures/internalTexture */ "./Materials/Textures/internalTexture.ts"); /* harmony import */ var _States_index__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../States/index */ "./States/index.ts"); /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./constants */ "./Engines/constants.ts"); /* harmony import */ var _Misc_domManagement__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Misc/domManagement */ "./Misc/domManagement.ts"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _engineStore__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./engineStore */ "./Engines/engineStore.ts"); /* harmony import */ var _Materials_Textures_renderTargetCreationOptions__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../Materials/Textures/renderTargetCreationOptions */ "./Materials/Textures/renderTargetCreationOptions.ts"); /* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../Misc/devTools */ "./Misc/devTools.ts"); /** * Keeps track of all the buffer info used in engine. */ var BufferPointer = /** @class */ (function () { function BufferPointer() { } return BufferPointer; }()); /** * Interface for attribute information associated with buffer instanciation */ var InstancingAttributeInfo = /** @class */ (function () { function InstancingAttributeInfo() { } return InstancingAttributeInfo; }()); /** * Define options used to create a depth texture */ var DepthTextureCreationOptions = /** @class */ (function () { function DepthTextureCreationOptions() { } return DepthTextureCreationOptions; }()); /** * Class used to describe the capabilities of the engine relatively to the current browser */ var EngineCapabilities = /** @class */ (function () { function EngineCapabilities() { } return EngineCapabilities; }()); /** * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio */ var Engine = /** @class */ (function () { /** * 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 alreay 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) */ function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) { if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; } var _this = this; // Public members /** * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required */ this.forcePOTTextures = false; /** * Gets a boolean indicating if the engine is currently rendering in fullscreen mode */ this.isFullscreen = false; /** * Gets a boolean indicating if the pointer is currently locked */ this.isPointerLock = false; /** * Gets or sets a boolean indicating if back faces must be culled (true by default) */ this.cullBackFaces = true; /** * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun */ this.renderEvenInBackground = true; /** * Gets or sets a boolean indicating that cache can be kept between frames */ this.preventCacheWipeBetweenFrames = false; /** * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest **/ this.enableOfflineSupport = false; /** * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (js will always consider the database is up to date) **/ this.disableManifestCheck = false; /** * Gets the list of created scenes */ this.scenes = new Array(); /** * Event raised when a new scene is created */ this.onNewSceneAddedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Gets the list of created postprocesses */ this.postProcesses = new Array(); /** Gets or sets a boolean indicating if the engine should validate programs after compilation */ this.validateShaderPrograms = false; // Observables /** * Observable event triggered each time the rendering canvas is resized */ this.onResizeObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Observable event triggered each time the canvas loses focus */ this.onCanvasBlurObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Observable event triggered each time the canvas gains focus */ this.onCanvasFocusObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Observable event triggered each time the canvas receives pointerout event */ this.onCanvasPointerOutObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Observable event triggered before each texture is initialized */ this.onBeforeTextureInitObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); //WebVR this._vrDisplay = undefined; this._vrSupported = false; this._vrExclusivePointerMode = false; // Uniform buffers list /** * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported */ this.disableUniformBuffers = false; /** @hidden */ this._uniformBuffers = new Array(); // Observables /** * Observable raised when the engine begins a new frame */ this.onBeginFrameObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * If set, will be used to request the next animation frame for the render loop */ this.customAnimationFrameRequester = null; /** * Observable raised when the engine ends the current frame */ this.onEndFrameObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Observable raised when the engine is about to compile a shader */ this.onBeforeShaderCompilationObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Observable raised when the engine has jsut compiled a shader */ this.onAfterShaderCompilationObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); this._windowIsBackground = false; this._webGLVersion = 1.0; this._highPrecisionShadersAllowed = true; /** @hidden */ this._badOS = false; /** @hidden */ this._badDesktopOS = false; /** * Observable signaled when VR display mode changes */ this.onVRDisplayChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Observable signaled when VR request present is complete */ this.onVRRequestPresentComplete = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Observable signaled when VR request present starts */ this.onVRRequestPresentStart = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); this._colorWrite = true; /** @hidden */ this._drawCalls = new _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["PerfCounter"](); this._renderingQueueLaunched = false; this._activeRenderLoops = new Array(); // Deterministic lockstepMaxSteps this._deterministicLockstep = false; this._lockstepMaxSteps = 4; // Lost context /** * Observable signaled when a context lost event is raised */ this.onContextLostObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Observable signaled when a context restored event is raised */ this.onContextRestoredObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); this._contextWasLost = false; this._doNotHandleContextLost = false; // FPS this._performanceMonitor = new _Misc_performanceMonitor__WEBPACK_IMPORTED_MODULE_2__["PerformanceMonitor"](); this._fps = 60; this._deltaTime = 0; /** * Turn this value on if you want to pause FPS computation when in background */ this.disablePerformanceMonitorInBackground = false; /** * Gets or sets a boolean indicating that vertex array object must be disabled even if they are supported */ this.disableVertexArrayObjects = false; // States /** @hidden */ this._depthCullingState = new _States_index__WEBPACK_IMPORTED_MODULE_11__["_DepthCullingState"](); /** @hidden */ this._stencilState = new _States_index__WEBPACK_IMPORTED_MODULE_11__["_StencilState"](); /** @hidden */ this._alphaState = new _States_index__WEBPACK_IMPORTED_MODULE_11__["_AlphaState"](); /** @hidden */ this._alphaMode = Engine.ALPHA_DISABLE; // Cache this._internalTexturesCache = new Array(); /** @hidden */ this._activeChannel = 0; this._currentTextureChannel = -1; /** @hidden */ this._boundTexturesCache = {}; this._compiledEffects = {}; this._vertexAttribArraysEnabled = []; this._uintIndicesCurrentlySet = false; this._currentBoundBuffer = new Array(); /** @hidden */ this._currentFramebuffer = 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._activeRequests = new Array(); // Hardware supported Compressed Textures this._texturesSupported = new Array(); /** * Defines whether the engine has been created with the premultipliedAlpha option on or not. */ this.premultipliedAlpha = true; this._viewportCached = new _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Vector4"](0, 0, 0, 0); this._onVRFullScreenTriggered = function () { if (_this._vrDisplay && _this._vrDisplay.isPresenting) { //get the old size before we change _this._oldSize = new _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Size"](_this.getRenderWidth(), _this.getRenderHeight()); _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel(); //get the width and height, change the render size var leftEye = _this._vrDisplay.getEyeParameters('left'); _this.setHardwareScalingLevel(1); _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight); } else { _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor); _this.setSize(_this._oldSize.width, _this._oldSize.height); } }; this._unpackFlipYCached = null; /** * In case you are sharing the context with other applications, it might * be interested to not cache the unpack flip y state to ensure a consistent * value would be set. */ this.enableUnpackFlipYCached = true; this._boundUniforms = {}; // Register promises _Misc_promise__WEBPACK_IMPORTED_MODULE_4__["PromisePolyfill"].Apply(); var canvas = null; Engine.Instances.push(this); if (!canvasOrContext) { return; } options = options || {}; if (canvasOrContext.getContext) { canvas = canvasOrContext; this._renderingCanvas = canvas; if (antialias != null) { options.antialias = antialias; } if (options.deterministicLockstep === undefined) { options.deterministicLockstep = false; } if (options.lockstepMaxSteps === undefined) { options.lockstepMaxSteps = 4; } if (options.preserveDrawingBuffer === undefined) { options.preserveDrawingBuffer = false; } if (options.audioEngine === undefined) { options.audioEngine = true; } if (options.stencil === undefined) { options.stencil = true; } if (options.premultipliedAlpha === false) { this.premultipliedAlpha = false; } this._deterministicLockstep = options.deterministicLockstep; this._lockstepMaxSteps = options.lockstepMaxSteps; this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false; // Exceptions if (navigator && navigator.userAgent) { var ua = navigator.userAgent; for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) { var exception = _a[_i]; var key = exception.key; var targets = exception.targets; var check = new RegExp(key); if (check.test(ua)) { if (exception.capture && exception.captureConstraint) { var capture = exception.capture; var constraint = exception.captureConstraint; var regex = new RegExp(capture); var matches = regex.exec(ua); if (matches && matches.length > 0) { var capturedValue = parseInt(matches[matches.length - 1]); if (capturedValue >= constraint) { continue; } } } for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) { var target = targets_1[_b]; switch (target) { case "uniformBuffer": this.disableUniformBuffers = true; break; case "vao": this.disableVertexArrayObjects = true; break; } } } } } // GL if (!options.disableWebGL2Support) { try { this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options)); if (this._gl) { this._webGLVersion = 2.0; // Prevent weird browsers to lie :-) if (!this._gl.deleteQuery) { this._webGLVersion = 1.0; } } } catch (e) { // Do nothing } } if (!this._gl) { if (!canvas) { throw new Error("The provided canvas is null or undefined."); } try { this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options)); } catch (e) { throw new Error("WebGL not supported"); } } if (!this._gl) { throw new Error("WebGL not supported"); } // Ensures a consistent color space unpacking of textures cross browser. this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, this._gl.NONE); this._onCanvasFocus = function () { _this.onCanvasFocusObservable.notifyObservers(_this); }; this._onCanvasBlur = function () { _this.onCanvasBlurObservable.notifyObservers(_this); }; canvas.addEventListener("focus", this._onCanvasFocus); canvas.addEventListener("blur", this._onCanvasBlur); this._onBlur = function () { if (_this.disablePerformanceMonitorInBackground) { _this._performanceMonitor.disable(); } _this._windowIsBackground = true; }; this._onFocus = function () { if (_this.disablePerformanceMonitorInBackground) { _this._performanceMonitor.enable(); } _this._windowIsBackground = false; }; this._onCanvasPointerOut = function (ev) { _this.onCanvasPointerOutObservable.notifyObservers(ev); }; if (_Misc_domManagement__WEBPACK_IMPORTED_MODULE_13__["DomManagement"].IsWindowObjectExist()) { window.addEventListener("blur", this._onBlur); window.addEventListener("focus", this._onFocus); } canvas.addEventListener("pointerout", this._onCanvasPointerOut); // Context lost if (!this._doNotHandleContextLost) { this._onContextLost = function (evt) { evt.preventDefault(); _this._contextWasLost = true; _Misc_logger__WEBPACK_IMPORTED_MODULE_14__["Logger"].Warn("WebGL context lost."); _this.onContextLostObservable.notifyObservers(_this); }; this._onContextRestored = function () { // Adding a timeout to avoid race condition at browser level setTimeout(function () { // Rebuild gl context _this._initGLContext(); // Rebuild effects _this._rebuildEffects(); // Rebuild textures _this._rebuildInternalTextures(); // Rebuild buffers _this._rebuildBuffers(); // Cache _this.wipeCaches(true); _Misc_logger__WEBPACK_IMPORTED_MODULE_14__["Logger"].Warn("WebGL context successfully restored."); _this.onContextRestoredObservable.notifyObservers(_this); _this._contextWasLost = false; }, 0); }; canvas.addEventListener("webglcontextlost", this._onContextLost, false); canvas.addEventListener("webglcontextrestored", this._onContextRestored, false); } if (!options.doNotHandleTouchAction) { this._disableTouchAction(); } } else { this._gl = canvasOrContext; this._renderingCanvas = this._gl.canvas; if (this._gl.renderbufferStorageMultisample) { this._webGLVersion = 2.0; } var attributes = this._gl.getContextAttributes(); if (attributes) { options.stencil = attributes.stencil; } } if (options.useHighPrecisionFloats !== undefined) { this._highPrecisionShadersAllowed = options.useHighPrecisionFloats; } // Viewport var devicePixelRatio = _Misc_domManagement__WEBPACK_IMPORTED_MODULE_13__["DomManagement"].IsWindowObjectExist() ? (window.devicePixelRatio || 1.0) : 1.0; var limitDeviceRatio = options.limitDeviceRatio || devicePixelRatio; this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, devicePixelRatio) : 1.0; this.resize(); this._isStencilEnable = options.stencil ? true : false; this._initGLContext(); if (canvas) { var anyDoc_1 = document; // Fullscreen this._onFullscreenChange = function () { if (anyDoc_1.fullscreen !== undefined) { _this.isFullscreen = anyDoc_1.fullscreen; } else if (anyDoc_1.mozFullScreen !== undefined) { _this.isFullscreen = anyDoc_1.mozFullScreen; } else if (anyDoc_1.webkitIsFullScreen !== undefined) { _this.isFullscreen = anyDoc_1.webkitIsFullScreen; } else if (anyDoc_1.msIsFullScreen !== undefined) { _this.isFullscreen = anyDoc_1.msIsFullScreen; } // Pointer lock if (_this.isFullscreen && _this._pointerLockRequested && canvas) { canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock; if (canvas.requestPointerLock) { canvas.requestPointerLock(); } } }; document.addEventListener("fullscreenchange", this._onFullscreenChange, false); document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false); document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false); document.addEventListener("msfullscreenchange", this._onFullscreenChange, false); // Pointer lock this._onPointerLockChange = function () { _this.isPointerLock = (anyDoc_1.mozPointerLockElement === canvas || anyDoc_1.webkitPointerLockElement === canvas || anyDoc_1.msPointerLockElement === canvas || anyDoc_1.pointerLockElement === canvas); }; document.addEventListener("pointerlockchange", this._onPointerLockChange, false); document.addEventListener("mspointerlockchange", this._onPointerLockChange, false); document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false); document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false); this._onVRDisplayPointerRestricted = function () { if (canvas) { canvas.requestPointerLock(); } }; this._onVRDisplayPointerUnrestricted = function () { if (!anyDoc_1.exitPointerLock) { return; } anyDoc_1.exitPointerLock(); }; if (_Misc_domManagement__WEBPACK_IMPORTED_MODULE_13__["DomManagement"].IsWindowObjectExist()) { window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false); window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false); } } // Create Audio Engine if needed. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) { Engine.audioEngine = Engine.AudioEngineFactory(this.getRenderingCanvas()); } // Prepare buffer pointers for (var i = 0; i < this._caps.maxVertexAttribs; i++) { this._currentBufferPointers[i] = new BufferPointer(); } // Load WebVR Devices if (options.autoEnableWebVR) { this.initWebVR(); } // Detect if we are running on a faulty buggy OS. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent); // Detect if we are running on a faulty buggy desktop OS. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); console.log("Babylon.js v" + Engine.Version + " - " + this.description); this.enableOfflineSupport = Engine.OfflineProviderFactory !== undefined; } Object.defineProperty(Engine, "Instances", { /** Gets the list of created engines */ get: function () { return _engineStore__WEBPACK_IMPORTED_MODULE_15__["EngineStore"].Instances; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "LastCreatedEngine", { /** * Gets the latest created engine */ get: function () { return _engineStore__WEBPACK_IMPORTED_MODULE_15__["EngineStore"].LastCreatedEngine; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "LastCreatedScene", { /** * Gets the latest created scene */ get: function () { return _engineStore__WEBPACK_IMPORTED_MODULE_15__["EngineStore"].LastCreatedScene; }, enumerable: true, configurable: true }); /** * 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 */ Engine.MarkAllMaterialsAsDirty = function (flag, predicate) { for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) { var engine = Engine.Instances[engineIndex]; for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) { engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate); } } }; Object.defineProperty(Engine, "NpmPackage", { /** * Returns the current npm package of the sdk */ // Not mixed with Version for tooling purpose. get: function () { return "babylonjs@4.0.0-beta.3"; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "Version", { /** * Returns the current version of the framework */ get: function () { return "4.0.0-beta.3"; }, enumerable: true, configurable: true }); Object.defineProperty(Engine.prototype, "description", { /** * Returns a string describing the current engine */ get: function () { var description = "WebGL" + this.webGLVersion; if (this._caps.parallelShaderCompile) { description += " - Parallel shader compilation"; } return description; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "ShadersRepository", { /** * Gets or sets the relative url used to load shaders if using the engine in non-minified mode */ get: function () { return _Materials_effect__WEBPACK_IMPORTED_MODULE_8__["Effect"].ShadersRepository; }, set: function (value) { _Materials_effect__WEBPACK_IMPORTED_MODULE_8__["Effect"].ShadersRepository = value; }, enumerable: true, configurable: true }); /** * Method called to create the default loading screen. * This can be overriden in your own app. * @param canvas The rendering canvas element * @returns The loading screen */ Engine.DefaultLoadingScreenFactory = function (canvas) { throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_17__["_DevTools"].WarnImport("LoadingScreen"); }; Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", { /** * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input */ get: function () { return this._vrExclusivePointerMode; }, enumerable: true, configurable: true }); Object.defineProperty(Engine.prototype, "supportsUniformBuffers", { /** * Gets a boolean indicating that the engine supports uniform buffers * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets */ get: function () { return this.webGLVersion > 1 && !this.disableUniformBuffers; }, enumerable: true, configurable: true }); Object.defineProperty(Engine.prototype, "_shouldUseHighPrecisionShader", { /** @hidden */ get: function () { return this._caps.highPrecisionShaderSupported && this._highPrecisionShadersAllowed; }, enumerable: true, configurable: true }); Object.defineProperty(Engine.prototype, "needPOTTextures", { /** * 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: function () { return this._webGLVersion < 2 || this.forcePOTTextures; }, enumerable: true, configurable: true }); Object.defineProperty(Engine.prototype, "doNotHandleContextLost", { /** * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost */ get: function () { return this._doNotHandleContextLost; }, set: function (value) { this._doNotHandleContextLost = value; }, enumerable: true, configurable: true }); Object.defineProperty(Engine.prototype, "performanceMonitor", { /** * Gets the performance monitor attached to this engine * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation */ get: function () { return this._performanceMonitor; }, enumerable: true, configurable: true }); Object.defineProperty(Engine.prototype, "texturesSupported", { /** * Gets the list of texture formats supported */ get: function () { return this._texturesSupported; }, enumerable: true, configurable: true }); Object.defineProperty(Engine.prototype, "textureFormatInUse", { /** * Gets the list of texture formats in use */ get: function () { return this._textureFormatInUse; }, enumerable: true, configurable: true }); Object.defineProperty(Engine.prototype, "currentViewport", { /** * Gets the current viewport */ get: function () { return this._cachedViewport; }, enumerable: true, configurable: true }); Object.defineProperty(Engine.prototype, "emptyTexture", { /** * Gets the default empty texture */ get: function () { if (!this._emptyTexture) { this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE); } return this._emptyTexture; }, enumerable: true, configurable: true }); Object.defineProperty(Engine.prototype, "emptyTexture3D", { /** * Gets the default empty 3D texture */ get: function () { if (!this._emptyTexture3D) { this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE); } return this._emptyTexture3D; }, enumerable: true, configurable: true }); Object.defineProperty(Engine.prototype, "emptyCubeTexture", { /** * Gets the default empty cube texture */ get: function () { if (!this._emptyCubeTexture) { var faceData = new Uint8Array(4); var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData]; this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE); } return this._emptyCubeTexture; }, enumerable: true, configurable: true }); Engine.prototype._disableTouchAction = function () { if (!this._renderingCanvas) { return; } this._renderingCanvas.setAttribute("touch-action", "none"); this._renderingCanvas.style.touchAction = "none"; this._renderingCanvas.style.msTouchAction = "none"; }; Engine.prototype._rebuildInternalTextures = function () { var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) { var internalTexture = currentState_1[_i]; internalTexture._rebuild(); } }; Engine.prototype._rebuildEffects = function () { for (var key in this._compiledEffects) { var effect = this._compiledEffects[key]; effect._prepareEffect(); } _Materials_effect__WEBPACK_IMPORTED_MODULE_8__["Effect"].ResetCache(); }; /** * Gets a boolean indicating if all created effects are ready * @returns true if all effects are ready */ Engine.prototype.areAllEffectsReady = function () { for (var key in this._compiledEffects) { var effect = this._compiledEffects[key]; if (!effect.isReady()) { return false; } } return true; }; Engine.prototype._rebuildBuffers = function () { // Index / Vertex for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) { var scene = _a[_i]; scene.resetCachedMaterial(); scene._rebuildGeometries(); scene._rebuildTextures(); } // Uniforms for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) { var uniformBuffer = _c[_b]; uniformBuffer._rebuild(); } }; Engine.prototype._initGLContext = function () { // Caps this._caps = new EngineCapabilities(); this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS); this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS); this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS); this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE); this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE); this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE); this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS); this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS); this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS); this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS); // Infos this._glVersion = this._gl.getParameter(this._gl.VERSION); var 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 = "Unknown vendor"; } if (!this._glRenderer) { this._glRenderer = "Unknown renderer"; } // Constants this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit). if (this._gl.RGBA16F !== 0x881A) { this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format. } if (this._gl.RGBA32F !== 0x8814) { this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format. } if (this._gl.DEPTH24_STENCIL8 !== 35056) { this._gl.DEPTH24_STENCIL8 = 35056; } // Extensions this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null); this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc'); this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc'); this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'); this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1'); this._caps.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 this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic'); this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0; this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null; this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null; this._caps.highPrecisionShaderSupported = false; this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query"); 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; } // Checks if some of the format renders first to allow the use of webgl inspector. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float'); this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false; 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.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false; this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false; if (this._webGLVersion > 1) { this._gl.HALF_FLOAT_OES = 0x140B; } this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer(); this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false; this._caps.multiview = this._gl.getExtension('WEBGL_multiview'); // Draw buffers if (this._webGLVersion > 1) { this._caps.drawBuffersExtension = true; } else { var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers'); if (drawBuffersExtension !== null) { this._caps.drawBuffersExtension = true; this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension); this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER; for (var i = 0; i < 16; i++) { this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"]; } } else { this._caps.drawBuffersExtension = false; } } // Shader compiler threads this._caps.parallelShaderCompile = this._gl.getExtension('KHR_parallel_shader_compile'); // Depth Texture if (this._webGLVersion > 1) { this._caps.depthTextureExtension = true; } else { var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture'); if (depthTextureExtension != null) { this._caps.depthTextureExtension = true; this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL; } } // Vertex array object if (this.disableVertexArrayObjects) { this._caps.vertexArrayObject = false; } else if (this._webGLVersion > 1) { this._caps.vertexArrayObject = true; } else { var 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); } else { this._caps.vertexArrayObject = false; } } // Instances count if (this._webGLVersion > 1) { this._caps.instancedArrays = true; } else { var 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; } } // Intelligently add supported compressed formats in order to check for. // Check for ASTC support first as it is most powerful and to be very cross platform. // Next PVRTC & DXT, which are probably superior to ETC1/2. // Likely no hardware which supports both PVR & DXT, so order matters little. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first. if (this._caps.astc) { this.texturesSupported.push('-astc.ktx'); } if (this._caps.s3tc) { this.texturesSupported.push('-dxt.ktx'); } if (this._caps.pvrtc) { this.texturesSupported.push('-pvrtc.ktx'); } if (this._caps.etc2) { this.texturesSupported.push('-etc2.ktx'); } if (this._caps.etc1) { this.texturesSupported.push('-etc1.ktx'); } if (this._gl.getShaderPrecisionFormat) { var vertex_highp = this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER, this._gl.HIGH_FLOAT); var fragment_highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT); if (vertex_highp && fragment_highp) { this._caps.highPrecisionShaderSupported = vertex_highp.precision !== 0 && fragment_highp.precision !== 0; } } // Depth buffer this.setDepthBuffer(true); this.setDepthFunctionToLessOrEqual(); this.setDepthWrite(true); // Texture maps this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits; for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) { this._nextFreeTextureSlots.push(slot); } }; Object.defineProperty(Engine.prototype, "webGLVersion", { /** * Gets version of the current webGL context */ get: function () { return this._webGLVersion; }, enumerable: true, configurable: true }); Object.defineProperty(Engine.prototype, "isStencilEnable", { /** * Returns true if the stencil buffer has been enabled through the creation option of the context. */ get: function () { return this._isStencilEnable; }, enumerable: true, configurable: true }); Engine.prototype._prepareWorkingCanvas = function () { if (this._workingCanvas) { return; } this._workingCanvas = document.createElement("canvas"); var context = this._workingCanvas.getContext("2d"); if (context) { this._workingContext = context; } }; /** * Reset the texture cache to empty state */ Engine.prototype.resetTextureCache = function () { for (var key in this._boundTexturesCache) { if (!this._boundTexturesCache.hasOwnProperty(key)) { continue; } this._boundTexturesCache[key] = null; } this._currentTextureChannel = -1; }; /** * Gets a boolean indicating that the engine is running in deterministic lock step mode * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep * @returns true if engine is in deterministic lock step mode */ Engine.prototype.isDeterministicLockStep = function () { return this._deterministicLockstep; }; /** * Gets the max steps when engine is running in deterministic lock step * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep * @returns the max steps */ Engine.prototype.getLockstepMaxSteps = function () { return this._lockstepMaxSteps; }; /** * Gets an object containing information about the current webGL context * @returns an object containing the vender, the renderer and the version of the current webGL context */ Engine.prototype.getGlInfo = function () { return { vendor: this._glVendor, renderer: this._glRenderer, version: this._glVersion }; }; /** * Gets current aspect ratio * @param camera defines the camera to use to get the aspect ratio * @param useScreen defines if screen size must be used (or the current render target if any) * @returns a number defining the aspect ratio */ Engine.prototype.getAspectRatio = function (camera, useScreen) { if (useScreen === void 0) { useScreen = false; } var viewport = camera.viewport; return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height); }; /** * Gets current screen aspect ratio * @returns a number defining the aspect ratio */ Engine.prototype.getScreenAspectRatio = function () { return (this.getRenderWidth(true)) / (this.getRenderHeight(true)); }; /** * 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 */ Engine.prototype.getRenderWidth = function (useScreen) { if (useScreen === void 0) { useScreen = false; } if (!useScreen && this._currentRenderTarget) { return this._currentRenderTarget.width; } return 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 */ Engine.prototype.getRenderHeight = function (useScreen) { if (useScreen === void 0) { useScreen = false; } if (!useScreen && this._currentRenderTarget) { return this._currentRenderTarget.height; } return this._gl.drawingBufferHeight; }; /** * Gets the HTML canvas attached with the current webGL context * @returns a HTML canvas */ Engine.prototype.getRenderingCanvas = function () { return this._renderingCanvas; }; /** * Gets the client rect of the HTML canvas attached with the current webGL context * @returns a client rectanglee */ Engine.prototype.getRenderingCanvasClientRect = function () { if (!this._renderingCanvas) { return null; } return this._renderingCanvas.getBoundingClientRect(); }; /** * 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 */ Engine.prototype.setHardwareScalingLevel = function (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 */ Engine.prototype.getHardwareScalingLevel = function () { return this._hardwareScalingLevel; }; /** * Gets the list of loaded textures * @returns an array containing all loaded textures */ Engine.prototype.getLoadedTexturesCache = function () { return this._internalTexturesCache; }; /** * Gets the object containing all engine capabilities * @returns the EngineCapabilities object */ Engine.prototype.getCaps = function () { return this._caps; }; /** * Gets the current depth function * @returns a number defining the depth function */ Engine.prototype.getDepthFunction = function () { return this._depthCullingState.depthFunc; }; /** * Sets the current depth function * @param depthFunc defines the function to use */ Engine.prototype.setDepthFunction = function (depthFunc) { this._depthCullingState.depthFunc = depthFunc; }; /** * Sets the current depth function to GREATER */ Engine.prototype.setDepthFunctionToGreater = function () { this._depthCullingState.depthFunc = this._gl.GREATER; }; /** * Sets the current depth function to GEQUAL */ Engine.prototype.setDepthFunctionToGreaterOrEqual = function () { this._depthCullingState.depthFunc = this._gl.GEQUAL; }; /** * Sets the current depth function to LESS */ Engine.prototype.setDepthFunctionToLess = function () { this._depthCullingState.depthFunc = this._gl.LESS; }; /** * Caches the the state of the stencil buffer */ Engine.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(); }; /** * Restores the state of the stencil buffer */ Engine.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); }; /** * Sets the current depth function to LEQUAL */ Engine.prototype.setDepthFunctionToLessOrEqual = function () { this._depthCullingState.depthFunc = this._gl.LEQUAL; }; /** * Gets a boolean indicating if stencil buffer is enabled * @returns the current stencil buffer state */ Engine.prototype.getStencilBuffer = function () { return this._stencilState.stencilTest; }; /** * Enable or disable the stencil buffer * @param enable defines if the stencil buffer must be enabled or disabled */ Engine.prototype.setStencilBuffer = function (enable) { this._stencilState.stencilTest = enable; }; /** * Gets the current stencil mask * @returns a number defining the new stencil mask to use */ Engine.prototype.getStencilMask = function () { return this._stencilState.stencilMask; }; /** * Sets the current stencil mask * @param mask defines the new stencil mask to use */ Engine.prototype.setStencilMask = function (mask) { this._stencilState.stencilMask = mask; }; /** * Gets the current stencil function * @returns a number defining the stencil function to use */ Engine.prototype.getStencilFunction = function () { return this._stencilState.stencilFunc; }; /** * Gets the current stencil reference value * @returns a number defining the stencil reference value to use */ Engine.prototype.getStencilFunctionReference = function () { return this._stencilState.stencilFuncRef; }; /** * Gets the current stencil mask * @returns a number defining the stencil mask to use */ Engine.prototype.getStencilFunctionMask = function () { return this._stencilState.stencilFuncMask; }; /** * Sets the current stencil function * @param stencilFunc defines the new stencil function to use */ Engine.prototype.setStencilFunction = function (stencilFunc) { this._stencilState.stencilFunc = stencilFunc; }; /** * Sets the current stencil reference * @param reference defines the new stencil reference to use */ Engine.prototype.setStencilFunctionReference = function (reference) { this._stencilState.stencilFuncRef = reference; }; /** * Sets the current stencil mask * @param mask defines the new stencil mask to use */ Engine.prototype.setStencilFunctionMask = function (mask) { this._stencilState.stencilFuncMask = mask; }; /** * Gets the current stencil operation when stencil fails * @returns a number defining stencil operation to use when stencil fails */ Engine.prototype.getStencilOperationFail = function () { return this._stencilState.stencilOpStencilFail; }; /** * Gets the current stencil operation when depth fails * @returns a number defining stencil operation to use when depth fails */ Engine.prototype.getStencilOperationDepthFail = function () { return this._stencilState.stencilOpDepthFail; }; /** * Gets the current stencil operation when stencil passes * @returns a number defining stencil operation to use when stencil passes */ Engine.prototype.getStencilOperationPass = function () { return this._stencilState.stencilOpStencilDepthPass; }; /** * Sets the stencil operation to use when stencil fails * @param operation defines the stencil operation to use when stencil fails */ Engine.prototype.setStencilOperationFail = function (operation) { this._stencilState.stencilOpStencilFail = operation; }; /** * Sets the stencil operation to use when depth fails * @param operation defines the stencil operation to use when depth fails */ Engine.prototype.setStencilOperationDepthFail = function (operation) { this._stencilState.stencilOpDepthFail = operation; }; /** * Sets the stencil operation to use when stencil passes * @param operation defines the stencil operation to use when stencil passes */ Engine.prototype.setStencilOperationPass = function (operation) { this._stencilState.stencilOpStencilDepthPass = operation; }; /** * Sets a boolean indicating if the dithering state is enabled or disabled * @param value defines the dithering state */ Engine.prototype.setDitheringState = function (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 */ Engine.prototype.setRasterizerState = function (value) { if (value) { this._gl.disable(this._gl.RASTERIZER_DISCARD); } else { this._gl.enable(this._gl.RASTERIZER_DISCARD); } }; /** * 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. */ Engine.prototype.stopRenderLoop = function (renderFunction) { if (!renderFunction) { this._activeRenderLoops = []; return; } var index = this._activeRenderLoops.indexOf(renderFunction); if (index >= 0) { this._activeRenderLoops.splice(index, 1); } }; /** @hidden */ Engine.prototype._renderLoop = function () { if (!this._contextWasLost) { var shouldRender = true; if (!this.renderEvenInBackground && this._windowIsBackground) { shouldRender = false; } if (shouldRender) { // Start new frame this.beginFrame(); for (var index = 0; index < this._activeRenderLoops.length; index++) { var renderFunction = this._activeRenderLoops[index]; renderFunction(); } // Present this.endFrame(); } } if (this._activeRenderLoops.length > 0) { // Register new frame if (this.customAnimationFrameRequester) { this.customAnimationFrameRequester.requestID = _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].QueueNewFrame(this.customAnimationFrameRequester.renderFunction || this._bindedRenderFunction, this.customAnimationFrameRequester); this._frameHandler = this.customAnimationFrameRequester.requestID; } else if (this._vrDisplay && this._vrDisplay.isPresenting) { this._frameHandler = _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].QueueNewFrame(this._bindedRenderFunction, this._vrDisplay); } else { this._frameHandler = _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].QueueNewFrame(this._bindedRenderFunction); } } else { this._renderingQueueLaunched = false; } }; /** * Register and execute a render loop. The engine can have more than one render function * @param renderFunction defines the function to continuously execute */ Engine.prototype.runRenderLoop = function (renderFunction) { if (this._activeRenderLoops.indexOf(renderFunction) !== -1) { return; } this._activeRenderLoops.push(renderFunction); if (!this._renderingQueueLaunched) { this._renderingQueueLaunched = true; this._bindedRenderFunction = this._renderLoop.bind(this); this._frameHandler = _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].QueueNewFrame(this._bindedRenderFunction); } }; /** * Toggle full screen mode * @param requestPointerLock defines if a pointer lock should be requested from the user */ Engine.prototype.switchFullscreen = function (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 */ Engine.prototype.enterFullscreen = function (requestPointerLock) { if (!this.isFullscreen) { this._pointerLockRequested = requestPointerLock; if (this._renderingCanvas) { _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].RequestFullscreen(this._renderingCanvas); } } }; /** * Exits full screen mode */ Engine.prototype.exitFullscreen = function () { if (this.isFullscreen) { _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].ExitFullscreen(); } }; /** * 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 */ Engine.prototype.clear = function (color, backBuffer, depth, stencil) { if (stencil === void 0) { stencil = false; } this.applyStates(); var mode = 0; if (backBuffer && color) { this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0); mode |= this._gl.COLOR_BUFFER_BIT; } if (depth) { this._gl.clearDepth(1.0); mode |= this._gl.DEPTH_BUFFER_BIT; } if (stencil) { this._gl.clearStencil(0); mode |= this._gl.STENCIL_BUFFER_BIT; } this._gl.clear(mode); }; /** * Executes a scissor clear (ie. a clear on a specific portion of the screen) * @param x defines the x-coordinate of the top 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 */ Engine.prototype.scissorClear = function (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 top 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 */ Engine.prototype.enableScissor = function (x, y, width, height) { var gl = this._gl; // Change state gl.enable(gl.SCISSOR_TEST); gl.scissor(x, y, width, height); }; /** * Disable previously set scissor test rectangle */ Engine.prototype.disableScissor = function () { var gl = this._gl; gl.disable(gl.SCISSOR_TEST); }; /** @hidden */ Engine.prototype._viewport = function (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); } }; /** * 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 */ Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) { var width = requiredWidth || this.getRenderWidth(); var height = requiredHeight || this.getRenderHeight(); var x = viewport.x || 0; var y = viewport.y || 0; this._cachedViewport = viewport; this._viewport(x * width, y * height, width * viewport.width, height * viewport.height); }; /** * 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) * @return 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 */ Engine.prototype.setDirectViewport = function (x, y, width, height) { var currentViewport = this._cachedViewport; this._cachedViewport = null; this._viewport(x, y, width, height); return currentViewport; }; /** * Begin a new frame */ Engine.prototype.beginFrame = function () { this.onBeginFrameObservable.notifyObservers(this); this._measureFps(); }; /** * Enf the current frame */ Engine.prototype.endFrame = function () { // Force a flush in case we are using a bad OS. if (this._badOS) { this.flushFramebuffer(); } // Submit frame to the vr device, if enabled if (this._vrDisplay && this._vrDisplay.isPresenting) { // TODO: We should only submit the frame if we read frameData successfully. try { this._vrDisplay.submitFrame(); } catch (e) { _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].Warn("webVR submitFrame has had an unexpected failure: " + e); } } this.onEndFrameObservable.notifyObservers(this); }; /** * Resize the view according to the canvas' size */ Engine.prototype.resize = function () { // We're not resizing the size of the canvas while in VR mode & presenting if (!(this._vrDisplay && this._vrDisplay.isPresenting)) { var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth; var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight; this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel); } }; /** * Force a specific size of the canvas * @param width defines the new canvas' width * @param height defines the new canvas' height */ Engine.prototype.setSize = function (width, height) { if (!this._renderingCanvas) { return; } if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) { return; } this._renderingCanvas.width = width; this._renderingCanvas.height = height; for (var index = 0; index < this.scenes.length; index++) { var scene = this.scenes[index]; for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) { var cam = scene.cameras[camIndex]; cam._currentRenderId = 0; } } if (this.onResizeObservable.hasObservers) { this.onResizeObservable.notifyObservers(this); } }; // WebVR functions /** * Gets a boolean indicating if a webVR device was detected * @returns true if a webVR device was detected */ Engine.prototype.isVRDevicePresent = function () { return !!this._vrDisplay; }; /** * Gets the current webVR device * @returns the current webVR device (or null) */ Engine.prototype.getVRDevice = function () { return this._vrDisplay; }; /** * Initializes a webVR display and starts listening to display change events * The onVRDisplayChangedObservable will be notified upon these changes * @returns The onVRDisplayChangedObservable */ Engine.prototype.initWebVR = function () { this.initWebVRAsync(); return this.onVRDisplayChangedObservable; }; /** * Initializes a webVR display and starts listening to display change events * The onVRDisplayChangedObservable will be notified upon these changes * @returns A promise containing a VRDisplay and if vr is supported */ Engine.prototype.initWebVRAsync = function () { var _this = this; var notifyObservers = function () { var eventArgs = { vrDisplay: _this._vrDisplay, vrSupported: _this._vrSupported }; _this.onVRDisplayChangedObservable.notifyObservers(eventArgs); _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); }); }; if (!this._onVrDisplayConnect) { this._onVrDisplayConnect = function (event) { _this._vrDisplay = event.display; notifyObservers(); }; this._onVrDisplayDisconnect = function () { _this._vrDisplay.cancelAnimationFrame(_this._frameHandler); _this._vrDisplay = undefined; _this._frameHandler = _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].QueueNewFrame(_this._bindedRenderFunction); notifyObservers(); }; this._onVrDisplayPresentChange = function () { _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting; }; window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect); window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect); window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange); } this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync(); this._webVRInitPromise.then(notifyObservers); return this._webVRInitPromise; }; /** * Call this function to switch to webVR mode * Will do nothing if webVR is not supported or if there is no webVR device * @see http://doc.babylonjs.com/how_to/webvr_camera */ Engine.prototype.enableVR = function () { var _this = this; if (this._vrDisplay && !this._vrDisplay.isPresenting) { var onResolved = function () { _this.onVRRequestPresentComplete.notifyObservers(true); _this._onVRFullScreenTriggered(); }; var onRejected = function () { _this.onVRRequestPresentComplete.notifyObservers(false); }; this.onVRRequestPresentStart.notifyObservers(this); this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected); } }; /** * Call this function to leave webVR mode * Will do nothing if webVR is not supported or if there is no webVR device * @see http://doc.babylonjs.com/how_to/webvr_camera */ Engine.prototype.disableVR = function () { if (this._vrDisplay && this._vrDisplay.isPresenting) { this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered); } }; Engine.prototype._getVRDisplaysAsync = function () { var _this = this; return new Promise(function (res) { if (navigator.getVRDisplays) { navigator.getVRDisplays().then(function (devices) { _this._vrSupported = true; // note that devices may actually be an empty array. This is fine; // we expect this._vrDisplay to be undefined in this case. _this._vrDisplay = devices[0]; res({ vrDisplay: _this._vrDisplay, vrSupported: _this._vrSupported }); }); } else { _this._vrDisplay = undefined; _this._vrSupported = false; res({ vrDisplay: _this._vrDisplay, vrSupported: _this._vrSupported }); } }); }; /** * Binds the frame buffer to the specified texture. * @param texture The texture to render to or null for the default canvas * @param faceIndex The face of the texture to render to in case of cube texture * @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 depthStencilTexture The depth stencil texture to use to render * @param lodLevel defines le lod level to bind to the frame buffer */ Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) { if (lodLevel === void 0) { lodLevel = 0; } if (this._currentRenderTarget) { this.unBindFramebuffer(this._currentRenderTarget); } this._currentRenderTarget = texture; this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer); var gl = this._gl; if (texture.isCube) { if (faceIndex === undefined) { faceIndex = 0; } gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel); if (depthStencilTexture) { if (depthStencilTexture._generateStencilBuffer) { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel); } else { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel); } } } if (this._cachedViewport && !forceFullscreenViewport) { this.setViewport(this._cachedViewport, requiredWidth, requiredHeight); } else { if (!requiredWidth) { requiredWidth = texture.width; if (lodLevel) { requiredWidth = requiredWidth / Math.pow(2, lodLevel); } } if (!requiredHeight) { requiredHeight = texture.height; if (lodLevel) { requiredHeight = requiredHeight / Math.pow(2, lodLevel); } } this._viewport(0, 0, requiredWidth, requiredHeight); } this.wipeCaches(); }; Engine.prototype.bindUnboundFramebuffer = function (framebuffer) { if (this._currentFramebuffer !== framebuffer) { this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer); this._currentFramebuffer = framebuffer; } }; /** * Unbind the current render target texture from the webGL context * @param texture defines the render target texture 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 */ Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) { if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; } this._currentRenderTarget = null; // If MSAA, we need to bitblt back to main texture var gl = this._gl; if (texture._MSAAFramebuffer) { gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer); gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer); gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST); } if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) { this._bindTextureDirectly(gl.TEXTURE_2D, texture, true); gl.generateMipmap(gl.TEXTURE_2D); this._bindTextureDirectly(gl.TEXTURE_2D, null); } if (onBeforeUnbind) { if (texture._MSAAFramebuffer) { // Bind the correct framebuffer this.bindUnboundFramebuffer(texture._framebuffer); } onBeforeUnbind(); } this.bindUnboundFramebuffer(null); }; /** * Unbind a list of render target textures from the webGL context * This is used only when drawBuffer extension or webGL2 are active * @param textures defines the render target textures 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 */ Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) { if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; } this._currentRenderTarget = null; // If MSAA, we need to bitblt back to main texture var gl = this._gl; if (textures[0]._MSAAFramebuffer) { gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer); gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer); var attachments = textures[0]._attachments; if (!attachments) { attachments = new Array(textures.length); textures[0]._attachments = attachments; } for (var i = 0; i < textures.length; i++) { var texture = textures[i]; for (var j = 0; j < attachments.length; j++) { attachments[j] = gl.NONE; } attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"]; gl.readBuffer(attachments[i]); gl.drawBuffers(attachments); gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST); } for (var i = 0; i < attachments.length; i++) { attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"]; } gl.drawBuffers(attachments); } for (var i = 0; i < textures.length; i++) { var texture = textures[i]; if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) { this._bindTextureDirectly(gl.TEXTURE_2D, texture); gl.generateMipmap(gl.TEXTURE_2D); this._bindTextureDirectly(gl.TEXTURE_2D, null); } } if (onBeforeUnbind) { if (textures[0]._MSAAFramebuffer) { // Bind the correct framebuffer this.bindUnboundFramebuffer(textures[0]._framebuffer); } onBeforeUnbind(); } this.bindUnboundFramebuffer(null); }; /** * Force the mipmap generation for the given render target texture * @param texture defines the render target texture to use */ Engine.prototype.generateMipMapsForCubemap = function (texture) { if (texture.generateMipMaps) { var gl = this._gl; this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); gl.generateMipmap(gl.TEXTURE_CUBE_MAP); this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); } }; /** * Force a webGL flush (ie. a flush of all waiting webGL commands) */ Engine.prototype.flushFramebuffer = function () { this._gl.flush(); }; /** * Unbind the current render target and bind the default framebuffer */ Engine.prototype.restoreDefaultFramebuffer = function () { if (this._currentRenderTarget) { this.unBindFramebuffer(this._currentRenderTarget); } else { this.bindUnboundFramebuffer(null); } if (this._cachedViewport) { this.setViewport(this._cachedViewport); } this.wipeCaches(); }; // UBOs /** * Create an uniform buffer * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets * @param elements defines the content of the uniform buffer * @returns the webGL uniform buffer */ Engine.prototype.createUniformBuffer = function (elements) { var ubo = this._gl.createBuffer(); if (!ubo) { throw new Error("Unable to create uniform buffer"); } this.bindUniformBuffer(ubo); 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); ubo.references = 1; return ubo; }; /** * Create a dynamic uniform buffer * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets * @param elements defines the content of the uniform buffer * @returns the webGL uniform buffer */ Engine.prototype.createDynamicUniformBuffer = function (elements) { var ubo = this._gl.createBuffer(); if (!ubo) { throw new Error("Unable to create dynamic uniform buffer"); } this.bindUniformBuffer(ubo); 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); ubo.references = 1; return ubo; }; /** * Update an existing uniform buffer * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets * @param uniformBuffer defines the target uniform buffer * @param elements defines the content to update * @param offset defines the offset in the uniform buffer where update should start * @param count defines the size of the data to update */ Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) { this.bindUniformBuffer(uniformBuffer); if (offset === undefined) { offset = 0; } if (count === undefined) { if (elements instanceof Float32Array) { this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements); } else { this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements)); } } else { if (elements instanceof Float32Array) { this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count)); } else { this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count)); } } this.bindUniformBuffer(null); }; // VBOs Engine.prototype._resetVertexBufferBinding = function () { this.bindArrayBuffer(null); this._cachedVertexBuffers = null; }; /** * Creates a vertex buffer * @param data the data for the vertex buffer * @returns the new WebGL static buffer */ Engine.prototype.createVertexBuffer = function (data) { var vbo = this._gl.createBuffer(); if (!vbo) { throw new Error("Unable to create vertex buffer"); } this.bindArrayBuffer(vbo); if (data instanceof Array) { this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW); } else { this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW); } this._resetVertexBufferBinding(); vbo.references = 1; return vbo; }; /** * Creates a dynamic vertex buffer * @param data the data for the dynamic vertex buffer * @returns the new WebGL dynamic buffer */ Engine.prototype.createDynamicVertexBuffer = function (data) { var vbo = this._gl.createBuffer(); if (!vbo) { throw new Error("Unable to create dynamic vertex buffer"); } this.bindArrayBuffer(vbo); if (data instanceof Array) { this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW); } else { this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW); } this._resetVertexBufferBinding(); vbo.references = 1; return vbo; }; /** * Update a dynamic index buffer * @param indexBuffer defines the target index buffer * @param indices defines the data to update * @param offset defines the offset in the target index buffer where update should start */ Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) { if (offset === void 0) { offset = 0; } // Force cache update this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null; this.bindIndexBuffer(indexBuffer); var arrayBuffer; if (indices instanceof Uint16Array || indices instanceof Uint32Array) { arrayBuffer = indices; } else { arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices); } this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW); this._resetIndexBufferBinding(); }; /** * Updates a dynamic vertex buffer. * @param vertexBuffer the vertex buffer to update * @param data the data used to update the vertex buffer * @param byteOffset the byte offset of the data * @param byteLength the byte length of the data */ Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) { this.bindArrayBuffer(vertexBuffer); if (byteOffset === undefined) { byteOffset = 0; } if (byteLength === undefined) { 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, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength)); } else { if (data instanceof ArrayBuffer) { data = new Uint8Array(data, byteOffset, byteLength); } else { var offset = data.byteOffset + byteOffset; if (offset || byteLength !== data.byteLength) { data = new Uint8Array(data.buffer, offset, byteLength); } } this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data); } } this._resetVertexBufferBinding(); }; Engine.prototype._resetIndexBufferBinding = function () { 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 * @returns a new webGL buffer */ Engine.prototype.createIndexBuffer = function (indices, updatable) { var vbo = this._gl.createBuffer(); if (!vbo) { throw new Error("Unable to create index buffer"); } this.bindIndexBuffer(vbo); // Check for 32 bits indices var arrayBuffer; var need32Bits = false; if (indices instanceof Uint16Array) { arrayBuffer = indices; } else { //check 32 bit support if (this._caps.uintIndices) { if (indices instanceof Uint32Array) { arrayBuffer = indices; need32Bits = true; } else { //number[] or Int32Array, check if 32 bit is necessary for (var index = 0; index < indices.length; index++) { if (indices[index] > 65535) { need32Bits = true; break; } } arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices); } } else { //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost) arrayBuffer = new Uint16Array(indices); } } this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW); this._resetIndexBufferBinding(); vbo.references = 1; vbo.is32Bits = need32Bits; return vbo; }; /** * Bind a webGL buffer to the webGL context * @param buffer defines the buffer to bind */ Engine.prototype.bindArrayBuffer = function (buffer) { if (!this._vaoRecordInProgress) { this._unbindVertexArrayObject(); } this.bindBuffer(buffer, this._gl.ARRAY_BUFFER); }; /** * Bind an uniform buffer to the current webGL context * @param buffer defines the buffer to bind */ Engine.prototype.bindUniformBuffer = function (buffer) { this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer); }; /** * Bind a buffer to the current webGL context at a given location * @param buffer defines the buffer to bind * @param location defines the index where to bind the buffer */ Engine.prototype.bindUniformBufferBase = function (buffer, location) { this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer); }; /** * Bind a specific block at a given index in a specific shader program * @param shaderProgram defines the shader program * @param blockName defines the block name * @param index defines the index where to bind the block */ Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) { var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName); this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index); }; Engine.prototype.bindIndexBuffer = function (buffer) { if (!this._vaoRecordInProgress) { this._unbindVertexArrayObject(); } this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER); }; Engine.prototype.bindBuffer = function (buffer, target) { if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) { this._gl.bindBuffer(target, buffer); this._currentBoundBuffer[target] = buffer; } }; /** * update the bound buffer with the given data * @param data defines the data to update */ Engine.prototype.updateArrayBuffer = function (data) { this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data); }; Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) { var pointer = this._currentBufferPointers[indx]; var 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); this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset); } }; Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) { if (indexBuffer == null) { return; } if (this._cachedIndexBuffer !== indexBuffer) { this._cachedIndexBuffer = indexBuffer; this.bindIndexBuffer(indexBuffer); this._uintIndicesCurrentlySet = indexBuffer.is32Bits; } }; Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) { var attributes = effect.getAttributesNames(); if (!this._vaoRecordInProgress) { this._unbindVertexArrayObject(); } this.unbindAllAttributes(); for (var index = 0; index < attributes.length; index++) { var order = effect.getAttributeLocation(index); if (order >= 0) { var vertexBuffer = vertexBuffers[attributes[index]]; if (!vertexBuffer) { continue; } this._gl.enableVertexAttribArray(order); if (!this._vaoRecordInProgress) { this._vertexAttribArraysEnabled[order] = true; } var 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 http://doc.babylonjs.com/features/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 * @returns the new vertex array object */ Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) { var vao = this._gl.createVertexArray(); this._vaoRecordInProgress = true; this._gl.bindVertexArray(vao); this._mustWipeVertexAttributes = true; this._bindVertexBuffersAttributes(vertexBuffers, effect); this.bindIndexBuffer(indexBuffer); this._vaoRecordInProgress = false; this._gl.bindVertexArray(null); return vao; }; /** * Bind a specific vertex array object * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects * @param vertexArrayObject defines the vertex array object to bind * @param indexBuffer defines the index buffer to bind */ Engine.prototype.bindVertexArrayObject = function (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 */ Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) { if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) { this._cachedVertexBuffers = vertexBuffer; this._cachedEffectForVertexBuffers = effect; var attributesCount = effect.getAttributesCount(); this._unbindVertexArrayObject(); this.unbindAllAttributes(); var offset = 0; for (var index = 0; index < attributesCount; index++) { if (index < vertexDeclaration.length) { var 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); }; Engine.prototype._unbindVertexArrayObject = function () { 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 */ Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) { if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) { this._cachedVertexBuffers = vertexBuffers; this._cachedEffectForVertexBuffers = effect; this._bindVertexBuffersAttributes(vertexBuffers, effect); } this._bindIndexBufferWithCache(indexBuffer); }; /** * Unbind all instance attributes */ Engine.prototype.unbindInstanceAttributes = function () { var boundBuffer; for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) { var instancesBuffer = this._currentInstanceBuffers[i]; if (boundBuffer != instancesBuffer && instancesBuffer.references) { boundBuffer = instancesBuffer; this.bindArrayBuffer(instancesBuffer); } var 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 */ Engine.prototype.releaseVertexArrayObject = function (vao) { this._gl.deleteVertexArray(vao); }; /** @hidden */ Engine.prototype._releaseBuffer = function (buffer) { buffer.references--; if (buffer.references === 0) { this._gl.deleteBuffer(buffer); return true; } return false; }; /** * Creates a webGL buffer to use with instanciation * @param capacity defines the size of the buffer * @returns the webGL buffer */ Engine.prototype.createInstancesBuffer = function (capacity) { var buffer = this._gl.createBuffer(); if (!buffer) { throw new Error("Unable to create instance buffer"); } buffer.capacity = capacity; this.bindArrayBuffer(buffer); this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW); return buffer; }; /** * Delete a webGL buffer used with instanciation * @param buffer defines the webGL buffer to delete */ Engine.prototype.deleteInstancesBuffer = function (buffer) { this._gl.deleteBuffer(buffer); }; /** * Update the content of a webGL buffer used with instanciation 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 */ Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) { this.bindArrayBuffer(instancesBuffer); if (data) { this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data); } if (offsetLocations[0].index !== undefined) { var stride = 0; for (var i = 0; i < offsetLocations.length; i++) { var ai = offsetLocations[i]; stride += ai.attributeSize * 4; } for (var i = 0; i < offsetLocations.length; i++) { var ai = offsetLocations[i]; if (!this._vertexAttribArraysEnabled[ai.index]) { this._gl.enableVertexAttribArray(ai.index); this._vertexAttribArraysEnabled[ai.index] = true; } this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset); this._gl.vertexAttribDivisor(ai.index, 1); this._currentInstanceLocations.push(ai.index); this._currentInstanceBuffers.push(instancesBuffer); } } else { for (var index = 0; index < 4; index++) { var 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); } } }; /** * Apply all cached states (depth, culling, stencil and alpha) */ Engine.prototype.applyStates = function () { this._depthCullingState.apply(this._gl); this._stencilState.apply(this._gl); this._alphaState.apply(this._gl); }; /** * 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 instanciation is enabled) */ Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) { this.drawElementsType(useTriangles ? _Materials_material__WEBPACK_IMPORTED_MODULE_9__["Material"].TriangleFillMode : _Materials_material__WEBPACK_IMPORTED_MODULE_9__["Material"].WireFrameFillMode, 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 instanciation is enabled) */ Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) { this.drawArraysType(_Materials_material__WEBPACK_IMPORTED_MODULE_9__["Material"].PointFillMode, 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 instanciation is enabled) */ Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) { this.drawArraysType(useTriangles ? _Materials_material__WEBPACK_IMPORTED_MODULE_9__["Material"].TriangleFillMode : _Materials_material__WEBPACK_IMPORTED_MODULE_9__["Material"].WireFrameFillMode, 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 instanciation is enabled) */ Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) { // Apply states this.applyStates(); this._drawCalls.addCount(1, false); // Render var drawMode = this._drawMode(fillMode); var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT; var 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 instanciation is enabled) */ Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) { // Apply states this.applyStates(); this._drawCalls.addCount(1, false); var drawMode = this._drawMode(fillMode); if (instancesCount) { this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount); } else { this._gl.drawArrays(drawMode, verticesStart, verticesCount); } }; Engine.prototype._drawMode = function (fillMode) { switch (fillMode) { // Triangle views case _Materials_material__WEBPACK_IMPORTED_MODULE_9__["Material"].TriangleFillMode: return this._gl.TRIANGLES; case _Materials_material__WEBPACK_IMPORTED_MODULE_9__["Material"].PointFillMode: return this._gl.POINTS; case _Materials_material__WEBPACK_IMPORTED_MODULE_9__["Material"].WireFrameFillMode: return this._gl.LINES; // Draw modes case _Materials_material__WEBPACK_IMPORTED_MODULE_9__["Material"].PointListDrawMode: return this._gl.POINTS; case _Materials_material__WEBPACK_IMPORTED_MODULE_9__["Material"].LineListDrawMode: return this._gl.LINES; case _Materials_material__WEBPACK_IMPORTED_MODULE_9__["Material"].LineLoopDrawMode: return this._gl.LINE_LOOP; case _Materials_material__WEBPACK_IMPORTED_MODULE_9__["Material"].LineStripDrawMode: return this._gl.LINE_STRIP; case _Materials_material__WEBPACK_IMPORTED_MODULE_9__["Material"].TriangleStripDrawMode: return this._gl.TRIANGLE_STRIP; case _Materials_material__WEBPACK_IMPORTED_MODULE_9__["Material"].TriangleFanDrawMode: return this._gl.TRIANGLE_FAN; default: return this._gl.TRIANGLES; } }; // Shaders /** @hidden */ Engine.prototype._releaseEffect = function (effect) { if (this._compiledEffects[effect._key]) { delete this._compiledEffects[effect._key]; this._deleteProgram(effect.getProgram()); } }; /** @hidden */ Engine.prototype._deleteProgram = function (program) { if (program) { program.__SPECTOR_rebuildProgram = null; if (program.transformFeedback) { this.deleteTransformFeedback(program.transformFeedback); program.transformFeedback = null; } this._gl.deleteProgram(program); } }; /** * 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 EffectCreationOptions 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 conmpilation 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) * @returns the new Effect */ Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) { var vertex = baseName.vertexElement || baseName.vertex || baseName; var fragment = baseName.fragmentElement || baseName.fragment || baseName; var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines); if (this._compiledEffects[name]) { var compiledEffect = this._compiledEffects[name]; if (onCompiled && compiledEffect.isReady()) { onCompiled(compiledEffect); } return compiledEffect; } var effect = new _Materials_effect__WEBPACK_IMPORTED_MODULE_8__["Effect"](baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters); effect._key = name; this._compiledEffects[name] = effect; return effect; }; Engine.prototype._compileShader = function (source, type, defines, shaderVersion) { return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type); }; Engine.prototype._compileRawShader = function (source, type) { var gl = this._gl; var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER); if (!shader) { throw new Error("Something went wrong while compile the shader."); } gl.shaderSource(shader, source); gl.compileShader(shader); return shader; }; /** * Directly creates a webGL program * @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 */ Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) { if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; } context = context || this._gl; var vertexShader = this._compileRawShader(vertexCode, "vertex"); var fragmentShader = this._compileRawShader(fragmentCode, "fragment"); return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings); }; /** * Creates a webGL program * @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 */ Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) { if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; } context = context || this._gl; this.onBeforeShaderCompilationObservable.notifyObservers(this); var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : ""; var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion); var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion); var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings); this.onAfterShaderCompilationObservable.notifyObservers(this); return program; }; Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) { if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; } var shaderProgram = context.createProgram(); if (!shaderProgram) { throw new Error("Unable to create program"); } if (this._caps.parallelShaderCompile) { shaderProgram.isParallelCompiled = true; } context.attachShader(shaderProgram, vertexShader); context.attachShader(shaderProgram, fragmentShader); if (this.webGLVersion > 1 && transformFeedbackVaryings) { var transformFeedback = this.createTransformFeedback(); this.bindTransformFeedback(transformFeedback); this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings); shaderProgram.transformFeedback = transformFeedback; } context.linkProgram(shaderProgram); if (this.webGLVersion > 1 && transformFeedbackVaryings) { this.bindTransformFeedback(null); } shaderProgram.context = context; shaderProgram.vertexShader = vertexShader; shaderProgram.fragmentShader = fragmentShader; if (!shaderProgram.isParallelCompiled) { this._finalizeProgram(shaderProgram); } return shaderProgram; }; Engine.prototype._finalizeProgram = function (shaderProgram) { var context = shaderProgram.context; var vertexShader = shaderProgram.vertexShader; var fragmentShader = shaderProgram.fragmentShader; var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS); if (!linked) { // Get more info // Vertex if (!this._gl.getShaderParameter(vertexShader, this._gl.COMPILE_STATUS)) { var log = this._gl.getShaderInfoLog(vertexShader); if (log) { throw new Error(log); } } // Fragment if (!this._gl.getShaderParameter(fragmentShader, this._gl.COMPILE_STATUS)) { var log = this._gl.getShaderInfoLog(fragmentShader); if (log) { throw new Error(log); } } var error = context.getProgramInfoLog(shaderProgram); if (error) { throw new Error(error); } } if (this.validateShaderPrograms) { context.validateProgram(shaderProgram); var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS); if (!validated) { var error = context.getProgramInfoLog(shaderProgram); if (error) { throw new Error(error); } } } context.deleteShader(vertexShader); context.deleteShader(fragmentShader); shaderProgram.context = undefined; shaderProgram.vertexShader = undefined; shaderProgram.fragmentShader = undefined; if (shaderProgram.onCompiled) { shaderProgram.onCompiled(); shaderProgram.onCompiled = undefined; } }; /** @hidden */ Engine.prototype._isProgramCompiled = function (shaderProgram) { if (!shaderProgram.isParallelCompiled) { return true; } if (this._gl.getProgramParameter(shaderProgram, this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)) { this._finalizeProgram(shaderProgram); return true; } return false; }; /** @hidden */ Engine.prototype._executeWhenProgramIsCompiled = function (shaderProgram, action) { if (!shaderProgram.isParallelCompiled) { action(); return; } shaderProgram.onCompiled = action; }; /** * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names * @param shaderProgram defines the webGL program to use * @param uniformsNames defines the list of uniform names * @returns an array of webGL uniform locations */ Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) { var results = new Array(); for (var index = 0; index < uniformsNames.length; index++) { results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index])); } return results; }; /** * Gets the lsit of active attributes for a given webGL program * @param shaderProgram defines the webGL program to use * @param attributesNames defines the list of attribute names to get * @returns an array of indices indicating the offset of each attribute */ Engine.prototype.getAttributes = function (shaderProgram, attributesNames) { var results = []; for (var index = 0; index < attributesNames.length; index++) { try { results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index])); } catch (e) { results.push(-1); } } return results; }; /** * Activates an effect, mkaing it the current one (ie. the one used for rendering) * @param effect defines the effect to activate */ Engine.prototype.enableEffect = function (effect) { if (!effect || effect === this._currentEffect) { return; } // Use program this.bindSamplers(effect); this._currentEffect = effect; if (effect.onBind) { effect.onBind(effect); } if (effect._onBindObservable) { effect._onBindObservable.notifyObservers(effect); } }; /** * Set the value of an uniform to 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 */ Engine.prototype.setIntArray = function (uniform, array) { if (!uniform) { return; } this._gl.uniform1iv(uniform, array); }; /** * 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 */ Engine.prototype.setIntArray2 = function (uniform, array) { if (!uniform || array.length % 2 !== 0) { return; } this._gl.uniform2iv(uniform, array); }; /** * 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 */ Engine.prototype.setIntArray3 = function (uniform, array) { if (!uniform || array.length % 3 !== 0) { return; } this._gl.uniform3iv(uniform, array); }; /** * 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 */ Engine.prototype.setIntArray4 = function (uniform, array) { if (!uniform || array.length % 4 !== 0) { return; } this._gl.uniform4iv(uniform, array); }; /** * Set the value of an uniform to an array of float32 * @param uniform defines the webGL uniform location where to store the value * @param array defines the array of float32 to store */ Engine.prototype.setFloatArray = function (uniform, array) { if (!uniform) { return; } this._gl.uniform1fv(uniform, array); }; /** * Set the value of an uniform to an array of float32 (stored as vec2) * @param uniform defines the webGL uniform location where to store the value * @param array defines the array of float32 to store */ Engine.prototype.setFloatArray2 = function (uniform, array) { if (!uniform || array.length % 2 !== 0) { return; } this._gl.uniform2fv(uniform, array); }; /** * Set the value of an uniform to an array of float32 (stored as vec3) * @param uniform defines the webGL uniform location where to store the value * @param array defines the array of float32 to store */ Engine.prototype.setFloatArray3 = function (uniform, array) { if (!uniform || array.length % 3 !== 0) { return; } this._gl.uniform3fv(uniform, array); }; /** * Set the value of an uniform to an array of float32 (stored as vec4) * @param uniform defines the webGL uniform location where to store the value * @param array defines the array of float32 to store */ Engine.prototype.setFloatArray4 = function (uniform, array) { if (!uniform || array.length % 4 !== 0) { return; } this._gl.uniform4fv(uniform, array); }; /** * 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 */ Engine.prototype.setArray = function (uniform, array) { if (!uniform) { return; } this._gl.uniform1fv(uniform, array); }; /** * 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 */ Engine.prototype.setArray2 = function (uniform, array) { if (!uniform || array.length % 2 !== 0) { return; } this._gl.uniform2fv(uniform, array); }; /** * 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 */ Engine.prototype.setArray3 = function (uniform, array) { if (!uniform || array.length % 3 !== 0) { return; } this._gl.uniform3fv(uniform, array); }; /** * 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 */ Engine.prototype.setArray4 = function (uniform, array) { if (!uniform || array.length % 4 !== 0) { return; } this._gl.uniform4fv(uniform, array); }; /** * 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 */ Engine.prototype.setMatrices = function (uniform, matrices) { if (!uniform) { return; } this._gl.uniformMatrix4fv(uniform, false, matrices); }; /** * Set the value of an uniform to a matrix * @param uniform defines the webGL uniform location where to store the value * @param matrix defines the matrix to store */ Engine.prototype.setMatrix = function (uniform, matrix) { if (!uniform) { return; } this._gl.uniformMatrix4fv(uniform, false, matrix.toArray()); }; /** * 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 */ Engine.prototype.setMatrix3x3 = function (uniform, matrix) { if (!uniform) { return; } this._gl.uniformMatrix3fv(uniform, false, matrix); }; /** * 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 */ Engine.prototype.setMatrix2x2 = function (uniform, matrix) { if (!uniform) { return; } this._gl.uniformMatrix2fv(uniform, false, matrix); }; /** * 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 */ Engine.prototype.setInt = function (uniform, value) { if (!uniform) { return; } this._gl.uniform1i(uniform, value); }; /** * 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 */ Engine.prototype.setFloat = function (uniform, value) { if (!uniform) { return; } this._gl.uniform1f(uniform, value); }; /** * 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 */ Engine.prototype.setFloat2 = function (uniform, x, y) { if (!uniform) { return; } this._gl.uniform2f(uniform, x, y); }; /** * 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 */ Engine.prototype.setFloat3 = function (uniform, x, y, z) { if (!uniform) { return; } this._gl.uniform3f(uniform, x, y, z); }; /** * Set the value of an uniform to a boolean * @param uniform defines the webGL uniform location where to store the value * @param bool defines the boolean to store */ Engine.prototype.setBool = function (uniform, bool) { if (!uniform) { return; } this._gl.uniform1i(uniform, bool); }; /** * 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 */ Engine.prototype.setFloat4 = function (uniform, x, y, z, w) { if (!uniform) { return; } this._gl.uniform4f(uniform, x, y, z, w); }; /** * Set the value of an uniform to a Color3 * @param uniform defines the webGL uniform location where to store the value * @param color3 defines the color to store */ Engine.prototype.setColor3 = function (uniform, color3) { if (!uniform) { return; } this._gl.uniform3f(uniform, color3.r, color3.g, color3.b); }; /** * Set the value of an uniform to a Color3 and an alpha value * @param uniform defines the webGL uniform location where to store the value * @param color3 defines the color to store * @param alpha defines the alpha component to store */ Engine.prototype.setColor4 = function (uniform, color3, alpha) { if (!uniform) { return; } this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha); }; /** * Sets a Color4 on a uniform variable * @param uniform defines the uniform location * @param color4 defines the value to be set */ Engine.prototype.setDirectColor4 = function (uniform, color4) { if (!uniform) { return; } this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a); }; // States /** * Set various states to the webGL context * @param culling defines backface culling state * @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 instead of CW and CW instead of CCW) */ Engine.prototype.setState = function (culling, zOffset, force, reverseSide) { if (zOffset === void 0) { zOffset = 0; } if (reverseSide === void 0) { reverseSide = false; } // Culling if (this._depthCullingState.cull !== culling || force) { this._depthCullingState.cull = culling; } // Cull face var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT; if (this._depthCullingState.cullFace !== cullFace || force) { this._depthCullingState.cullFace = cullFace; } // Z offset this.setZOffset(zOffset); // Front face var frontFace = reverseSide ? this._gl.CW : this._gl.CCW; if (this._depthCullingState.frontFace !== frontFace || force) { this._depthCullingState.frontFace = frontFace; } }; /** * Set the z offset to apply to current rendering * @param value defines the offset to apply */ Engine.prototype.setZOffset = function (value) { this._depthCullingState.zOffset = value; }; /** * Gets the current value of the zOffset * @returns the current zOffset state */ Engine.prototype.getZOffset = function () { return this._depthCullingState.zOffset; }; /** * Enable or disable depth buffering * @param enable defines the state to set */ Engine.prototype.setDepthBuffer = function (enable) { this._depthCullingState.depthTest = enable; }; /** * Gets a boolean indicating if depth writing is enabled * @returns the current depth writing state */ Engine.prototype.getDepthWrite = function () { return this._depthCullingState.depthMask; }; /** * Enable or disable depth writing * @param enable defines the state to set */ Engine.prototype.setDepthWrite = function (enable) { this._depthCullingState.depthMask = enable; }; /** * Enable or disable color writing * @param enable defines the state to set */ Engine.prototype.setColorWrite = function (enable) { this._gl.colorMask(enable, enable, enable, enable); this._colorWrite = enable; }; /** * Gets a boolean indicating if color writing is enabled * @returns the current color writing state */ Engine.prototype.getColorWrite = function () { return this._colorWrite; }; /** * Sets alpha constants used by some alpha blending modes * @param r defines the red component * @param g defines the green component * @param b defines the blue component * @param a defines the alpha component */ Engine.prototype.setAlphaConstants = function (r, g, b, a) { this._alphaState.setAlphaBlendConstants(r, g, b, a); }; /** * Sets the current alpha mode * @param mode defines the mode to use (one of the Engine.ALPHA_XXX) * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default) * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered */ Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) { if (noDepthWriteChange === void 0) { noDepthWriteChange = false; } if (this._alphaMode === mode) { return; } switch (mode) { case Engine.ALPHA_DISABLE: this._alphaState.alphaBlend = false; break; case Engine.ALPHA_PREMULTIPLIED: this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE); this._alphaState.alphaBlend = true; break; case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF: this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA); this._alphaState.alphaBlend = true; break; case Engine.ALPHA_COMBINE: this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE); this._alphaState.alphaBlend = true; break; case Engine.ALPHA_ONEONE: this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE); this._alphaState.alphaBlend = true; break; case Engine.ALPHA_ADD: this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE); this._alphaState.alphaBlend = true; break; case Engine.ALPHA_SUBTRACT: this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE); this._alphaState.alphaBlend = true; break; case Engine.ALPHA_MULTIPLY: this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE); this._alphaState.alphaBlend = true; break; case Engine.ALPHA_MAXIMIZED: this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE); this._alphaState.alphaBlend = true; break; case Engine.ALPHA_INTERPOLATE: this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA); this._alphaState.alphaBlend = true; break; case Engine.ALPHA_SCREENMODE: this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA); this._alphaState.alphaBlend = true; break; } if (!noDepthWriteChange) { this.setDepthWrite(mode === Engine.ALPHA_DISABLE); } this._alphaMode = mode; }; /** * Gets the current alpha mode * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered * @returns the current alpha mode */ Engine.prototype.getAlphaMode = function () { return this._alphaMode; }; // Textures /** * Clears the list of texture accessible through engine. * This can help preventing texture load conflict due to name collision. */ Engine.prototype.clearInternalTexturesCache = function () { this._internalTexturesCache = []; }; /** * 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) */ Engine.prototype.wipeCaches = function (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; if (bruteForce) { this.resetTextureCache(); this._currentProgram = null; this._stencilState.reset(); this._depthCullingState.reset(); this.setDepthFunctionToLessOrEqual(); this._alphaState.reset(); this._unpackFlipYCached = null; } this._resetVertexBufferBinding(); this._cachedIndexBuffer = null; this._cachedEffectForVertexBuffers = null; this._unbindVertexArrayObject(); this.bindIndexBuffer(null); }; /** * Set the compressed texture format to use, based on the formats you have, and the formats * supported by the hardware / browser. * * Khronos Texture Container (.ktx) files are used to support this. This format has the * advantage of being specifically designed for OpenGL. Header elements directly correspond * to API arguments needed to compressed textures. This puts the burden on the container * generator to house the arcane code for determining these for current & future formats. * * for description see https://www.khronos.org/opengles/sdk/tools/KTX/ * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/ * * Note: The result of this call is not taken into account when a texture is base64. * * @param formatsAvailable defines the list of those format families you have created * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.) * * Current families are astc, dxt, pvrtc, etc2, & etc1. * @returns The extension selected. */ Engine.prototype.setTextureFormatToUse = function (formatsAvailable) { for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) { for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) { if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) { return this._textureFormatInUse = this._texturesSupported[i]; } } } // actively set format to nothing, to allow this to be called more than once // and possibly fail the 2nd time this._textureFormatInUse = null; return null; }; Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) { var gl = this._gl; var magFilter = gl.NEAREST; var minFilter = gl.NEAREST; switch (samplingMode) { case Engine.TEXTURE_BILINEAR_SAMPLINGMODE: magFilter = gl.LINEAR; if (generateMipMaps) { minFilter = gl.LINEAR_MIPMAP_NEAREST; } else { minFilter = gl.LINEAR; } break; case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE: magFilter = gl.LINEAR; if (generateMipMaps) { minFilter = gl.LINEAR_MIPMAP_LINEAR; } else { minFilter = gl.LINEAR; } break; case Engine.TEXTURE_NEAREST_SAMPLINGMODE: magFilter = gl.NEAREST; if (generateMipMaps) { minFilter = gl.NEAREST_MIPMAP_LINEAR; } else { minFilter = gl.NEAREST; } break; case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST: magFilter = gl.NEAREST; if (generateMipMaps) { minFilter = gl.NEAREST_MIPMAP_NEAREST; } else { minFilter = gl.NEAREST; } break; case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST: magFilter = gl.NEAREST; if (generateMipMaps) { minFilter = gl.LINEAR_MIPMAP_NEAREST; } else { minFilter = gl.LINEAR; } break; case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR: magFilter = gl.NEAREST; if (generateMipMaps) { minFilter = gl.LINEAR_MIPMAP_LINEAR; } else { minFilter = gl.LINEAR; } break; case Engine.TEXTURE_NEAREST_LINEAR: magFilter = gl.NEAREST; minFilter = gl.LINEAR; break; case Engine.TEXTURE_NEAREST_NEAREST: magFilter = gl.NEAREST; minFilter = gl.NEAREST; break; case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST: magFilter = gl.LINEAR; if (generateMipMaps) { minFilter = gl.NEAREST_MIPMAP_NEAREST; } else { minFilter = gl.NEAREST; } break; case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR: magFilter = gl.LINEAR; if (generateMipMaps) { minFilter = gl.NEAREST_MIPMAP_LINEAR; } else { minFilter = gl.NEAREST; } break; case Engine.TEXTURE_LINEAR_LINEAR: magFilter = gl.LINEAR; minFilter = gl.LINEAR; break; case Engine.TEXTURE_LINEAR_NEAREST: magFilter = gl.LINEAR; minFilter = gl.NEAREST; break; } return { min: minFilter, mag: magFilter }; }; Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) { if (onErrorCallBack === void 0) { onErrorCallBack = null; } var img; var onload = function () { loadedImages[index] = img; loadedImages._internalCount++; if (scene) { scene._removePendingData(img); } if (loadedImages._internalCount === 6) { onfinish(loadedImages); } }; var onerror = function (message, exception) { if (scene) { scene._removePendingData(img); } if (onErrorCallBack) { onErrorCallBack(message, exception); } }; img = _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].LoadImage(url, onload, onerror, scene ? scene.offlineProvider : null); if (scene) { scene._addPendingData(img); } }; Engine.prototype._cascadeLoadImgs = function (scene, onfinish, files, onError) { if (onError === void 0) { onError = null; } var loadedImages = []; loadedImages._internalCount = 0; for (var index = 0; index < 6; index++) { this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError); } }; /** @hidden */ Engine.prototype._createTexture = function () { var texture = this._gl.createTexture(); if (!texture) { throw new Error("Unable to create texture"); } return texture; }; /** * Usually called from Texture.ts. * Passed information to create a WebGLTexture * @param urlArg 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 excludeLoaders array of texture loaders that should be excluded when picking a loader for the texture (default: empty array) * @returns a InternalTexture for assignment back into BABYLON.Texture */ Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension, excludeLoaders) { var _this = this; if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; } if (onLoad === void 0) { onLoad = null; } if (onError === void 0) { onError = null; } if (buffer === void 0) { buffer = null; } if (fallback === void 0) { fallback = null; } if (format === void 0) { format = null; } if (forcedExtension === void 0) { forcedExtension = null; } if (excludeLoaders === void 0) { excludeLoaders = []; } var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback var fromData = url.substr(0, 5) === "data:"; var fromBlob = url.substr(0, 5) === "blob:"; var isBase64 = fromData && url.indexOf(";base64,") !== -1; var texture = fallback ? fallback : new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"].DATASOURCE_URL); // establish the file extension, if possible var lastDot = url.lastIndexOf('.'); var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : ""); var loader = null; for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) { var availableLoader = _a[_i]; if (excludeLoaders.indexOf(availableLoader) === -1 && availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) { loader = availableLoader; break; } } if (loader) { url = loader.transformUrl(url, this._textureFormatInUse); } if (scene) { scene._addPendingData(texture); } texture.url = url; texture.generateMipMaps = !noMipmap; texture.samplingMode = samplingMode; texture.invertY = invertY; if (!this._doNotHandleContextLost) { // Keep a link to the buffer only if we plan to handle context lost texture._buffer = buffer; } var onLoadObserver = null; if (onLoad && !fallback) { onLoadObserver = texture.onLoadedObservable.add(onLoad); } if (!fallback) { this._internalTexturesCache.push(texture); } var onInternalError = function (message, exception) { if (scene) { scene._removePendingData(texture); } var customFallback = false; if (loader) { var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse); if (fallbackUrl) { // Add Back customFallback = true; excludeLoaders.push(loader); _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].Warn(loader.constructor.name + " failed when trying to load " + texture.url + ", falling back to the next supported loader"); _this.createTexture(urlArg, noMipmap, texture.invertY, scene, samplingMode, null, null, buffer, texture, undefined, undefined, excludeLoaders); } } if (!customFallback) { if (onLoadObserver) { texture.onLoadedObservable.remove(onLoadObserver); } if (_Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].UseFallbackTexture) { _this.createTexture(_Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].fallbackTexture, noMipmap, texture.invertY, scene, samplingMode, null, null, buffer, texture); } } if (onError) { onError(message || "Unknown error", exception); } }; // processing for non-image formats if (loader) { var callback = function (data) { loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done, loadFailed) { if (loadFailed) { onInternalError("TextureLoader failed to load data"); } else { _this._prepareWebGLTexture(texture, scene, width, height, texture.invertY, !loadMipmap, isCompressed, function () { done(); return false; }, samplingMode); } }); }; if (!buffer) { this._loadFile(url, callback, undefined, scene ? scene.offlineProvider : undefined, true, function (request, exception) { onInternalError("Unable to load " + (request ? request.responseURL : url, exception)); }); } else { callback(buffer); } } else { var onload = function (img) { if (fromBlob && !_this._doNotHandleContextLost) { // We need to store the image if we need to rebuild the texture // in case of a webgl context lost texture._buffer = img; } _this._prepareWebGLTexture(texture, scene, img.width, img.height, texture.invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) { var gl = _this._gl; var isPot = (img.width === potWidth && img.height === potHeight); var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA); if (isPot) { gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img); return false; } var maxTextureSize = _this._caps.maxTextureSize; if (img.width > maxTextureSize || img.height > maxTextureSize || Engine._RescalePostProcessFactory === null) { _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, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas); texture.width = potWidth; texture.height = potHeight; return false; } else { // Using shaders when possible to rescale because canvas.drawImage is lossy var source_1 = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"](_this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"].DATASOURCE_TEMP); _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true); gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); _this._rescaleTexture(source_1, texture, scene, internalFormat, function () { _this._releaseTexture(source_1); _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true); continuationCallback(); }); } return true; }, samplingMode); }; if (!fromData || isBase64) { if (buffer instanceof HTMLImageElement) { onload(buffer); } else { _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].LoadImage(url, onload, onInternalError, scene ? scene.offlineProvider : null); } } else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) { _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].LoadImage(buffer, onload, onInternalError, scene ? scene.offlineProvider : null); } else { onload(buffer); } } return texture; }; Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) { var _this = this; var rtt = this.createRenderTargetTexture({ width: destination.width, height: destination.height, }, { generateMipMaps: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE, generateDepthBuffer: false, generateStencilBuffer: false }); if (!this._rescalePostProcess && Engine._RescalePostProcessFactory) { this._rescalePostProcess = Engine._RescalePostProcessFactory(this); } this._rescalePostProcess.getEffect().executeWhenCompiled(function () { _this._rescalePostProcess.onApply = function (effect) { effect._bindTexture("textureSampler", source); }; var 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); _this._releaseTexture(rtt); if (onComplete) { onComplete(); } }); }; /** * Update a raw texture * @param texture defines the texture to update * @param data defines the data to store in the texture * @param format defines the format of the data * @param invertY defines if data must be stored with Y axis inverted * @param compression defines the compression used (null by default) * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default) */ Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) { if (compression === void 0) { compression = null; } if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; } if (!texture) { return; } // babylon's internalSizedFomat but gl's texImage2D internalFormat var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format); // babylon's internalFormat but gl's texImage2D format var internalFormat = this._getInternalFormat(format); var textureType = this._getWebGLTextureType(type); this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true); this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false)); if (!this._doNotHandleContextLost) { texture._bufferView = data; texture.format = format; texture.type = type; texture.invertY = invertY; texture._compression = compression; } if (texture.width % 4 !== 0) { this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1); } if (compression && data) { this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data); } else { this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data); } if (texture.generateMipMaps) { this._gl.generateMipmap(this._gl.TEXTURE_2D); } this._bindTextureDirectly(this._gl.TEXTURE_2D, null); // this.resetTextureCache(); texture.isReady = true; }; /** * 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_INT by default) * @returns the raw texture inside an InternalTexture */ Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) { if (compression === void 0) { compression = null; } if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; } var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"].DATASOURCE_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; if (!this._doNotHandleContextLost) { texture._bufferView = data; } this.updateRawTexture(texture, data, format, invertY, compression, type); this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true); // Filters var 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; }; /** @hidden */ Engine.prototype._unpackFlipY = function (value) { if (this._unpackFlipYCached !== value) { this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0); if (this.enableUnpackFlipYCached) { this._unpackFlipYCached = value; } } }; /** @hidden */ Engine.prototype._getUnpackAlignement = function () { return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT); }; /** * Creates a dynamic texture * @param width defines the width of the texture * @param height defines the height of the texture * @param generateMipMaps defines if the engine should generate the mip levels * @param samplingMode defines the required sampling mode (Texture.NEAREST_SAMPLINGMODE by default) * @returns the dynamic texture inside an InternalTexture */ Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) { var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"].DATASOURCE_DYNAMIC); texture.baseWidth = width; texture.baseHeight = height; if (generateMipMaps) { width = this.needPOTTextures ? _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].GetExponentOfTwo(width, this._caps.maxTextureSize) : width; height = this.needPOTTextures ? _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].GetExponentOfTwo(height, this._caps.maxTextureSize) : height; } // this.resetTextureCache(); texture.width = width; texture.height = height; texture.isReady = false; texture.generateMipMaps = generateMipMaps; texture.samplingMode = samplingMode; this.updateTextureSamplingMode(samplingMode, texture); this._internalTexturesCache.push(texture); return texture; }; /** * Update the sampling mode of a given texture * @param samplingMode defines the required sampling mode * @param texture defines the texture to update */ Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) { var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps); if (texture.isCube) { this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture); this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min); this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null); } else if (texture.is3D) { this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture); this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min); this._bindTextureDirectly(this._gl.TEXTURE_3D, null); } else { this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture); this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min); this._bindTextureDirectly(this._gl.TEXTURE_2D, null); } texture.samplingMode = samplingMode; }; /** * Update the content of a dynamic texture * @param texture defines the texture to update * @param canvas defines the canvas containing the source * @param invertY defines if data must be stored with Y axis inverted * @param premulAlpha defines if alpha is stored as premultiplied * @param format defines the format of the data * @param forceBindTexture if the texture should be forced to be bound eg. after a graphics context loss (Default: false) */ Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format, forceBindTexture) { if (premulAlpha === void 0) { premulAlpha = false; } if (forceBindTexture === void 0) { forceBindTexture = false; } if (!texture) { return; } this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true, forceBindTexture); this._unpackFlipY(invertY); if (premulAlpha) { this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1); } var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA; this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas); if (texture.generateMipMaps) { this._gl.generateMipmap(this._gl.TEXTURE_2D); } this._bindTextureDirectly(this._gl.TEXTURE_2D, null); if (premulAlpha) { this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0); } texture.isReady = true; }; /** * Update a video texture * @param texture defines the texture to update * @param video defines the video element to use * @param invertY defines if data must be stored with Y axis inverted */ Engine.prototype.updateVideoTexture = function (texture, video, invertY) { if (!texture || texture._isDisabled) { return; } var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true); this._unpackFlipY(!invertY); // Video are upside down by default try { // Testing video texture support if (this._videoTextureSupported === undefined) { this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video); if (this._gl.getError() !== 0) { this._videoTextureSupported = false; } else { this._videoTextureSupported = true; } } // Copy video through the current working canvas if video texture is not supported if (!this._videoTextureSupported) { if (!texture._workingCanvas) { texture._workingCanvas = document.createElement("canvas"); var context = texture._workingCanvas.getContext("2d"); if (!context) { throw new Error("Unable to get 2d context"); } texture._workingContext = context; texture._workingCanvas.width = texture.width; texture._workingCanvas.height = texture.height; } texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height); this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas); } else { this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video); } if (texture.generateMipMaps) { this._gl.generateMipmap(this._gl.TEXTURE_2D); } if (!wasPreviouslyBound) { this._bindTextureDirectly(this._gl.TEXTURE_2D, null); } // this.resetTextureCache(); texture.isReady = true; } catch (ex) { // Something unexpected // Let's disable the texture texture._isDisabled = 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 */ Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) { if (this.webGLVersion === 1) { _Misc_logger__WEBPACK_IMPORTED_MODULE_14__["Logger"].Error("WebGL 1 does not support texture comparison."); return; } var 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, Engine.LEQUAL); 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, Engine.LEQUAL); 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; }; Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) { var width = size.width || size; var height = size.height || size; internalTexture.baseWidth = width; internalTexture.baseHeight = height; internalTexture.width = width; internalTexture.height = height; internalTexture.isReady = true; internalTexture.samples = 1; internalTexture.generateMipMaps = false; internalTexture._generateDepthBuffer = true; internalTexture._generateStencilBuffer = generateStencil; internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE; internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT; internalTexture._comparisonFunction = comparisonFunction; var gl = this._gl; var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D; var 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 (comparisonFunction === 0) { gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL); 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); } }; /** * Creates a depth stencil texture. * This is only available in WebGL 2 or with the depth texture extension available. * @param size The size of face edge in the texture. * @param options The options defining the texture. * @returns The texture */ Engine.prototype.createDepthStencilTexture = function (size, options) { if (options.isCube) { var width = size.width || size; return this._createDepthStencilCubeTexture(width, options); } else { return this._createDepthStencilTexture(size, options); } }; /** * Creates a depth stencil texture. * This is only available in WebGL 2 or with the depth texture extension available. * @param size The size of face edge in the texture. * @param options The options defining the texture. * @returns The texture */ Engine.prototype._createDepthStencilTexture = function (size, options) { var internalTexture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"].DATASOURCE_DEPTHTEXTURE); if (!this._caps.depthTextureExtension) { _Misc_logger__WEBPACK_IMPORTED_MODULE_14__["Logger"].Error("Depth texture is not supported by your browser or hardware."); return internalTexture; } var internalOptions = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options); var gl = this._gl; this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true); this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction); if (this.webGLVersion > 1) { if (internalOptions.generateStencil) { gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null); } else { gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null); } } else { if (internalOptions.generateStencil) { gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null); } else { gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null); } } this._bindTextureDirectly(gl.TEXTURE_2D, null); return internalTexture; }; /** * Creates a depth stencil cube texture. * This is only available in WebGL 2. * @param size The size of face edge in the cube texture. * @param options The options defining the cube texture. * @returns The cube texture */ Engine.prototype._createDepthStencilCubeTexture = function (size, options) { var internalTexture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"].DATASOURCE_UNKNOWN); internalTexture.isCube = true; if (this.webGLVersion === 1) { _Misc_logger__WEBPACK_IMPORTED_MODULE_14__["Logger"].Error("Depth cube texture is not supported by WebGL 1."); return internalTexture; } var internalOptions = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options); var gl = this._gl; this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true); this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction); // Create the depth/stencil buffer for (var 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); return internalTexture; }; /** * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture. * @param renderTarget The render target to set the frame buffer for */ Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) { // Create the framebuffer var internalTexture = renderTarget.getInternalTexture(); if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) { return; } var gl = this._gl; var depthStencilTexture = renderTarget.depthStencilTexture; this.bindUnboundFramebuffer(internalTexture._framebuffer); if (depthStencilTexture.isCube) { if (depthStencilTexture._generateStencilBuffer) { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0); } else { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0); } } else { if (depthStencilTexture._generateStencilBuffer) { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0); } else { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0); } } this.bindUnboundFramebuffer(null); }; /** * Creates a new render target texture * @param size defines the size of the texture * @param options defines the options used to create the texture * @returns a new render target texture stored in an InternalTexture */ Engine.prototype.createRenderTargetTexture = function (size, options) { var fullOptions = new _Materials_Textures_renderTargetCreationOptions__WEBPACK_IMPORTED_MODULE_16__["RenderTargetCreationOptions"](); if (options !== undefined && typeof options === "object") { fullOptions.generateMipMaps = options.generateMipMaps; fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer; fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer; fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type; fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode; fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format; } else { fullOptions.generateMipMaps = options; fullOptions.generateDepthBuffer = true; fullOptions.generateStencilBuffer = false; fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT; fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; fullOptions.format = Engine.TEXTUREFORMAT_RGBA; } if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) { // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE; } else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) { // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE; } var gl = this._gl; var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"].DATASOURCE_RENDERTARGET); this._bindTextureDirectly(gl.TEXTURE_2D, texture, true); var width = size.width || size; var height = size.height || size; var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false); if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) { fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT; _Misc_logger__WEBPACK_IMPORTED_MODULE_14__["Logger"].Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type"); } gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null); // Create the framebuffer var currentFrameBuffer = this._currentFramebuffer; var framebuffer = gl.createFramebuffer(); this.bindUnboundFramebuffer(framebuffer); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0); texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height); if (fullOptions.generateMipMaps) { this._gl.generateMipmap(this._gl.TEXTURE_2D); } // Unbind this._bindTextureDirectly(gl.TEXTURE_2D, null); gl.bindRenderbuffer(gl.RENDERBUFFER, null); this.bindUnboundFramebuffer(currentFrameBuffer); texture._framebuffer = framebuffer; texture.baseWidth = width; texture.baseHeight = height; texture.width = width; texture.height = height; texture.isReady = true; texture.samples = 1; texture.generateMipMaps = fullOptions.generateMipMaps ? true : false; texture.samplingMode = fullOptions.samplingMode; texture.type = fullOptions.type; texture.format = fullOptions.format; texture._generateDepthBuffer = fullOptions.generateDepthBuffer; texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false; // this.resetTextureCache(); this._internalTexturesCache.push(texture); return texture; }; /** * Create a multi render target texture * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target * @param size defines the size of the texture * @param options defines the creation options * @returns the cube texture as an InternalTexture */ Engine.prototype.createMultipleRenderTarget = function (size, options) { var generateMipMaps = false; var generateDepthBuffer = true; var generateStencilBuffer = false; var generateDepthTexture = false; var textureCount = 1; var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT; var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; var types = new Array(); var samplingModes = new Array(); if (options !== undefined) { generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps; generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer; generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer; generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture; textureCount = options.textureCount || 1; if (options.types) { types = options.types; } if (options.samplingModes) { samplingModes = options.samplingModes; } } var gl = this._gl; // Create the framebuffer var framebuffer = gl.createFramebuffer(); this.bindUnboundFramebuffer(framebuffer); var width = size.width || size; var height = size.height || size; var textures = []; var attachments = []; var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height); for (var i = 0; i < textureCount; i++) { var samplingMode = samplingModes[i] || defaultSamplingMode; var type = types[i] || defaultType; if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) { // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE; } else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) { // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE; } var filters = this._getSamplingParameters(samplingMode, generateMipMaps); if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) { type = Engine.TEXTURETYPE_UNSIGNED_INT; _Misc_logger__WEBPACK_IMPORTED_MODULE_14__["Logger"].Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type"); } var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"].DATASOURCE_MULTIRENDERTARGET); var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"]; textures.push(texture); attachments.push(attachment); gl.activeTexture(gl["TEXTURE" + i]); gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null); gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0); if (generateMipMaps) { this._gl.generateMipmap(this._gl.TEXTURE_2D); } // Unbind this._bindTextureDirectly(gl.TEXTURE_2D, null); texture._framebuffer = framebuffer; texture._depthStencilBuffer = depthStencilBuffer; texture.baseWidth = width; texture.baseHeight = height; texture.width = width; texture.height = height; texture.isReady = true; texture.samples = 1; texture.generateMipMaps = generateMipMaps; texture.samplingMode = samplingMode; texture.type = type; texture._generateDepthBuffer = generateDepthBuffer; texture._generateStencilBuffer = generateStencilBuffer; texture._attachments = attachments; this._internalTexturesCache.push(texture); } if (generateDepthTexture && this._caps.depthTextureExtension) { // Depth texture var depthTexture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"].DATASOURCE_MULTIRENDERTARGET); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texImage2D(gl.TEXTURE_2D, 0, this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0); depthTexture._framebuffer = framebuffer; depthTexture.baseWidth = width; depthTexture.baseHeight = height; depthTexture.width = width; depthTexture.height = height; depthTexture.isReady = true; depthTexture.samples = 1; depthTexture.generateMipMaps = generateMipMaps; depthTexture.samplingMode = gl.NEAREST; depthTexture._generateDepthBuffer = generateDepthBuffer; depthTexture._generateStencilBuffer = generateStencilBuffer; textures.push(depthTexture); this._internalTexturesCache.push(depthTexture); } gl.drawBuffers(attachments); gl.bindRenderbuffer(gl.RENDERBUFFER, null); this.bindUnboundFramebuffer(null); this.resetTextureCache(); return textures; }; Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) { if (samples === void 0) { samples = 1; } var depthStencilBuffer = null; var gl = this._gl; // Create the depth/stencil buffer if (generateStencilBuffer) { depthStencilBuffer = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer); if (samples > 1) { gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height); } else { gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height); } gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer); } else if (generateDepthBuffer) { depthStencilBuffer = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer); if (samples > 1) { gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height); } else { gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height); } gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer); } return depthStencilBuffer; }; /** * Updates the sample count of a render target texture * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets * @param texture defines the texture to update * @param samples defines the sample count to set * @returns the effective sample count (could be 0 if multisample render targets are not supported) */ Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) { if (this.webGLVersion < 2 || !texture) { return 1; } if (texture.samples === samples) { return samples; } var gl = this._gl; samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES)); // Dispose previous render buffers if (texture._depthStencilBuffer) { gl.deleteRenderbuffer(texture._depthStencilBuffer); texture._depthStencilBuffer = null; } if (texture._MSAAFramebuffer) { gl.deleteFramebuffer(texture._MSAAFramebuffer); texture._MSAAFramebuffer = null; } if (texture._MSAARenderBuffer) { gl.deleteRenderbuffer(texture._MSAARenderBuffer); texture._MSAARenderBuffer = null; } if (samples > 1) { var framebuffer = gl.createFramebuffer(); if (!framebuffer) { throw new Error("Unable to create multi sampled framebuffer"); } texture._MSAAFramebuffer = framebuffer; this.bindUnboundFramebuffer(texture._MSAAFramebuffer); var colorRenderbuffer = gl.createRenderbuffer(); if (!colorRenderbuffer) { throw new Error("Unable to create multi sampled framebuffer"); } gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer); gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer); texture._MSAARenderBuffer = colorRenderbuffer; } else { this.bindUnboundFramebuffer(texture._framebuffer); } texture.samples = samples; texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples); gl.bindRenderbuffer(gl.RENDERBUFFER, null); this.bindUnboundFramebuffer(null); return samples; }; /** * Update the sample count for a given multiple render target texture * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets * @param textures defines the textures to update * @param samples defines the sample count to set * @returns the effective sample count (could be 0 if multisample render targets are not supported) */ Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) { if (this.webGLVersion < 2 || !textures || textures.length == 0) { return 1; } if (textures[0].samples === samples) { return samples; } var gl = this._gl; samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES)); // Dispose previous render buffers if (textures[0]._depthStencilBuffer) { gl.deleteRenderbuffer(textures[0]._depthStencilBuffer); textures[0]._depthStencilBuffer = null; } if (textures[0]._MSAAFramebuffer) { gl.deleteFramebuffer(textures[0]._MSAAFramebuffer); textures[0]._MSAAFramebuffer = null; } for (var i = 0; i < textures.length; i++) { if (textures[i]._MSAARenderBuffer) { gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer); textures[i]._MSAARenderBuffer = null; } } if (samples > 1) { var framebuffer = gl.createFramebuffer(); if (!framebuffer) { throw new Error("Unable to create multi sampled framebuffer"); } this.bindUnboundFramebuffer(framebuffer); var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples); var attachments = []; for (var i = 0; i < textures.length; i++) { var texture = textures[i]; var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"]; var colorRenderbuffer = gl.createRenderbuffer(); if (!colorRenderbuffer) { throw new Error("Unable to create multi sampled framebuffer"); } gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer); gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer); texture._MSAAFramebuffer = framebuffer; texture._MSAARenderBuffer = colorRenderbuffer; texture.samples = samples; texture._depthStencilBuffer = depthStencilBuffer; gl.bindRenderbuffer(gl.RENDERBUFFER, null); attachments.push(attachment); } gl.drawBuffers(attachments); } else { this.bindUnboundFramebuffer(textures[0]._framebuffer); } this.bindUnboundFramebuffer(null); return samples; }; /** @hidden */ Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) { if (faceIndex === void 0) { faceIndex = 0; } if (lod === void 0) { lod = 0; } var gl = this._gl; var target = gl.TEXTURE_2D; if (texture.isCube) { target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex; } this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data); }; /** @hidden */ Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) { if (faceIndex === void 0) { faceIndex = 0; } if (lod === void 0) { lod = 0; } var gl = this._gl; var textureType = this._getWebGLTextureType(texture.type); var format = this._getInternalFormat(texture.format); var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format); this._unpackFlipY(texture.invertY); var target = gl.TEXTURE_2D; if (texture.isCube) { target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex; } var lodMaxWidth = Math.round(_Maths_math_scalar__WEBPACK_IMPORTED_MODULE_7__["Scalar"].Log2(texture.width)); var lodMaxHeight = Math.round(_Maths_math_scalar__WEBPACK_IMPORTED_MODULE_7__["Scalar"].Log2(texture.height)); var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0)); var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0)); gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData); }; /** @hidden */ Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) { if (faceIndex === void 0) { faceIndex = 0; } if (lod === void 0) { lod = 0; } var gl = this._gl; var 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); }; /** @hidden */ Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) { if (faceIndex === void 0) { faceIndex = 0; } if (lod === void 0) { lod = 0; } var gl = this._gl; var textureType = this._getWebGLTextureType(texture.type); var format = this._getInternalFormat(texture.format); var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format); var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D; this._bindTextureDirectly(bindTarget, texture, true); this._unpackFlipY(texture.invertY); var 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); }; /** * Creates a new render target cube texture * @param size defines the size of the texture * @param options defines the options used to create the texture * @returns a new render target cube texture stored in an InternalTexture */ Engine.prototype.createRenderTargetCubeTexture = function (size, options) { var fullOptions = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options); fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer; if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) { // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE; } else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) { // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE; } var gl = this._gl; var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"].DATASOURCE_RENDERTARGET); this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps); if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) { fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT; _Misc_logger__WEBPACK_IMPORTED_MODULE_14__["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 (var face = 0; face < 6; face++) { gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null); } // Create the framebuffer var framebuffer = gl.createFramebuffer(); this.bindUnboundFramebuffer(framebuffer); texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size); // MipMaps if (fullOptions.generateMipMaps) { gl.generateMipmap(gl.TEXTURE_CUBE_MAP); } // Unbind this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); gl.bindRenderbuffer(gl.RENDERBUFFER, null); this.bindUnboundFramebuffer(null); texture._framebuffer = framebuffer; 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; texture._generateDepthBuffer = fullOptions.generateDepthBuffer; texture._generateStencilBuffer = fullOptions.generateStencilBuffer; this._internalTexturesCache.push(texture); return texture; }; /** * Creates a cube texture * @param rootUrl defines the url where the files to load is located * @param scene defines the current scene * @param files defines the list of files to load (1 per face) * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default) * @param onLoad defines an optional callback raised when the texture is loaded * @param onError defines an optional callback raised if there is an issue to load the texture * @param format defines the format of the data * @param forcedExtension defines the extension to use to pick the right loader * @param createPolynomials if a polynomial sphere should be created for the cube texture * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness * @param fallback defines texture to use while falling back when (compressed) texture file not found. * @param excludeLoaders array of texture loaders that should be excluded when picking a loader for the texture (defualt: empty array) * @returns the cube texture as an InternalTexture */ Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback, excludeLoaders) { var _this = this; if (onLoad === void 0) { onLoad = null; } if (onError === void 0) { onError = null; } if (forcedExtension === void 0) { forcedExtension = null; } if (createPolynomials === void 0) { createPolynomials = false; } if (lodScale === void 0) { lodScale = 0; } if (lodOffset === void 0) { lodOffset = 0; } if (fallback === void 0) { fallback = null; } if (excludeLoaders === void 0) { excludeLoaders = []; } var gl = this._gl; var texture = fallback ? fallback : new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"].DATASOURCE_CUBE); texture.isCube = true; texture.url = rootUrl; texture.generateMipMaps = !noMipmap; texture._lodGenerationScale = lodScale; texture._lodGenerationOffset = lodOffset; if (!this._doNotHandleContextLost) { texture._extension = forcedExtension; texture._files = files; } var lastDot = rootUrl.lastIndexOf('.'); var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : ""); var loader = null; for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) { var availableLoader = _a[_i]; if (excludeLoaders.indexOf(availableLoader) === -1 && availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) { loader = availableLoader; break; } } var onInternalError = function (request, exception) { if (loader) { var fallbackUrl = loader.getFallbackTextureUrl(texture.url, _this._textureFormatInUse); _Misc_logger__WEBPACK_IMPORTED_MODULE_14__["Logger"].Warn(loader.constructor.name + " failed when trying to load " + texture.url + ", falling back to the next supported loader"); if (fallbackUrl) { excludeLoaders.push(loader); _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture, excludeLoaders); return; } } if (onError && request) { onError(request.status + " " + request.statusText, exception); } }; if (loader) { rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse); var onloaddata = function (data) { _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); loader.loadCubeData(data, texture, createPolynomials, onLoad, onError); }; if (files && files.length === 6) { if (loader.supportCascades) { this._cascadeLoadFiles(scene, onloaddata, files, onError); } else { if (onError) { onError("Textures type does not support cascades."); } else { _Misc_logger__WEBPACK_IMPORTED_MODULE_14__["Logger"].Warn("Texture loader does not support cascades."); } } } else { this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError); } } else { if (!files) { throw new Error("Cannot load cubemap because files were not defined"); } this._cascadeLoadImgs(scene, function (imgs) { var width = _this.needPOTTextures ? _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width; var height = width; _this._prepareWorkingCanvas(); if (!_this._workingCanvas || !_this._workingContext) { return; } _this._workingCanvas.width = width; _this._workingCanvas.height = height; var 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); var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA; for (var index = 0; index < faces.length; index++) { if (imgs[index].width !== width || imgs[index].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, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas); } else { gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, imgs[index]); } } if (!noMipmap) { gl.generateMipmap(gl.TEXTURE_CUBE_MAP); } _this._setCubeMapTextureParams(!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(); } }, files, onError); } this._internalTexturesCache.push(texture); return texture; }; /** * @hidden */ Engine.prototype._setCubeMapTextureParams = function (loadMipmap) { var 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); this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); // this.resetTextureCache(); }; /** * Update a raw cube texture * @param texture defines the texture to udpdate * @param data defines the data to store * @param format defines the data format * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default) * @param invertY defines if data must be stored with Y axis inverted * @param compression defines the compression used (null by default) * @param level defines which level of the texture to update */ Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) { if (compression === void 0) { compression = null; } if (level === void 0) { level = 0; } texture._bufferViewArray = data; texture.format = format; texture.type = type; texture.invertY = invertY; texture._compression = compression; var gl = this._gl; var textureType = this._getWebGLTextureType(type); var internalFormat = this._getInternalFormat(format); var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type); var needConversion = false; if (internalFormat === gl.RGB) { internalFormat = gl.RGBA; needConversion = true; } this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false)); if (texture.width % 4 !== 0) { gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1); } // Data are known to be in +X +Y +Z -X -Y -Z for (var faceIndex = 0; faceIndex < 6; faceIndex++) { var 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 = this._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); } } var isPot = !this.needPOTTextures || (_Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].IsExponentOfTwo(texture.width) && _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].IsExponentOfTwo(texture.height)); if (isPot && texture.generateMipMaps && level === 0) { this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP); } this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null); // this.resetTextureCache(); texture.isReady = true; }; /** * 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_INT) * @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 */ Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) { if (compression === void 0) { compression = null; } var gl = this._gl; var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"].DATASOURCE_CUBERAW); texture.isCube = true; texture.format = format; texture.type = type; if (!this._doNotHandleContextLost) { texture._bufferViewArray = data; } var textureType = this._getWebGLTextureType(type); var internalFormat = this._getInternalFormat(format); if (internalFormat === gl.RGB) { internalFormat = gl.RGBA; } // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) { generateMipMaps = false; samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE; _Misc_logger__WEBPACK_IMPORTED_MODULE_14__["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 = Engine.TEXTURE_NEAREST_SAMPLINGMODE; _Misc_logger__WEBPACK_IMPORTED_MODULE_14__["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; _Misc_logger__WEBPACK_IMPORTED_MODULE_14__["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; _Misc_logger__WEBPACK_IMPORTED_MODULE_14__["Logger"].Warn("Render to half float textures is not supported. Mipmap generation forced to false."); } var width = size; var height = width; texture.width = width; texture.height = height; // Double check on POT to generate Mips. var isPot = !this.needPOTTextures || (_Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].IsExponentOfTwo(texture.width) && _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].IsExponentOfTwo(texture.height)); if (!isPot) { generateMipMaps = false; } // Upload data if needed. The texture won't be ready until then. if (data) { this.updateRawCubeTexture(texture, data, format, type, invertY, compression); } this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true); // Filters if (data && generateMipMaps) { this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP); } var 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; return texture; }; /** * Creates a new raw cube texture from a specified url * @param url defines the url where the data is located * @param scene defines the current scene * @param size defines the size of the textures * @param format defines the format of the data * @param type defines the type fo the data (like Engine.TEXTURETYPE_UNSIGNED_INT) * @param noMipmap defines if the engine should avoid generating the mip levels * @param callback defines a callback used to extract texture data from loaded data * @param mipmapGenerator defines to provide an optional tool to generate mip levels * @param onLoad defines a callback called when texture is loaded * @param onError defines a callback called if there is an error * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE) * @param invertY defines if data must be stored with Y axis inverted * @returns the cube texture as an InternalTexture */ Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) { var _this = this; if (onLoad === void 0) { onLoad = null; } if (onError === void 0) { onError = null; } if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; } if (invertY === void 0) { invertY = false; } var gl = this._gl; var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode); scene._addPendingData(texture); texture.url = url; this._internalTexturesCache.push(texture); var onerror = function (request, exception) { scene._removePendingData(texture); if (onError && request) { onError(request.status + " " + request.statusText, exception); } }; var internalCallback = function (data) { var width = texture.width; var faceDataArrays = callback(data); if (!faceDataArrays) { return; } if (mipmapGenerator) { var textureType = _this._getWebGLTextureType(type); var internalFormat = _this._getInternalFormat(format); var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type); var needConversion = false; if (internalFormat === gl.RGB) { internalFormat = gl.RGBA; needConversion = true; } _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); _this._unpackFlipY(false); var mipData = mipmapGenerator(faceDataArrays); for (var level = 0; level < mipData.length; level++) { var mipSize = width >> level; for (var faceIndex = 0; faceIndex < 6; faceIndex++) { var mipFaceData = mipData[level][faceIndex]; if (needConversion) { mipFaceData = _this._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; // this.resetTextureCache(); scene._removePendingData(texture); if (onLoad) { onLoad(); } }; this._loadFile(url, function (data) { internalCallback(data); }, undefined, scene.offlineProvider, true, onerror); return texture; }; /** * Update a raw 3D texture * @param texture defines the texture to update * @param data defines the data to store * @param format defines the data format * @param invertY defines if data must be stored with Y axis inverted * @param compression defines the used compression (can be null) * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...) */ Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) { if (compression === void 0) { compression = null; } if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; } var internalType = this._getWebGLTextureType(textureType); var internalFormat = this._getInternalFormat(format); var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format); this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true); this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false)); if (!this._doNotHandleContextLost) { texture._bufferView = data; texture.format = format; texture.invertY = invertY; texture._compression = compression; } if (texture.width % 4 !== 0) { this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1); } if (compression && data) { this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data); } else { this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data); } if (texture.generateMipMaps) { this._gl.generateMipmap(this._gl.TEXTURE_3D); } this._bindTextureDirectly(this._gl.TEXTURE_3D, null); // this.resetTextureCache(); texture.isReady = true; }; /** * 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) * @returns a new raw 3D texture (stored in an InternalTexture) */ Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) { if (compression === void 0) { compression = null; } if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; } var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_10__["InternalTexture"].DATASOURCE_RAW3D); 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; texture.is3D = true; if (!this._doNotHandleContextLost) { texture._bufferView = data; } this.updateRawTexture3D(texture, data, format, invertY, compression, textureType); this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true); // Filters var filters = this._getSamplingParameters(samplingMode, generateMipMaps); this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag); this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min); if (generateMipMaps) { this._gl.generateMipmap(this._gl.TEXTURE_3D); } this._bindTextureDirectly(this._gl.TEXTURE_3D, null); this._internalTexturesCache.push(texture); return texture; }; Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) { var gl = this._gl; if (!gl) { return; } var filters = this._getSamplingParameters(samplingMode, !noMipmap); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min); if (!noMipmap && !isCompressed) { gl.generateMipmap(gl.TEXTURE_2D); } this._bindTextureDirectly(gl.TEXTURE_2D, null); // this.resetTextureCache(); if (scene) { scene._removePendingData(texture); } texture.onLoadedObservable.notifyObservers(texture); texture.onLoadedObservable.clear(); }; Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) { var _this = this; if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; } var maxTextureSize = this.getCaps().maxTextureSize; var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].GetExponentOfTwo(width, maxTextureSize) : width); var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].GetExponentOfTwo(height, maxTextureSize) : height); var gl = this._gl; if (!gl) { return; } if (!texture._webGLTexture) { // this.resetTextureCache(); if (scene) { scene._removePendingData(texture); } return; } this._bindTextureDirectly(gl.TEXTURE_2D, texture, true); this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false)); texture.baseWidth = width; texture.baseHeight = height; texture.width = potWidth; texture.height = potHeight; texture.isReady = true; if (processFunction(potWidth, potHeight, function () { _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode); })) { // Returning as texture needs extra async steps return; } this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode); }; Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) { // Create new RGBA data container. var rgbaData; if (textureType === Engine.TEXTURETYPE_FLOAT) { rgbaData = new Float32Array(width * height * 4); } else { rgbaData = new Uint32Array(width * height * 4); } // Convert each pixel. for (var x = 0; x < width; x++) { for (var y = 0; y < height; y++) { var index = (y * width + x) * 3; var newIndex = (y * width + x) * 4; // Map Old Value to new value. rgbaData[newIndex + 0] = rgbData[index + 0]; rgbaData[newIndex + 1] = rgbData[index + 1]; rgbaData[newIndex + 2] = rgbData[index + 2]; // Add fully opaque alpha channel. rgbaData[newIndex + 3] = 1; } } return rgbaData; }; /** @hidden */ Engine.prototype._releaseFramebufferObjects = function (texture) { var gl = this._gl; if (texture._framebuffer) { gl.deleteFramebuffer(texture._framebuffer); texture._framebuffer = null; } if (texture._depthStencilBuffer) { gl.deleteRenderbuffer(texture._depthStencilBuffer); texture._depthStencilBuffer = null; } if (texture._MSAAFramebuffer) { gl.deleteFramebuffer(texture._MSAAFramebuffer); texture._MSAAFramebuffer = null; } if (texture._MSAARenderBuffer) { gl.deleteRenderbuffer(texture._MSAARenderBuffer); texture._MSAARenderBuffer = null; } }; /** @hidden */ Engine.prototype._releaseTexture = function (texture) { var gl = this._gl; this._releaseFramebufferObjects(texture); gl.deleteTexture(texture._webGLTexture); // Unbind channels this.unbindAllTextures(); var index = this._internalTexturesCache.indexOf(texture); if (index !== -1) { this._internalTexturesCache.splice(index, 1); } // Integrated fixed lod samplers. if (texture._lodTextureHigh) { texture._lodTextureHigh.dispose(); } if (texture._lodTextureMid) { texture._lodTextureMid.dispose(); } if (texture._lodTextureLow) { texture._lodTextureLow.dispose(); } // Set output texture of post process to null if the texture has been released/disposed this.scenes.forEach(function (scene) { scene.postProcesses.forEach(function (postProcess) { if (postProcess._outputTexture == texture) { postProcess._outputTexture = null; } }); scene.cameras.forEach(function (camera) { camera._postProcesses.forEach(function (postProcess) { if (postProcess) { if (postProcess._outputTexture == texture) { postProcess._outputTexture = null; } } }); }); }); }; Engine.prototype.setProgram = function (program) { if (this._currentProgram !== program) { this._gl.useProgram(program); this._currentProgram = program; } }; /** * Binds an effect to the webGL context * @param effect defines the effect to bind */ Engine.prototype.bindSamplers = function (effect) { this.setProgram(effect.getProgram()); var samplers = effect.getSamplers(); for (var index = 0; index < samplers.length; index++) { var uniform = effect.getUniform(samplers[index]); if (uniform) { this._boundUniforms[index] = uniform; } } this._currentEffect = null; }; Engine.prototype._activateCurrentTexture = function () { if (this._currentTextureChannel !== this._activeChannel) { this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel); this._currentTextureChannel = this._activeChannel; } }; /** @hidden */ Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) { if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; } if (force === void 0) { force = false; } var wasPreviouslyBound = false; var isTextureForRendering = texture && texture._associatedChannel > -1; if (forTextureDataUpdate && isTextureForRendering) { this._activeChannel = texture._associatedChannel; } var currentTextureBound = this._boundTexturesCache[this._activeChannel]; if (currentTextureBound !== texture || force) { this._activateCurrentTexture(); if (texture && texture.isMultiview) { this._gl.bindTexture(target, texture ? texture._colorTextureArray : null); } else { this._gl.bindTexture(target, texture ? texture._webGLTexture : 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; }; /** @hidden */ Engine.prototype._bindTexture = function (channel, texture) { if (channel < 0) { return; } if (texture) { texture._associatedChannel = channel; } this._activeChannel = channel; this._bindTextureDirectly(this._gl.TEXTURE_2D, texture); }; /** * Sets a texture to the webGL context from a postprocess * @param channel defines the channel to use * @param postProcess defines the source postprocess */ Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) { this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null); }; /** * Binds the output of the passed in post process to the texture channel specified * @param channel The channel the texture should be bound to * @param postProcess The post process which's output should be bound */ Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) { this._bindTexture(channel, postProcess ? postProcess._outputTexture : null); }; /** * Unbind all textures from the webGL context */ Engine.prototype.unbindAllTextures = function () { for (var 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); } } }; /** * Sets a texture to the according uniform. * @param channel The texture channel * @param uniform The uniform to set * @param texture The texture to apply */ Engine.prototype.setTexture = function (channel, uniform, texture) { if (channel < 0) { return; } if (uniform) { this._boundUniforms[channel] = uniform; } this._setTexture(channel, texture); }; /** * Sets a depth stencil texture from a render target to the according uniform. * @param channel The texture channel * @param uniform The uniform to set * @param texture The render target texture containing the depth stencil texture to apply */ Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) { if (channel < 0) { return; } if (uniform) { this._boundUniforms[channel] = uniform; } if (!texture || !texture.depthStencilTexture) { this._setTexture(channel, null); } else { this._setTexture(channel, texture, false, true); } }; Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) { var uniform = this._boundUniforms[sourceSlot]; if (uniform._currentState === destination) { return; } this._gl.uniform1i(uniform, destination); uniform._currentState = destination; }; Engine.prototype._getTextureWrapMode = function (mode) { switch (mode) { case Engine.TEXTURE_WRAP_ADDRESSMODE: return this._gl.REPEAT; case Engine.TEXTURE_CLAMP_ADDRESSMODE: return this._gl.CLAMP_TO_EDGE; case Engine.TEXTURE_MIRROR_ADDRESSMODE: return this._gl.MIRRORED_REPEAT; } return this._gl.REPEAT; }; Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) { if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; } if (depthStencilTexture === void 0) { depthStencilTexture = false; } // Not ready? if (!texture) { if (this._boundTexturesCache[channel] != null) { this._activeChannel = channel; this._bindTextureDirectly(this._gl.TEXTURE_2D, null); this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null); if (this.webGLVersion > 1) { this._bindTextureDirectly(this._gl.TEXTURE_3D, null); } } return false; } // Video if (texture.video) { this._activeChannel = channel; texture.update(); } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading texture.delayLoad(); return false; } var 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 { internalTexture = this.emptyTexture; } if (!isPartOfTextureArray && internalTexture) { internalTexture._associatedChannel = channel; } var needToBind = true; if (this._boundTexturesCache[channel] === internalTexture) { if (!isPartOfTextureArray) { this._bindSamplerUniformToChannel(internalTexture._associatedChannel, channel); } needToBind = false; } this._activeChannel = channel; if (internalTexture && internalTexture.isMultiview) { if (needToBind) { this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY, internalTexture, isPartOfTextureArray); } } else if (internalTexture && internalTexture.is3D) { if (needToBind) { this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray); } if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) { internalTexture._cachedWrapU = texture.wrapU; this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture); } if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) { internalTexture._cachedWrapV = texture.wrapV; this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture); } if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) { internalTexture._cachedWrapR = texture.wrapR; this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture); } this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture); } else if (internalTexture && internalTexture.isCube) { if (needToBind) { this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray); } if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) { internalTexture._cachedCoordinatesMode = texture.coordinatesMode; // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE; this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture); this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode); } this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture); } else { if (needToBind) { this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray); } if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) { internalTexture._cachedWrapU = texture.wrapU; this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture); } if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) { internalTexture._cachedWrapV = texture.wrapV; this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture); } this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture); } 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 */ Engine.prototype.setTextureArray = function (channel, uniform, textures) { if (channel < 0 || !uniform) { return; } if (!this._textureUnits || this._textureUnits.length !== textures.length) { this._textureUnits = new Int32Array(textures.length); } for (var i = 0; i < textures.length; i++) { var texture = textures[i].getInternalTexture(); if (texture) { this._textureUnits[channel + i] = channel + i; texture._associatedChannel = channel + i; } else { this._textureUnits[channel + i] = -1; } } this._gl.uniform1iv(uniform, this._textureUnits); for (var index = 0; index < textures.length; index++) { this._setTexture(this._textureUnits[index], textures[index], true); } }; /** @hidden */ Engine.prototype._setAnisotropicLevel = function (target, texture) { var internalTexture = texture.getInternalTexture(); if (!internalTexture) { return; } var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension; var value = texture.anisotropicFilteringLevel; if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) { value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear } if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) { this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture); internalTexture._cachedAnisotropicFilteringLevel = value; } }; Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) { this._bindTextureDirectly(target, texture, true, true); this._gl.texParameterf(target, parameter, value); }; Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) { if (texture) { this._bindTextureDirectly(target, texture, true, true); } this._gl.texParameteri(target, parameter, value); }; /** * 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 * @returns a Uint8Array containing RGBA colors */ Engine.prototype.readPixels = function (x, y, width, height) { var data = new Uint8Array(height * width * 4); this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data); return data; }; /** * Add an externaly 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 * @return true if no such key were already present and the data was added successfully, false otherwise */ Engine.prototype.addExternalData = function (key, data) { if (!this._externalData) { this._externalData = new _Misc_stringDictionary__WEBPACK_IMPORTED_MODULE_3__["StringDictionary"](); } return this._externalData.add(key, data); }; /** * Get an externaly attached data from its key * @param key the unique key that identifies the data * @return the associated data, if present (can be null), or undefined if not present */ Engine.prototype.getExternalData = function (key) { if (!this._externalData) { this._externalData = new _Misc_stringDictionary__WEBPACK_IMPORTED_MODULE_3__["StringDictionary"](); } return this._externalData.get(key); }; /** * Get an externaly 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 * @return the associated data, can be null if the factory returned null. */ Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) { if (!this._externalData) { this._externalData = new _Misc_stringDictionary__WEBPACK_IMPORTED_MODULE_3__["StringDictionary"](); } return this._externalData.getOrAddWithFactory(key, factory); }; /** * Remove an externaly attached data from the Engine instance * @param key the unique key that identifies the data * @return true if the data was successfully removed, false if it doesn't exist */ Engine.prototype.removeExternalData = function (key) { if (!this._externalData) { this._externalData = new _Misc_stringDictionary__WEBPACK_IMPORTED_MODULE_3__["StringDictionary"](); } return this._externalData.remove(key); }; /** * Unbind all vertex attributes from the webGL context */ Engine.prototype.unbindAllAttributes = function () { if (this._mustWipeVertexAttributes) { this._mustWipeVertexAttributes = false; for (var i = 0; i < this._caps.maxVertexAttribs; i++) { this._gl.disableVertexAttribArray(i); this._vertexAttribArraysEnabled[i] = false; this._currentBufferPointers[i].active = false; } return; } for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) { if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) { continue; } this._gl.disableVertexAttribArray(i); this._vertexAttribArraysEnabled[i] = false; this._currentBufferPointers[i].active = false; } }; /** * 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 */ Engine.prototype.releaseEffects = function () { for (var name in this._compiledEffects) { this._deleteProgram(this._compiledEffects[name]._program); } this._compiledEffects = {}; }; /** * Dispose and release all associated resources */ Engine.prototype.dispose = function () { this.hideLoadingUI(); this.stopRenderLoop(); this.onNewSceneAddedObservable.clear(); // Release postProcesses while (this.postProcesses.length) { this.postProcesses[0].dispose(); } // Empty texture if (this._emptyTexture) { this._releaseTexture(this._emptyTexture); this._emptyTexture = null; } if (this._emptyCubeTexture) { this._releaseTexture(this._emptyCubeTexture); this._emptyCubeTexture = null; } // Rescale PP if (this._rescalePostProcess) { this._rescalePostProcess.dispose(); } // Release scenes while (this.scenes.length) { this.scenes[0].dispose(); } // Release audio engine if (Engine.Instances.length === 1 && Engine.audioEngine) { Engine.audioEngine.dispose(); } // Release effects this.releaseEffects(); // Unbind this.unbindAllAttributes(); this._boundUniforms = []; if (this._dummyFramebuffer) { this._gl.deleteFramebuffer(this._dummyFramebuffer); } //WebVR this.disableVR(); // Events if (_Misc_domManagement__WEBPACK_IMPORTED_MODULE_13__["DomManagement"].IsWindowObjectExist()) { window.removeEventListener("blur", this._onBlur); window.removeEventListener("focus", this._onFocus); window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted); window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted); if (this._renderingCanvas) { this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus); this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur); this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut); if (!this._doNotHandleContextLost) { this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost); this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored); } } document.removeEventListener("fullscreenchange", this._onFullscreenChange); document.removeEventListener("mozfullscreenchange", this._onFullscreenChange); document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange); document.removeEventListener("msfullscreenchange", this._onFullscreenChange); document.removeEventListener("pointerlockchange", this._onPointerLockChange); document.removeEventListener("mspointerlockchange", this._onPointerLockChange); document.removeEventListener("mozpointerlockchange", this._onPointerLockChange); document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange); if (this._onVrDisplayConnect) { window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect); if (this._onVrDisplayDisconnect) { window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect); } if (this._onVrDisplayPresentChange) { window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange); } this._onVrDisplayConnect = null; this._onVrDisplayDisconnect = null; } } // Remove from Instances var index = Engine.Instances.indexOf(this); if (index >= 0) { Engine.Instances.splice(index, 1); } this._workingCanvas = null; this._workingContext = null; this._currentBufferPointers = []; this._renderingCanvas = null; this._currentProgram = null; this._bindedRenderFunction = null; this.onResizeObservable.clear(); this.onCanvasBlurObservable.clear(); this.onCanvasFocusObservable.clear(); this.onCanvasPointerOutObservable.clear(); this.onBeginFrameObservable.clear(); this.onEndFrameObservable.clear(); _Materials_effect__WEBPACK_IMPORTED_MODULE_8__["Effect"].ResetCache(); // Abort active requests for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) { var request = _a[_i]; request.abort(); } }; // Loading screen /** * Display the loading screen * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen */ Engine.prototype.displayLoadingUI = function () { if (!_Misc_domManagement__WEBPACK_IMPORTED_MODULE_13__["DomManagement"].IsWindowObjectExist()) { return; } var loadingScreen = this.loadingScreen; if (loadingScreen) { loadingScreen.displayLoadingUI(); } }; /** * Hide the loading screen * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen */ Engine.prototype.hideLoadingUI = function () { if (!_Misc_domManagement__WEBPACK_IMPORTED_MODULE_13__["DomManagement"].IsWindowObjectExist()) { return; } var loadingScreen = this.loadingScreen; if (loadingScreen) { loadingScreen.hideLoadingUI(); } }; Object.defineProperty(Engine.prototype, "loadingScreen", { /** * Gets the current loading screen object * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen */ get: function () { if (!this._loadingScreen && this._renderingCanvas) { this._loadingScreen = Engine.DefaultLoadingScreenFactory(this._renderingCanvas); } return this._loadingScreen; }, /** * Sets the current loading screen object * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen */ set: function (loadingScreen) { this._loadingScreen = loadingScreen; }, enumerable: true, configurable: true }); Object.defineProperty(Engine.prototype, "loadingUIText", { /** * Sets the current loading screen text * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen */ set: function (text) { this.loadingScreen.loadingUIText = text; }, enumerable: true, configurable: true }); Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", { /** * Sets the current loading screen background color * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen */ set: function (color) { this.loadingScreen.loadingUIBackgroundColor = color; }, enumerable: true, configurable: true }); /** * Attach a new callback raised when context lost event is fired * @param callback defines the callback to call */ Engine.prototype.attachContextLostEvent = function (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 */ Engine.prototype.attachContextRestoredEvent = function (callback) { if (this._renderingCanvas) { this._renderingCanvas.addEventListener("webglcontextrestored", callback, false); } }; /** * 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 */ Engine.prototype.getVertexShaderSource = function (program) { var 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 */ Engine.prototype.getFragmentShaderSource = function (program) { var shaders = this._gl.getAttachedShaders(program); if (!shaders) { return null; } return this._gl.getShaderSource(shaders[1]); }; /** * 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 */ Engine.prototype.getError = function () { return this._gl.getError(); }; // FPS /** * Gets the current framerate * @returns a number representing the framerate */ Engine.prototype.getFps = function () { return this._fps; }; /** * Gets the time spent between current and previous frame * @returns a number representing the delta time in ms */ Engine.prototype.getDeltaTime = function () { return this._deltaTime; }; Engine.prototype._measureFps = function () { this._performanceMonitor.sampleFrame(); this._fps = this._performanceMonitor.averageFPS; this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0; }; /** @hidden */ Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) { if (faceIndex === void 0) { faceIndex = -1; } if (level === void 0) { level = 0; } if (buffer === void 0) { buffer = null; } var gl = this._gl; if (!this._dummyFramebuffer) { var 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._webGLTexture, level); } else { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level); } var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE; 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; } gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer); gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer); return buffer; }; Engine.prototype._canRenderToFloatFramebuffer = function () { if (this._webGLVersion > 1) { return this._caps.colorBufferFloat; } return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT); }; Engine.prototype._canRenderToHalfFloatFramebuffer = function () { if (this._webGLVersion > 1) { return this._caps.colorBufferFloat; } return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT); }; // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture Engine.prototype._canRenderToFramebuffer = function (type) { var gl = this._gl; //clear existing errors while (gl.getError() !== gl.NO_ERROR) { } var successful = true; var 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); var fb = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); successful = successful && (status === gl.FRAMEBUFFER_COMPLETE); successful = successful && (gl.getError() === gl.NO_ERROR); //try render by clearing frame buffer's color buffer if (successful) { gl.clear(gl.COLOR_BUFFER_BIT); successful = successful && (gl.getError() === gl.NO_ERROR); } //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported) if (successful) { //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture gl.bindFramebuffer(gl.FRAMEBUFFER, null); var readFormat = gl.RGBA; var readType = gl.UNSIGNED_BYTE; var buffer = new Uint8Array(4); gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer); successful = successful && (gl.getError() === gl.NO_ERROR); } //clean up gl.deleteTexture(texture); gl.deleteFramebuffer(fb); gl.bindFramebuffer(gl.FRAMEBUFFER, null); //clear accumulated errors while (!successful && (gl.getError() !== gl.NO_ERROR)) { } return successful; }; /** @hidden */ Engine.prototype._getWebGLTextureType = function (type) { if (this._webGLVersion === 1) { switch (type) { case Engine.TEXTURETYPE_FLOAT: return this._gl.FLOAT; case Engine.TEXTURETYPE_HALF_FLOAT: return this._gl.HALF_FLOAT_OES; case Engine.TEXTURETYPE_UNSIGNED_BYTE: return this._gl.UNSIGNED_BYTE; } return this._gl.UNSIGNED_BYTE; } switch (type) { case Engine.TEXTURETYPE_BYTE: return this._gl.BYTE; case Engine.TEXTURETYPE_UNSIGNED_BYTE: return this._gl.UNSIGNED_BYTE; case Engine.TEXTURETYPE_SHORT: return this._gl.SHORT; case Engine.TEXTURETYPE_UNSIGNED_SHORT: return this._gl.UNSIGNED_SHORT; case Engine.TEXTURETYPE_INT: return this._gl.INT; case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT return this._gl.UNSIGNED_INT; case Engine.TEXTURETYPE_FLOAT: return this._gl.FLOAT; case Engine.TEXTURETYPE_HALF_FLOAT: return this._gl.HALF_FLOAT; case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4: return this._gl.UNSIGNED_SHORT_4_4_4_4; case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1: return this._gl.UNSIGNED_SHORT_5_5_5_1; case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5: return this._gl.UNSIGNED_SHORT_5_6_5; case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV: return this._gl.UNSIGNED_INT_2_10_10_10_REV; case Engine.TEXTURETYPE_UNSIGNED_INT_24_8: return this._gl.UNSIGNED_INT_24_8; case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV: return this._gl.UNSIGNED_INT_10F_11F_11F_REV; case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV: return this._gl.UNSIGNED_INT_5_9_9_9_REV; case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV: return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV; } return this._gl.UNSIGNED_BYTE; }; Engine.prototype._getInternalFormat = function (format) { var internalFormat = this._gl.RGBA; switch (format) { case Engine.TEXTUREFORMAT_ALPHA: internalFormat = this._gl.ALPHA; break; case Engine.TEXTUREFORMAT_LUMINANCE: internalFormat = this._gl.LUMINANCE; break; case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA: internalFormat = this._gl.LUMINANCE_ALPHA; break; case Engine.TEXTUREFORMAT_RED: internalFormat = this._gl.RED; break; case Engine.TEXTUREFORMAT_RG: internalFormat = this._gl.RG; break; case Engine.TEXTUREFORMAT_RGB: internalFormat = this._gl.RGB; break; case Engine.TEXTUREFORMAT_RGBA: internalFormat = this._gl.RGBA; break; } if (this._webGLVersion > 1) { switch (format) { case Engine.TEXTUREFORMAT_RED_INTEGER: internalFormat = this._gl.RED_INTEGER; break; case Engine.TEXTUREFORMAT_RG_INTEGER: internalFormat = this._gl.RG_INTEGER; break; case Engine.TEXTUREFORMAT_RGB_INTEGER: internalFormat = this._gl.RGB_INTEGER; break; case Engine.TEXTUREFORMAT_RGBA_INTEGER: internalFormat = this._gl.RGBA_INTEGER; break; } } return internalFormat; }; /** @hidden */ Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) { if (this._webGLVersion === 1) { if (format !== undefined) { switch (format) { case Engine.TEXTUREFORMAT_ALPHA: return this._gl.ALPHA; case Engine.TEXTUREFORMAT_LUMINANCE: return this._gl.LUMINANCE; case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA: return this._gl.LUMINANCE_ALPHA; } } return this._gl.RGBA; } switch (type) { case Engine.TEXTURETYPE_BYTE: switch (format) { case Engine.TEXTUREFORMAT_RED: return this._gl.R8_SNORM; case Engine.TEXTUREFORMAT_RG: return this._gl.RG8_SNORM; case Engine.TEXTUREFORMAT_RGB: return this._gl.RGB8_SNORM; case Engine.TEXTUREFORMAT_RED_INTEGER: return this._gl.R8I; case Engine.TEXTUREFORMAT_RG_INTEGER: return this._gl.RG8I; case Engine.TEXTUREFORMAT_RGB_INTEGER: return this._gl.RGB8I; case Engine.TEXTUREFORMAT_RGBA_INTEGER: return this._gl.RGBA8I; default: return this._gl.RGBA8_SNORM; } case Engine.TEXTURETYPE_UNSIGNED_BYTE: switch (format) { case Engine.TEXTUREFORMAT_RED: return this._gl.R8; case Engine.TEXTUREFORMAT_RG: return this._gl.RG8; case Engine.TEXTUREFORMAT_RGB: return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8. case Engine.TEXTUREFORMAT_RGBA: return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8. case Engine.TEXTUREFORMAT_RED_INTEGER: return this._gl.R8UI; case Engine.TEXTUREFORMAT_RG_INTEGER: return this._gl.RG8UI; case Engine.TEXTUREFORMAT_RGB_INTEGER: return this._gl.RGB8UI; case Engine.TEXTUREFORMAT_RGBA_INTEGER: return this._gl.RGBA8UI; default: return this._gl.RGBA8; } case Engine.TEXTURETYPE_SHORT: switch (format) { case Engine.TEXTUREFORMAT_RED_INTEGER: return this._gl.R16I; case Engine.TEXTUREFORMAT_RG_INTEGER: return this._gl.RG16I; case Engine.TEXTUREFORMAT_RGB_INTEGER: return this._gl.RGB16I; case Engine.TEXTUREFORMAT_RGBA_INTEGER: return this._gl.RGBA16I; default: return this._gl.RGBA16I; } case Engine.TEXTURETYPE_UNSIGNED_SHORT: switch (format) { case Engine.TEXTUREFORMAT_RED_INTEGER: return this._gl.R16UI; case Engine.TEXTUREFORMAT_RG_INTEGER: return this._gl.RG16UI; case Engine.TEXTUREFORMAT_RGB_INTEGER: return this._gl.RGB16UI; case Engine.TEXTUREFORMAT_RGBA_INTEGER: return this._gl.RGBA16UI; default: return this._gl.RGBA16UI; } case Engine.TEXTURETYPE_INT: switch (format) { case Engine.TEXTUREFORMAT_RED_INTEGER: return this._gl.R32I; case Engine.TEXTUREFORMAT_RG_INTEGER: return this._gl.RG32I; case Engine.TEXTUREFORMAT_RGB_INTEGER: return this._gl.RGB32I; case Engine.TEXTUREFORMAT_RGBA_INTEGER: return this._gl.RGBA32I; default: return this._gl.RGBA32I; } case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT switch (format) { case Engine.TEXTUREFORMAT_RED_INTEGER: return this._gl.R32UI; case Engine.TEXTUREFORMAT_RG_INTEGER: return this._gl.RG32UI; case Engine.TEXTUREFORMAT_RGB_INTEGER: return this._gl.RGB32UI; case Engine.TEXTUREFORMAT_RGBA_INTEGER: return this._gl.RGBA32UI; default: return this._gl.RGBA32UI; } case Engine.TEXTURETYPE_FLOAT: switch (format) { case Engine.TEXTUREFORMAT_RED: return this._gl.R32F; // By default. Other possibility is R16F. case Engine.TEXTUREFORMAT_RG: return this._gl.RG32F; // By default. Other possibility is RG16F. case Engine.TEXTUREFORMAT_RGB: return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5. case Engine.TEXTUREFORMAT_RGBA: return this._gl.RGBA32F; // By default. Other possibility is RGBA16F. default: return this._gl.RGBA32F; } case Engine.TEXTURETYPE_HALF_FLOAT: switch (format) { case Engine.TEXTUREFORMAT_RED: return this._gl.R16F; case Engine.TEXTUREFORMAT_RG: return this._gl.RG16F; case Engine.TEXTUREFORMAT_RGB: return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5. case Engine.TEXTUREFORMAT_RGBA: return this._gl.RGBA16F; default: return this._gl.RGBA16F; } case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5: return this._gl.RGB565; case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV: return this._gl.R11F_G11F_B10F; case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV: return this._gl.RGB9_E5; case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4: return this._gl.RGBA4; case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1: return this._gl.RGB5_A1; case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV: switch (format) { case Engine.TEXTUREFORMAT_RGBA: return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1. case Engine.TEXTUREFORMAT_RGBA_INTEGER: return this._gl.RGB10_A2UI; default: return this._gl.RGB10_A2; } } return this._gl.RGBA8; }; /** @hidden */ Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) { if (type === Engine.TEXTURETYPE_FLOAT) { return this._gl.RGBA32F; } else if (type === Engine.TEXTURETYPE_HALF_FLOAT) { return this._gl.RGBA16F; } return this._gl.RGBA8; }; /** @hidden */ Engine.prototype._loadFile = function (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) { var _this = this; var request = _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError); this._activeRequests.push(request); request.onCompleteObservable.add(function (request) { _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1); }); return request; }; /** @hidden */ Engine.prototype._loadFileAsync = function (url, offlineProvider, useArrayBuffer) { var _this = this; return new Promise(function (resolve, reject) { _this._loadFile(url, function (data) { resolve(data); }, undefined, offlineProvider, useArrayBuffer, function (request, exception) { reject(exception); }); }); }; Engine.prototype._partialLoadFile = function (url, index, loadedFiles, onfinish, onErrorCallBack) { if (onErrorCallBack === void 0) { onErrorCallBack = null; } var onload = function (data) { loadedFiles[index] = data; loadedFiles._internalCount++; if (loadedFiles._internalCount === 6) { onfinish(loadedFiles); } }; var onerror = function (request, exception) { if (onErrorCallBack && request) { onErrorCallBack(request.status + " " + request.statusText, exception); } }; this._loadFile(url, onload, undefined, undefined, true, onerror); }; Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) { if (onError === void 0) { onError = null; } var loadedFiles = []; loadedFiles._internalCount = 0; for (var index = 0; index < 6; index++) { this._partialLoadFile(files[index], index, loadedFiles, onfinish, onError); } }; // Statics /** * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found) * @returns true if the engine can be created * @ignorenaming */ Engine.isSupported = function () { try { var tempcanvas = document.createElement("canvas"); var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"); return gl != null && !!window.WebGLRenderingContext; } catch (e) { return false; } }; /** Use this array to turn off some WebGL2 features on known buggy browsers version */ Engine.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"] } ]; /** * Hidden */ Engine._TextureLoaders = []; // Const statics /** Defines that alpha blending is disabled */ Engine.ALPHA_DISABLE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].ALPHA_DISABLE; /** Defines that alpha blending to SRC ALPHA * SRC + DEST */ Engine.ALPHA_ADD = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].ALPHA_ADD; /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */ Engine.ALPHA_COMBINE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].ALPHA_COMBINE; /** Defines that alpha blending to DEST - SRC * DEST */ Engine.ALPHA_SUBTRACT = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].ALPHA_SUBTRACT; /** Defines that alpha blending to SRC * DEST */ Engine.ALPHA_MULTIPLY = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].ALPHA_MULTIPLY; /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */ Engine.ALPHA_MAXIMIZED = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].ALPHA_MAXIMIZED; /** Defines that alpha blending to SRC + DEST */ Engine.ALPHA_ONEONE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].ALPHA_ONEONE; /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */ Engine.ALPHA_PREMULTIPLIED = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].ALPHA_PREMULTIPLIED; /** * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA */ Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].ALPHA_PREMULTIPLIED_PORTERDUFF; /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */ Engine.ALPHA_INTERPOLATE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].ALPHA_INTERPOLATE; /** * Defines that alpha blending to SRC + (1 - SRC) * DEST * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA */ Engine.ALPHA_SCREENMODE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].ALPHA_SCREENMODE; /** Defines that the ressource is not delayed*/ Engine.DELAYLOADSTATE_NONE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].DELAYLOADSTATE_NONE; /** Defines that the ressource was successfully delay loaded */ Engine.DELAYLOADSTATE_LOADED = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].DELAYLOADSTATE_LOADED; /** Defines that the ressource is currently delay loading */ Engine.DELAYLOADSTATE_LOADING = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].DELAYLOADSTATE_LOADING; /** Defines that the ressource is delayed and has not started loading */ Engine.DELAYLOADSTATE_NOTLOADED = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].DELAYLOADSTATE_NOTLOADED; // Depht or Stencil test Constants. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */ Engine.NEVER = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].NEVER; /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */ Engine.ALWAYS = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].ALWAYS; /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */ Engine.LESS = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].LESS; /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */ Engine.EQUAL = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].EQUAL; /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */ Engine.LEQUAL = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].LEQUAL; /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */ Engine.GREATER = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].GREATER; /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */ Engine.GEQUAL = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].GEQUAL; /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */ Engine.NOTEQUAL = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].NOTEQUAL; // Stencil Actions Constants. /** Passed to stencilOperation to specify that stencil value must be kept */ Engine.KEEP = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].KEEP; /** Passed to stencilOperation to specify that stencil value must be replaced */ Engine.REPLACE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].REPLACE; /** Passed to stencilOperation to specify that stencil value must be incremented */ Engine.INCR = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].INCR; /** Passed to stencilOperation to specify that stencil value must be decremented */ Engine.DECR = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].DECR; /** Passed to stencilOperation to specify that stencil value must be inverted */ Engine.INVERT = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].INVERT; /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */ Engine.INCR_WRAP = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].INCR_WRAP; /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */ Engine.DECR_WRAP = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].DECR_WRAP; /** Texture is not repeating outside of 0..1 UVs */ Engine.TEXTURE_CLAMP_ADDRESSMODE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_CLAMP_ADDRESSMODE; /** Texture is repeating outside of 0..1 UVs */ Engine.TEXTURE_WRAP_ADDRESSMODE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_WRAP_ADDRESSMODE; /** Texture is repeating and mirrored */ Engine.TEXTURE_MIRROR_ADDRESSMODE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_MIRROR_ADDRESSMODE; /** ALPHA */ Engine.TEXTUREFORMAT_ALPHA = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTUREFORMAT_ALPHA; /** LUMINANCE */ Engine.TEXTUREFORMAT_LUMINANCE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTUREFORMAT_LUMINANCE; /** LUMINANCE_ALPHA */ Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTUREFORMAT_LUMINANCE_ALPHA; /** RGB */ Engine.TEXTUREFORMAT_RGB = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTUREFORMAT_RGB; /** RGBA */ Engine.TEXTUREFORMAT_RGBA = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTUREFORMAT_RGBA; /** RED */ Engine.TEXTUREFORMAT_RED = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTUREFORMAT_RED; /** RED (2nd reference) */ Engine.TEXTUREFORMAT_R = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTUREFORMAT_R; /** RG */ Engine.TEXTUREFORMAT_RG = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTUREFORMAT_RG; /** RED_INTEGER */ Engine.TEXTUREFORMAT_RED_INTEGER = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTUREFORMAT_RED_INTEGER; /** RED_INTEGER (2nd reference) */ Engine.TEXTUREFORMAT_R_INTEGER = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTUREFORMAT_R_INTEGER; /** RG_INTEGER */ Engine.TEXTUREFORMAT_RG_INTEGER = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTUREFORMAT_RG_INTEGER; /** RGB_INTEGER */ Engine.TEXTUREFORMAT_RGB_INTEGER = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTUREFORMAT_RGB_INTEGER; /** RGBA_INTEGER */ Engine.TEXTUREFORMAT_RGBA_INTEGER = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTUREFORMAT_RGBA_INTEGER; /** UNSIGNED_BYTE */ Engine.TEXTURETYPE_UNSIGNED_BYTE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURETYPE_UNSIGNED_BYTE; /** UNSIGNED_BYTE (2nd reference) */ Engine.TEXTURETYPE_UNSIGNED_INT = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURETYPE_UNSIGNED_INT; /** FLOAT */ Engine.TEXTURETYPE_FLOAT = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURETYPE_FLOAT; /** HALF_FLOAT */ Engine.TEXTURETYPE_HALF_FLOAT = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURETYPE_HALF_FLOAT; /** BYTE */ Engine.TEXTURETYPE_BYTE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURETYPE_BYTE; /** SHORT */ Engine.TEXTURETYPE_SHORT = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURETYPE_SHORT; /** UNSIGNED_SHORT */ Engine.TEXTURETYPE_UNSIGNED_SHORT = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURETYPE_UNSIGNED_SHORT; /** INT */ Engine.TEXTURETYPE_INT = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURETYPE_INT; /** UNSIGNED_INT */ Engine.TEXTURETYPE_UNSIGNED_INTEGER = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURETYPE_UNSIGNED_INTEGER; /** UNSIGNED_SHORT_4_4_4_4 */ Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4; /** UNSIGNED_SHORT_5_5_5_1 */ Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1; /** UNSIGNED_SHORT_5_6_5 */ Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURETYPE_UNSIGNED_SHORT_5_6_5; /** UNSIGNED_INT_2_10_10_10_REV */ Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV; /** UNSIGNED_INT_24_8 */ Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURETYPE_UNSIGNED_INT_24_8; /** UNSIGNED_INT_10F_11F_11F_REV */ Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV; /** UNSIGNED_INT_5_9_9_9_REV */ Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV; /** FLOAT_32_UNSIGNED_INT_24_8_REV */ Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV; /** nearest is mag = nearest and min = nearest and mip = linear */ Engine.TEXTURE_NEAREST_SAMPLINGMODE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE; /** Bilinear is mag = linear and min = linear and mip = nearest */ Engine.TEXTURE_BILINEAR_SAMPLINGMODE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_BILINEAR_SAMPLINGMODE; /** Trilinear is mag = linear and min = linear and mip = linear */ Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; /** nearest is mag = nearest and min = nearest and mip = linear */ Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_NEAREST_NEAREST_MIPLINEAR; /** Bilinear is mag = linear and min = linear and mip = nearest */ Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_LINEAR_LINEAR_MIPNEAREST; /** Trilinear is mag = linear and min = linear and mip = linear */ Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_LINEAR_LINEAR_MIPLINEAR; /** mag = nearest and min = nearest and mip = nearest */ Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_NEAREST_NEAREST_MIPNEAREST; /** mag = nearest and min = linear and mip = nearest */ Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_NEAREST_LINEAR_MIPNEAREST; /** mag = nearest and min = linear and mip = linear */ Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_NEAREST_LINEAR_MIPLINEAR; /** mag = nearest and min = linear and mip = none */ Engine.TEXTURE_NEAREST_LINEAR = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_NEAREST_LINEAR; /** mag = nearest and min = nearest and mip = none */ Engine.TEXTURE_NEAREST_NEAREST = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_NEAREST_NEAREST; /** mag = linear and min = nearest and mip = nearest */ Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_LINEAR_NEAREST_MIPNEAREST; /** mag = linear and min = nearest and mip = linear */ Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_LINEAR_NEAREST_MIPLINEAR; /** mag = linear and min = linear and mip = none */ Engine.TEXTURE_LINEAR_LINEAR = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_LINEAR_LINEAR; /** mag = linear and min = nearest and mip = none */ Engine.TEXTURE_LINEAR_NEAREST = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_LINEAR_NEAREST; /** Explicit coordinates mode */ Engine.TEXTURE_EXPLICIT_MODE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_EXPLICIT_MODE; /** Spherical coordinates mode */ Engine.TEXTURE_SPHERICAL_MODE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_SPHERICAL_MODE; /** Planar coordinates mode */ Engine.TEXTURE_PLANAR_MODE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_PLANAR_MODE; /** Cubic coordinates mode */ Engine.TEXTURE_CUBIC_MODE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_CUBIC_MODE; /** Projection coordinates mode */ Engine.TEXTURE_PROJECTION_MODE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_PROJECTION_MODE; /** Skybox coordinates mode */ Engine.TEXTURE_SKYBOX_MODE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_SKYBOX_MODE; /** Inverse Cubic coordinates mode */ Engine.TEXTURE_INVCUBIC_MODE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_INVCUBIC_MODE; /** Equirectangular coordinates mode */ Engine.TEXTURE_EQUIRECTANGULAR_MODE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_EQUIRECTANGULAR_MODE; /** Equirectangular Fixed coordinates mode */ Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_FIXED_EQUIRECTANGULAR_MODE; /** Equirectangular Fixed Mirrored coordinates mode */ Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // Texture rescaling mode /** Defines that texture rescaling will use a floor to find the closer power of 2 size */ Engine.SCALEMODE_FLOOR = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].SCALEMODE_FLOOR; /** Defines that texture rescaling will look for the nearest power of 2 size */ Engine.SCALEMODE_NEAREST = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].SCALEMODE_NEAREST; /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */ Engine.SCALEMODE_CEILING = _constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].SCALEMODE_CEILING; // Updatable statics so stick with vars here /** * Gets or sets the epsilon value used by collision engine */ Engine.CollisionsEpsilon = 0.001; /** * Method called to create the default rescale post process on each engine. */ Engine._RescalePostProcessFactory = null; return Engine; }()); /***/ }), /***/ "./Engines/engineStore.ts": /*!********************************!*\ !*** ./Engines/engineStore.ts ***! \********************************/ /*! exports provided: EngineStore */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EngineStore", function() { return EngineStore; }); /** * The engine store class is responsible to hold all the instances of Engine and Scene created * during the life time of the application. */ var EngineStore = /** @class */ (function () { function EngineStore() { } Object.defineProperty(EngineStore, "LastCreatedEngine", { /** * Gets the latest created engine */ get: function () { if (this.Instances.length === 0) { return null; } return this.Instances[this.Instances.length - 1]; }, enumerable: true, configurable: true }); Object.defineProperty(EngineStore, "LastCreatedScene", { /** * Gets the latest created scene */ get: function () { var lastCreatedEngine = this.LastCreatedEngine; if (!lastCreatedEngine) { return null; } if (lastCreatedEngine.scenes.length === 0) { return null; } return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1]; }, enumerable: true, configurable: true }); /** Gets the list of created engines */ EngineStore.Instances = new Array(); return EngineStore; }()); /***/ }), /***/ "./Engines/index.ts": /*!**************************!*\ !*** ./Engines/index.ts ***! \**************************/ /*! exports provided: Constants, InstancingAttributeInfo, DepthTextureCreationOptions, EngineCapabilities, Engine, EngineStore, NullEngineOptions, NullEngine, _OcclusionDataStorage, _forceTransformFeedbackToBundle */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./constants */ "./Engines/constants.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Constants", function() { return _constants__WEBPACK_IMPORTED_MODULE_0__["Constants"]; }); /* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine */ "./Engines/engine.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InstancingAttributeInfo", function() { return _engine__WEBPACK_IMPORTED_MODULE_1__["InstancingAttributeInfo"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthTextureCreationOptions", function() { return _engine__WEBPACK_IMPORTED_MODULE_1__["DepthTextureCreationOptions"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EngineCapabilities", function() { return _engine__WEBPACK_IMPORTED_MODULE_1__["EngineCapabilities"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Engine", function() { return _engine__WEBPACK_IMPORTED_MODULE_1__["Engine"]; }); /* harmony import */ var _engineStore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./engineStore */ "./Engines/engineStore.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EngineStore", function() { return _engineStore__WEBPACK_IMPORTED_MODULE_2__["EngineStore"]; }); /* harmony import */ var _nullEngine__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./nullEngine */ "./Engines/nullEngine.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NullEngineOptions", function() { return _nullEngine__WEBPACK_IMPORTED_MODULE_3__["NullEngineOptions"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NullEngine", function() { return _nullEngine__WEBPACK_IMPORTED_MODULE_3__["NullEngine"]; }); /* harmony import */ var _Extensions_index__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Extensions/index */ "./Engines/Extensions/index.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_OcclusionDataStorage", function() { return _Extensions_index__WEBPACK_IMPORTED_MODULE_4__["_OcclusionDataStorage"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_forceTransformFeedbackToBundle", function() { return _Extensions_index__WEBPACK_IMPORTED_MODULE_4__["_forceTransformFeedbackToBundle"]; }); /***/ }), /***/ "./Engines/nullEngine.ts": /*!*******************************!*\ !*** ./Engines/nullEngine.ts ***! \*******************************/ /*! exports provided: NullEngineOptions, NullEngine */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NullEngineOptions", function() { return NullEngineOptions; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NullEngine", function() { return NullEngine; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); /* harmony import */ var _Materials_Textures_renderTargetCreationOptions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Materials/Textures/renderTargetCreationOptions */ "./Materials/Textures/renderTargetCreationOptions.ts"); /* harmony import */ var _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Materials/Textures/internalTexture */ "./Materials/Textures/internalTexture.ts"); /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./constants */ "./Engines/constants.ts"); /** * Options to create the null engine */ var NullEngineOptions = /** @class */ (function () { function NullEngineOptions() { /** * Render width (Default: 512) */ this.renderWidth = 512; /** * Render height (Default: 256) */ this.renderHeight = 256; /** * Texture size (Default: 512) */ this.textureSize = 512; /** * If delta time between frames should be constant * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep */ this.deterministicLockstep = false; /** * Maximum about of steps between frames (Default: 4) * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep */ this.lockstepMaxSteps = 4; } return NullEngineOptions; }()); /** * The null engine class provides support for headless version of babylon.js. * This can be used in server side scenario or for testing purposes */ var NullEngine = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](NullEngine, _super); function NullEngine(options) { if (options === void 0) { options = new NullEngineOptions(); } var _this = _super.call(this, null) || this; if (options.deterministicLockstep === undefined) { options.deterministicLockstep = false; } if (options.lockstepMaxSteps === undefined) { options.lockstepMaxSteps = 4; } _this._options = options; // Init caps // We consider we are on a webgl1 capable device _this._caps = new _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["EngineCapabilities"](); _this._caps.maxTexturesImageUnits = 16; _this._caps.maxVertexTextureImageUnits = 16; _this._caps.maxTextureSize = 512; _this._caps.maxCubemapTextureSize = 512; _this._caps.maxRenderTextureSize = 512; _this._caps.maxVertexAttribs = 16; _this._caps.maxVaryingVectors = 16; _this._caps.maxFragmentUniformVectors = 16; _this._caps.maxVertexUniformVectors = 16; // Extensions _this._caps.standardDerivatives = false; _this._caps.astc = null; _this._caps.s3tc = null; _this._caps.pvrtc = null; _this._caps.etc1 = null; _this._caps.etc2 = null; _this._caps.textureAnisotropicFilterExtension = null; _this._caps.maxAnisotropy = 0; _this._caps.uintIndices = false; _this._caps.fragmentDepthSupported = false; _this._caps.highPrecisionShaderSupported = true; _this._caps.colorBufferFloat = false; _this._caps.textureFloat = false; _this._caps.textureFloatLinearFiltering = false; _this._caps.textureFloatRender = false; _this._caps.textureHalfFloat = false; _this._caps.textureHalfFloatLinearFiltering = false; _this._caps.textureHalfFloatRender = false; _this._caps.textureLOD = false; _this._caps.drawBuffersExtension = false; _this._caps.depthTextureExtension = false; _this._caps.vertexArrayObject = false; _this._caps.instancedArrays = false; _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Log("Babylon.js v" + _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Version + " - Null engine"); // Wrappers var theCurrentGlobal = (typeof self !== "undefined" ? self : typeof global !== "undefined" ? global : window); if (typeof URL === "undefined") { theCurrentGlobal.URL = { createObjectURL: function () { }, revokeObjectURL: function () { } }; } if (typeof Blob === "undefined") { theCurrentGlobal.Blob = function () { }; } return _this; } /** * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep */ NullEngine.prototype.isDeterministicLockStep = function () { return this._options.deterministicLockstep; }; /** @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep */ NullEngine.prototype.getLockstepMaxSteps = function () { return this._options.lockstepMaxSteps; }; /** * Sets hardware scaling, used to save performance if needed * @see https://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer */ NullEngine.prototype.getHardwareScalingLevel = function () { return 1.0; }; NullEngine.prototype.createVertexBuffer = function (vertices) { return { capacity: 0, references: 1, is32Bits: false }; }; NullEngine.prototype.createIndexBuffer = function (indices) { return { capacity: 0, references: 1, is32Bits: false }; }; NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) { if (stencil === void 0) { stencil = false; } }; NullEngine.prototype.getRenderWidth = function (useScreen) { if (useScreen === void 0) { useScreen = false; } if (!useScreen && this._currentRenderTarget) { return this._currentRenderTarget.width; } return this._options.renderWidth; }; NullEngine.prototype.getRenderHeight = function (useScreen) { if (useScreen === void 0) { useScreen = false; } if (!useScreen && this._currentRenderTarget) { return this._currentRenderTarget.height; } return this._options.renderHeight; }; NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) { this._cachedViewport = viewport; }; NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) { return { transformFeedback: null, __SPECTOR_rebuildProgram: null, isParallelCompiled: false }; }; NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) { return []; }; NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) { return []; }; NullEngine.prototype.bindSamplers = function (effect) { this._currentEffect = null; }; NullEngine.prototype.enableEffect = function (effect) { this._currentEffect = effect; if (effect.onBind) { effect.onBind(effect); } if (effect._onBindObservable) { effect._onBindObservable.notifyObservers(effect); } }; NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) { if (zOffset === void 0) { zOffset = 0; } if (reverseSide === void 0) { reverseSide = false; } }; NullEngine.prototype.setIntArray = function (uniform, array) { }; NullEngine.prototype.setIntArray2 = function (uniform, array) { }; NullEngine.prototype.setIntArray3 = function (uniform, array) { }; NullEngine.prototype.setIntArray4 = function (uniform, array) { }; NullEngine.prototype.setFloatArray = function (uniform, array) { }; NullEngine.prototype.setFloatArray2 = function (uniform, array) { }; NullEngine.prototype.setFloatArray3 = function (uniform, array) { }; NullEngine.prototype.setFloatArray4 = function (uniform, array) { }; NullEngine.prototype.setArray = function (uniform, array) { }; NullEngine.prototype.setArray2 = function (uniform, array) { }; NullEngine.prototype.setArray3 = function (uniform, array) { }; NullEngine.prototype.setArray4 = function (uniform, array) { }; NullEngine.prototype.setMatrices = function (uniform, matrices) { }; NullEngine.prototype.setMatrix = function (uniform, matrix) { }; NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) { }; NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) { }; NullEngine.prototype.setFloat = function (uniform, value) { }; NullEngine.prototype.setFloat2 = function (uniform, x, y) { }; NullEngine.prototype.setFloat3 = function (uniform, x, y, z) { }; NullEngine.prototype.setBool = function (uniform, bool) { }; NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) { }; NullEngine.prototype.setColor3 = function (uniform, color3) { }; NullEngine.prototype.setColor4 = function (uniform, color3, alpha) { }; NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) { if (noDepthWriteChange === void 0) { noDepthWriteChange = false; } if (this._alphaMode === mode) { return; } this._alphaState.alphaBlend = (mode !== _constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].ALPHA_DISABLE); if (!noDepthWriteChange) { this.setDepthWrite(mode === _constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].ALPHA_DISABLE); } this._alphaMode = mode; }; NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) { }; NullEngine.prototype.wipeCaches = function (bruteForce) { if (this.preventCacheWipeBetweenFrames) { return; } this.resetTextureCache(); this._currentEffect = null; if (bruteForce) { this._currentProgram = null; this._stencilState.reset(); this._depthCullingState.reset(); this._alphaState.reset(); } this._cachedVertexBuffers = null; this._cachedIndexBuffer = null; this._cachedEffectForVertexBuffers = null; }; NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) { }; NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) { }; NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) { }; /** @hidden */ NullEngine.prototype._createTexture = function () { return {}; }; /** @hidden */ NullEngine.prototype._releaseTexture = function (texture) { }; NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) { if (samplingMode === void 0) { samplingMode = _constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; } if (onLoad === void 0) { onLoad = null; } if (onError === void 0) { onError = null; } if (buffer === void 0) { buffer = null; } var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_4__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_4__["InternalTexture"].DATASOURCE_URL); var url = String(urlArg); texture.url = url; texture.generateMipMaps = !noMipmap; texture.samplingMode = samplingMode; texture.invertY = invertY; texture.baseWidth = this._options.textureSize; texture.baseHeight = this._options.textureSize; texture.width = this._options.textureSize; texture.height = this._options.textureSize; if (format) { texture.format = format; } texture.isReady = true; if (onLoad) { onLoad(); } this._internalTexturesCache.push(texture); return texture; }; NullEngine.prototype.createRenderTargetTexture = function (size, options) { var fullOptions = new _Materials_Textures_renderTargetCreationOptions__WEBPACK_IMPORTED_MODULE_3__["RenderTargetCreationOptions"](); if (options !== undefined && typeof options === "object") { fullOptions.generateMipMaps = options.generateMipMaps; fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer; fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer; fullOptions.type = options.type === undefined ? _constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURETYPE_UNSIGNED_INT : options.type; fullOptions.samplingMode = options.samplingMode === undefined ? _constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode; } else { fullOptions.generateMipMaps = options; fullOptions.generateDepthBuffer = true; fullOptions.generateStencilBuffer = false; fullOptions.type = _constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURETYPE_UNSIGNED_INT; fullOptions.samplingMode = _constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; } var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_4__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_4__["InternalTexture"].DATASOURCE_RENDERTARGET); var width = size.width || size; var height = size.height || size; texture._depthStencilBuffer = {}; texture._framebuffer = {}; texture.baseWidth = width; texture.baseHeight = height; texture.width = width; texture.height = height; texture.isReady = true; texture.samples = 1; texture.generateMipMaps = fullOptions.generateMipMaps ? true : false; texture.samplingMode = fullOptions.samplingMode; texture.type = fullOptions.type; texture._generateDepthBuffer = fullOptions.generateDepthBuffer; texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false; this._internalTexturesCache.push(texture); return texture; }; NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) { texture.samplingMode = samplingMode; }; NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) { if (this._currentRenderTarget) { this.unBindFramebuffer(this._currentRenderTarget); } this._currentRenderTarget = texture; this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer; if (this._cachedViewport && !forceFullscreenViewport) { this.setViewport(this._cachedViewport, requiredWidth, requiredHeight); } }; NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) { if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; } this._currentRenderTarget = null; if (onBeforeUnbind) { if (texture._MSAAFramebuffer) { this._currentFramebuffer = texture._framebuffer; } onBeforeUnbind(); } this._currentFramebuffer = null; }; NullEngine.prototype.createDynamicVertexBuffer = function (vertices) { var vbo = { capacity: 1, references: 1, is32Bits: false }; return vbo; }; NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) { if (premulAlpha === void 0) { premulAlpha = false; } }; NullEngine.prototype.areAllEffectsReady = function () { return true; }; /** * @hidden * 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 */ NullEngine.prototype.getError = function () { return 0; }; /** @hidden */ NullEngine.prototype._getUnpackAlignement = function () { return 1; }; /** @hidden */ NullEngine.prototype._unpackFlipY = function (value) { }; NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) { if (offset === void 0) { offset = 0; } }; /** * Updates a dynamic vertex buffer. * @param vertexBuffer the vertex buffer to update * @param data the data used to update the vertex buffer * @param byteOffset the byte offset of the data (optional) * @param byteLength the byte length of the data (optional) */ NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) { }; NullEngine.prototype._bindTextureDirectly = function (target, texture) { if (this._boundTexturesCache[this._activeChannel] !== texture) { this._boundTexturesCache[this._activeChannel] = texture; return true; } return false; }; /** @hidden */ NullEngine.prototype._bindTexture = function (channel, texture) { if (channel < 0) { return; } this._bindTextureDirectly(0, texture); }; /** @hidden */ NullEngine.prototype._releaseBuffer = function (buffer) { buffer.references--; if (buffer.references === 0) { return true; } return false; }; NullEngine.prototype.releaseEffects = function () { }; NullEngine.prototype.displayLoadingUI = function () { }; NullEngine.prototype.hideLoadingUI = function () { }; /** @hidden */ NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) { if (faceIndex === void 0) { faceIndex = 0; } if (lod === void 0) { lod = 0; } }; /** @hidden */ NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) { if (faceIndex === void 0) { faceIndex = 0; } if (lod === void 0) { lod = 0; } }; /** @hidden */ NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) { if (faceIndex === void 0) { faceIndex = 0; } if (lod === void 0) { lod = 0; } }; /** @hidden */ NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) { if (faceIndex === void 0) { faceIndex = 0; } if (lod === void 0) { lod = 0; } }; return NullEngine; }(_Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"])); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/webpack/buildin/global.js */ "../node_modules/webpack/buildin/global.js"))) /***/ }), /***/ "./Events/clipboardEvents.ts": /*!***********************************!*\ !*** ./Events/clipboardEvents.ts ***! \***********************************/ /*! exports provided: ClipboardEventTypes, ClipboardInfo */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ClipboardEventTypes", function() { return ClipboardEventTypes; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ClipboardInfo", function() { return ClipboardInfo; }); /** * Gather the list of clipboard event types as constants. */ var ClipboardEventTypes = /** @class */ (function () { function ClipboardEventTypes() { } /** * The clipboard event is fired when a copy command is active (pressed). */ ClipboardEventTypes.COPY = 0x01; // /** * The clipboard event is fired when a cut command is active (pressed). */ ClipboardEventTypes.CUT = 0x02; /** * The clipboard event is fired when a paste command is active (pressed). */ ClipboardEventTypes.PASTE = 0x03; return ClipboardEventTypes; }()); /** * This class is used to store clipboard related info for the onClipboardObservable event. */ var ClipboardInfo = /** @class */ (function () { /** *Creates an instance of ClipboardInfo. * @param type Defines the type of event (BABYLON.ClipboardEventTypes) * @param event Defines the related dom event */ function ClipboardInfo( /** * Defines the type of event (BABYLON.ClipboardEventTypes) */ type, /** * Defines the related dom event */ event) { this.type = type; this.event = event; } /** * Get the clipboard event's type from the keycode. * @param keyCode Defines the keyCode for the current keyboard event. * @return {number} */ ClipboardInfo.GetTypeFromCharacter = function (keyCode) { var charCode = keyCode; //TODO: add codes for extended ASCII switch (charCode) { case 67: return ClipboardEventTypes.COPY; case 86: return ClipboardEventTypes.PASTE; case 88: return ClipboardEventTypes.CUT; default: return -1; } }; return ClipboardInfo; }()); /***/ }), /***/ "./Events/index.ts": /*!*************************!*\ !*** ./Events/index.ts ***! \*************************/ /*! exports provided: KeyboardEventTypes, KeyboardInfo, KeyboardInfoPre, PointerEventTypes, PointerInfoBase, PointerInfoPre, PointerInfo, ClipboardEventTypes, ClipboardInfo */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _keyboardEvents__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./keyboardEvents */ "./Events/keyboardEvents.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyboardEventTypes", function() { return _keyboardEvents__WEBPACK_IMPORTED_MODULE_0__["KeyboardEventTypes"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyboardInfo", function() { return _keyboardEvents__WEBPACK_IMPORTED_MODULE_0__["KeyboardInfo"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyboardInfoPre", function() { return _keyboardEvents__WEBPACK_IMPORTED_MODULE_0__["KeyboardInfoPre"]; }); /* harmony import */ var _pointerEvents__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./pointerEvents */ "./Events/pointerEvents.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerEventTypes", function() { return _pointerEvents__WEBPACK_IMPORTED_MODULE_1__["PointerEventTypes"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerInfoBase", function() { return _pointerEvents__WEBPACK_IMPORTED_MODULE_1__["PointerInfoBase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerInfoPre", function() { return _pointerEvents__WEBPACK_IMPORTED_MODULE_1__["PointerInfoPre"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerInfo", function() { return _pointerEvents__WEBPACK_IMPORTED_MODULE_1__["PointerInfo"]; }); /* harmony import */ var _clipboardEvents__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./clipboardEvents */ "./Events/clipboardEvents.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClipboardEventTypes", function() { return _clipboardEvents__WEBPACK_IMPORTED_MODULE_2__["ClipboardEventTypes"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClipboardInfo", function() { return _clipboardEvents__WEBPACK_IMPORTED_MODULE_2__["ClipboardInfo"]; }); /***/ }), /***/ "./Events/keyboardEvents.ts": /*!**********************************!*\ !*** ./Events/keyboardEvents.ts ***! \**********************************/ /*! exports provided: KeyboardEventTypes, KeyboardInfo, KeyboardInfoPre */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyboardEventTypes", function() { return KeyboardEventTypes; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyboardInfo", function() { return KeyboardInfo; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyboardInfoPre", function() { return KeyboardInfoPre; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /** * Gather the list of keyboard event types as constants. */ var KeyboardEventTypes = /** @class */ (function () { function KeyboardEventTypes() { } /** * The keydown event is fired when a key becomes active (pressed). */ KeyboardEventTypes.KEYDOWN = 0x01; /** * The keyup event is fired when a key has been released. */ KeyboardEventTypes.KEYUP = 0x02; return KeyboardEventTypes; }()); /** * This class is used to store keyboard related info for the onKeyboardObservable event. */ var KeyboardInfo = /** @class */ (function () { /** * 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 */ function KeyboardInfo( /** * Defines the type of event (KeyboardEventTypes) */ type, /** * Defines the related dom event */ event) { this.type = type; this.event = event; } return KeyboardInfo; }()); /** * This class is used to store keyboard related info for the onPreKeyboardObservable event. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable */ var KeyboardInfoPre = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](KeyboardInfoPre, _super); /** * 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 */ function KeyboardInfoPre( /** * Defines the type of event (KeyboardEventTypes) */ type, /** * Defines the related dom event */ event) { var _this = _super.call(this, type, event) || this; _this.type = type; _this.event = event; _this.skipOnPointerObservable = false; return _this; } return KeyboardInfoPre; }(KeyboardInfo)); /***/ }), /***/ "./Events/pointerEvents.ts": /*!*********************************!*\ !*** ./Events/pointerEvents.ts ***! \*********************************/ /*! exports provided: PointerEventTypes, PointerInfoBase, PointerInfoPre, PointerInfo */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerEventTypes", function() { return PointerEventTypes; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerInfoBase", function() { return PointerInfoBase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerInfoPre", function() { return PointerInfoPre; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerInfo", function() { return PointerInfo; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /** * Gather the list of pointer event types as constants. */ var PointerEventTypes = /** @class */ (function () { function PointerEventTypes() { } /** * The pointerdown event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer. */ PointerEventTypes.POINTERDOWN = 0x01; /** * The pointerup event is fired when a pointer is no longer active. */ PointerEventTypes.POINTERUP = 0x02; /** * The pointermove event is fired when a pointer changes coordinates. */ PointerEventTypes.POINTERMOVE = 0x04; /** * The pointerwheel event is fired when a mouse wheel has been rotated. */ PointerEventTypes.POINTERWHEEL = 0x08; /** * The pointerpick event is fired when a mesh or sprite has been picked by the pointer. */ PointerEventTypes.POINTERPICK = 0x10; /** * The pointertap event is fired when a the object has been touched and released without drag. */ PointerEventTypes.POINTERTAP = 0x20; /** * The pointerdoubletap event is fired when a the object has been touched and released twice without drag. */ PointerEventTypes.POINTERDOUBLETAP = 0x40; return PointerEventTypes; }()); /** * Base class of pointer info types. */ var PointerInfoBase = /** @class */ (function () { /** * Instantiates the base class of pointers info. * @param type Defines the type of event (PointerEventTypes) * @param event Defines the related dom event */ function PointerInfoBase( /** * Defines the type of event (PointerEventTypes) */ type, /** * Defines the related dom event */ event) { this.type = type; this.event = event; } return PointerInfoBase; }()); /** * This class is used to store pointer related info for the onPrePointerObservable event. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable */ var PointerInfoPre = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PointerInfoPre, _super); /** * 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 */ function PointerInfoPre(type, event, localX, localY) { var _this = _super.call(this, type, event) || this; /** * Ray from a pointer if availible (eg. 6dof controller) */ _this.ray = null; _this.skipOnPointerObservable = false; _this.localPosition = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector2"](localX, localY); return _this; } return PointerInfoPre; }(PointerInfoBase)); /** * This type contains all the data related to a pointer event in Babylon.js. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class. */ var PointerInfo = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PointerInfo, _super); /** * 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)\ */ function PointerInfo(type, event, /** * Defines the picking info associated to the info (if any)\ */ pickInfo) { var _this = _super.call(this, type, event) || this; _this.pickInfo = pickInfo; return _this; } return PointerInfo; }(PointerInfoBase)); /***/ }), /***/ "./Gamepads/Controllers/daydreamController.ts": /*!****************************************************!*\ !*** ./Gamepads/Controllers/daydreamController.ts ***! \****************************************************/ /*! exports provided: DaydreamController */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DaydreamController", function() { return DaydreamController; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Loading/sceneLoader */ "./Loading/sceneLoader.ts"); /* harmony import */ var _webVRController__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./webVRController */ "./Gamepads/Controllers/webVRController.ts"); /* harmony import */ var _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts"); /** * Google Daydream controller */ var DaydreamController = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DaydreamController, _super); /** * Creates a new DaydreamController from a gamepad * @param vrGamepad the gamepad that the controller should be created from */ function DaydreamController(vrGamepad) { var _this = _super.call(this, vrGamepad) || this; _this.controllerType = _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__["PoseEnabledControllerType"].DAYDREAM; return _this; } /** * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful. * @param scene scene in which to add meshes * @param meshLoaded optional callback function that will be called if the mesh loads successfully. */ DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) { var _this = this; _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_2__["SceneLoader"].ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) { _this._defaultModel = newMeshes[1]; _this.attachToMesh(_this._defaultModel); if (meshLoaded) { meshLoaded(_this._defaultModel); } }); }; /** * Called once for each button that changed state since the last frame * @param buttonIdx Which button index changed * @param state New state of the button * @param changes Which properties on the state changed since last frame */ DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) { // Daydream controller only has 1 GamepadButton (on the trackpad). if (buttonIdx === 0) { var observable = this.onTriggerStateChangedObservable; if (observable) { observable.notifyObservers(state); } } else { // If the app or home buttons are ever made available _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Unrecognized Daydream button index: " + buttonIdx); } }; /** * Base Url for the controller model. */ DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/'; /** * File name for the controller model. */ DaydreamController.MODEL_FILENAME = 'generic.babylon'; /** * Gamepad Id prefix used to identify Daydream Controller. */ DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller' return DaydreamController; }(_webVRController__WEBPACK_IMPORTED_MODULE_3__["WebVRController"])); _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__["PoseEnabledControllerHelper"]._ControllerFactories.push({ canCreate: function (gamepadInfo) { return gamepadInfo.id.indexOf(DaydreamController.GAMEPAD_ID_PREFIX) === 0; }, create: function (gamepadInfo) { return new DaydreamController(gamepadInfo); } }); /***/ }), /***/ "./Gamepads/Controllers/gearVRController.ts": /*!**************************************************!*\ !*** ./Gamepads/Controllers/gearVRController.ts ***! \**************************************************/ /*! exports provided: GearVRController */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GearVRController", function() { return GearVRController; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Meshes/mesh */ "./Meshes/mesh.ts"); /* harmony import */ var _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Loading/sceneLoader */ "./Loading/sceneLoader.ts"); /* harmony import */ var _webVRController__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./webVRController */ "./Gamepads/Controllers/webVRController.ts"); /* harmony import */ var _poseEnabledController__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts"); /** * Gear VR Controller */ var GearVRController = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GearVRController, _super); /** * Creates a new GearVRController from a gamepad * @param vrGamepad the gamepad that the controller should be created from */ function GearVRController(vrGamepad) { var _this = _super.call(this, vrGamepad) || this; _this._buttonIndexToObservableNameMap = [ 'onPadStateChangedObservable', 'onTriggerStateChangedObservable' // Trigger ]; _this.controllerType = _poseEnabledController__WEBPACK_IMPORTED_MODULE_5__["PoseEnabledControllerType"].GEAR_VR; // Initial starting position defaults to where hand would be (incase of only 3dof controller) _this._calculatedPosition = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25); _this._disableTrackPosition(_this._calculatedPosition); return _this; } /** * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful. * @param scene scene in which to add meshes * @param meshLoaded optional callback function that will be called if the mesh loads successfully. */ GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) { var _this = this; _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_3__["SceneLoader"].ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) { // Offset the controller so it will rotate around the users wrist var mesh = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_2__["Mesh"]("", scene); newMeshes[1].parent = mesh; newMeshes[1].position.z = -0.15; _this._defaultModel = mesh; _this.attachToMesh(_this._defaultModel); if (meshLoaded) { meshLoaded(_this._defaultModel); } }); }; /** * Called once for each button that changed state since the last frame * @param buttonIdx Which button index changed * @param state New state of the button * @param changes Which properties on the state changed since last frame */ GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) { if (buttonIdx < this._buttonIndexToObservableNameMap.length) { var observableName = this._buttonIndexToObservableNameMap[buttonIdx]; // Only emit events for buttons that we know how to map from index to observable var observable = this[observableName]; if (observable) { observable.notifyObservers(state); } } }; /** * Base Url for the controller model. */ GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/'; /** * File name for the controller model. */ GearVRController.MODEL_FILENAME = 'generic.babylon'; /** * Gamepad Id prefix used to identify this controller. */ GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller' return GearVRController; }(_webVRController__WEBPACK_IMPORTED_MODULE_4__["WebVRController"])); _poseEnabledController__WEBPACK_IMPORTED_MODULE_5__["PoseEnabledControllerHelper"]._ControllerFactories.push({ canCreate: function (gamepadInfo) { return gamepadInfo.id.indexOf(GearVRController.GAMEPAD_ID_PREFIX) === 0 || gamepadInfo.id.indexOf('Oculus Go') !== -1; }, create: function (gamepadInfo) { return new GearVRController(gamepadInfo); } }); /***/ }), /***/ "./Gamepads/Controllers/genericController.ts": /*!***************************************************!*\ !*** ./Gamepads/Controllers/genericController.ts ***! \***************************************************/ /*! exports provided: GenericController */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GenericController", function() { return GenericController; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Loading/sceneLoader */ "./Loading/sceneLoader.ts"); /* harmony import */ var _webVRController__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./webVRController */ "./Gamepads/Controllers/webVRController.ts"); /* harmony import */ var _poseEnabledController__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts"); /** * Generic Controller */ var GenericController = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GenericController, _super); /** * Creates a new GenericController from a gamepad * @param vrGamepad the gamepad that the controller should be created from */ function GenericController(vrGamepad) { return _super.call(this, vrGamepad) || this; } /** * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful. * @param scene scene in which to add meshes * @param meshLoaded optional callback function that will be called if the mesh loads successfully. */ GenericController.prototype.initControllerMesh = function (scene, meshLoaded) { var _this = this; _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_1__["SceneLoader"].ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) { _this._defaultModel = newMeshes[1]; _this.attachToMesh(_this._defaultModel); if (meshLoaded) { meshLoaded(_this._defaultModel); } }); }; /** * Called once for each button that changed state since the last frame * @param buttonIdx Which button index changed * @param state New state of the button * @param changes Which properties on the state changed since last frame */ GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) { console.log("Button id: " + buttonIdx + "state: "); console.dir(state); }; /** * Base Url for the controller model. */ GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/'; /** * File name for the controller model. */ GenericController.MODEL_FILENAME = 'generic.babylon'; return GenericController; }(_webVRController__WEBPACK_IMPORTED_MODULE_2__["WebVRController"])); _poseEnabledController__WEBPACK_IMPORTED_MODULE_3__["PoseEnabledControllerHelper"]._DefaultControllerFactory = function (gamepadInfo) { return new GenericController(gamepadInfo); }; /***/ }), /***/ "./Gamepads/Controllers/index.ts": /*!***************************************!*\ !*** ./Gamepads/Controllers/index.ts ***! \***************************************/ /*! exports provided: DaydreamController, GearVRController, GenericController, OculusTouchController, PoseEnabledControllerType, PoseEnabledControllerHelper, PoseEnabledController, ViveController, WebVRController, WindowsMotionController */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _daydreamController__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./daydreamController */ "./Gamepads/Controllers/daydreamController.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DaydreamController", function() { return _daydreamController__WEBPACK_IMPORTED_MODULE_0__["DaydreamController"]; }); /* harmony import */ var _gearVRController__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./gearVRController */ "./Gamepads/Controllers/gearVRController.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GearVRController", function() { return _gearVRController__WEBPACK_IMPORTED_MODULE_1__["GearVRController"]; }); /* harmony import */ var _genericController__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./genericController */ "./Gamepads/Controllers/genericController.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GenericController", function() { return _genericController__WEBPACK_IMPORTED_MODULE_2__["GenericController"]; }); /* harmony import */ var _oculusTouchController__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./oculusTouchController */ "./Gamepads/Controllers/oculusTouchController.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OculusTouchController", function() { return _oculusTouchController__WEBPACK_IMPORTED_MODULE_3__["OculusTouchController"]; }); /* harmony import */ var _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledControllerType", function() { return _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__["PoseEnabledControllerType"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledControllerHelper", function() { return _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__["PoseEnabledControllerHelper"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledController", function() { return _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__["PoseEnabledController"]; }); /* harmony import */ var _viveController__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./viveController */ "./Gamepads/Controllers/viveController.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ViveController", function() { return _viveController__WEBPACK_IMPORTED_MODULE_5__["ViveController"]; }); /* harmony import */ var _webVRController__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./webVRController */ "./Gamepads/Controllers/webVRController.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebVRController", function() { return _webVRController__WEBPACK_IMPORTED_MODULE_6__["WebVRController"]; }); /* harmony import */ var _windowsMotionController__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./windowsMotionController */ "./Gamepads/Controllers/windowsMotionController.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WindowsMotionController", function() { return _windowsMotionController__WEBPACK_IMPORTED_MODULE_7__["WindowsMotionController"]; }); /***/ }), /***/ "./Gamepads/Controllers/oculusTouchController.ts": /*!*******************************************************!*\ !*** ./Gamepads/Controllers/oculusTouchController.ts ***! \*******************************************************/ /*! exports provided: OculusTouchController */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OculusTouchController", function() { return OculusTouchController; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Loading/sceneLoader */ "./Loading/sceneLoader.ts"); /* harmony import */ var _webVRController__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./webVRController */ "./Gamepads/Controllers/webVRController.ts"); /* harmony import */ var _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts"); /** * Oculus Touch Controller */ var OculusTouchController = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](OculusTouchController, _super); /** * Creates a new OculusTouchController from a gamepad * @param vrGamepad the gamepad that the controller should be created from */ function OculusTouchController(vrGamepad) { var _this = _super.call(this, vrGamepad) || this; /** * Fired when the secondary trigger on this controller is modified */ _this.onSecondaryTriggerStateChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Fired when the thumb rest on this controller is modified */ _this.onThumbRestChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); _this.controllerType = _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__["PoseEnabledControllerType"].OCULUS; return _this; } /** * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful. * @param scene scene in which to add meshes * @param meshLoaded optional callback function that will be called if the mesh loads successfully. */ OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) { var _this = this; var meshName; // Hand if (this.hand === 'left') { meshName = OculusTouchController.MODEL_LEFT_FILENAME; } else { // Right is the default if no hand is specified meshName = OculusTouchController.MODEL_RIGHT_FILENAME; } _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_2__["SceneLoader"].ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) { /* Parent Mesh name: oculus_touch_left - body - trigger - thumbstick - grip - button_y - button_x - button_enter */ _this._defaultModel = newMeshes[1]; _this.attachToMesh(_this._defaultModel); if (meshLoaded) { meshLoaded(_this._defaultModel); } }); }; Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", { /** * Fired when the A button on this controller is modified */ get: function () { if (this.hand === 'right') { return this.onMainButtonStateChangedObservable; } else { throw new Error('No A button on left hand'); } }, enumerable: true, configurable: true }); Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", { /** * Fired when the B button on this controller is modified */ get: function () { if (this.hand === 'right') { return this.onSecondaryButtonStateChangedObservable; } else { throw new Error('No B button on left hand'); } }, enumerable: true, configurable: true }); Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", { /** * Fired when the X button on this controller is modified */ get: function () { if (this.hand === 'left') { return this.onMainButtonStateChangedObservable; } else { throw new Error('No X button on right hand'); } }, enumerable: true, configurable: true }); Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", { /** * Fired when the Y button on this controller is modified */ get: function () { if (this.hand === 'left') { return this.onSecondaryButtonStateChangedObservable; } else { throw new Error('No Y button on right hand'); } }, enumerable: true, configurable: true }); /** * Called once for each button that changed state since the last frame * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1) * 2) secondary trigger (same) * 3) A (right) X (left), touch, pressed = value * 4) B / Y * 5) thumb rest * @param buttonIdx Which button index changed * @param state New state of the button * @param changes Which properties on the state changed since last frame */ OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) { var notifyObject = state; //{ state: state, changes: changes }; var triggerDirection = this.hand === 'right' ? -1 : 1; switch (buttonIdx) { case 0: this.onPadStateChangedObservable.notifyObservers(notifyObject); return; case 1: // index trigger if (this._defaultModel) { (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20; (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005; (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005; } this.onTriggerStateChangedObservable.notifyObservers(notifyObject); return; case 2: // secondary trigger if (this._defaultModel) { (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035; } this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject); return; case 3: if (this._defaultModel) { if (notifyObject.pressed) { (this._defaultModel.getChildren()[1]).position.y = -0.001; } else { (this._defaultModel.getChildren()[1]).position.y = 0; } } this.onMainButtonStateChangedObservable.notifyObservers(notifyObject); return; case 4: if (this._defaultModel) { if (notifyObject.pressed) { (this._defaultModel.getChildren()[2]).position.y = -0.001; } else { (this._defaultModel.getChildren()[2]).position.y = 0; } } this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject); return; case 5: this.onThumbRestChangedObservable.notifyObservers(notifyObject); return; } }; /** * Base Url for the controller model. */ OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/'; /** * File name for the left controller model. */ OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon'; /** * File name for the right controller model. */ OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon'; return OculusTouchController; }(_webVRController__WEBPACK_IMPORTED_MODULE_3__["WebVRController"])); _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__["PoseEnabledControllerHelper"]._ControllerFactories.push({ canCreate: function (gamepadInfo) { return gamepadInfo.id.indexOf('Oculus Touch') !== -1; }, create: function (gamepadInfo) { return new OculusTouchController(gamepadInfo); } }); /***/ }), /***/ "./Gamepads/Controllers/poseEnabledController.ts": /*!*******************************************************!*\ !*** ./Gamepads/Controllers/poseEnabledController.ts ***! \*******************************************************/ /*! exports provided: PoseEnabledControllerType, PoseEnabledControllerHelper, PoseEnabledController */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledControllerType", function() { return PoseEnabledControllerType; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledControllerHelper", function() { return PoseEnabledControllerHelper; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledController", function() { return PoseEnabledController; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Culling_ray__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Culling/ray */ "./Culling/ray.ts"); /* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Engines/engineStore */ "./Engines/engineStore.ts"); /* harmony import */ var _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Gamepads/gamepad */ "./Gamepads/gamepad.ts"); /** * Defines the types of pose enabled controllers that are supported */ var PoseEnabledControllerType; (function (PoseEnabledControllerType) { /** * HTC Vive */ PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE"; /** * Oculus Rift */ PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS"; /** * Windows mixed reality */ PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS"; /** * Samsung gear VR */ PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR"; /** * Google Daydream */ PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM"; /** * Generic */ PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC"; })(PoseEnabledControllerType || (PoseEnabledControllerType = {})); /** * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller) */ var PoseEnabledControllerHelper = /** @class */ (function () { function PoseEnabledControllerHelper() { } /** * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller) * @param vrGamepad the gamepad to initialized * @returns a vr controller of the type the gamepad identified as */ PoseEnabledControllerHelper.InitiateController = function (vrGamepad) { for (var _i = 0, _a = this._ControllerFactories; _i < _a.length; _i++) { var factory = _a[_i]; if (factory.canCreate(vrGamepad)) { return factory.create(vrGamepad); } } if (this._DefaultControllerFactory) { return this._DefaultControllerFactory(vrGamepad); } throw "The type of gamepad you are trying to load needs to be imported first or is not supported."; }; /** @hidden */ PoseEnabledControllerHelper._ControllerFactories = []; /** @hidden */ PoseEnabledControllerHelper._DefaultControllerFactory = null; return PoseEnabledControllerHelper; }()); /** * Defines the PoseEnabledController object that contains state of a vr capable controller */ var PoseEnabledController = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PoseEnabledController, _super); /** * Creates a new PoseEnabledController from a gamepad * @param browserGamepad the gamepad that the PoseEnabledController should be created from */ function PoseEnabledController(browserGamepad) { var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this; // Represents device position and rotation in room space. Should only be used to help calculate babylon space values _this._deviceRoomPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); _this._deviceRoomRotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"](); /** * The device position in babylon space */ _this.devicePosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); /** * The device rotation in babylon space */ _this.deviceRotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"](); /** * The scale factor of the device in babylon space */ _this.deviceScaleFactor = 1; // Used to convert 6dof controllers to 3dof _this._trackPosition = true; _this._maxRotationDistFromHeadset = Math.PI / 5; _this._draggedRoomRotation = 0; _this._leftHandSystemQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"](); /** * Internal, matrix used to convert room space to babylon space * @hidden */ _this._deviceToWorld = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Identity(); /** * Node to be used when casting a ray from the controller * @hidden */ _this._pointingPoseNode = null; _this._workingMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Identity(); /** * @hidden */ _this._meshAttachedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); _this.type = _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_5__["Gamepad"].POSE_ENABLED; _this.controllerType = PoseEnabledControllerType.GENERIC; _this.position = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); _this.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"](); _this._calculatedPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); _this._calculatedRotation = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"](); _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"].RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion); return _this; } /** * @hidden */ PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) { if (this._trackPosition) { this._calculatedPosition.copyFrom(fixedPosition); this._trackPosition = false; } }; /** * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller */ PoseEnabledController.prototype.update = function () { _super.prototype.update.call(this); this._updatePoseAndMesh(); }; /** * Updates only the pose device and mesh without doing any button event checking */ PoseEnabledController.prototype._updatePoseAndMesh = function () { var pose = this.browserGamepad.pose; this.updateFromDevice(pose); if (!this._trackPosition && _Engines_engineStore__WEBPACK_IMPORTED_MODULE_4__["EngineStore"].LastCreatedScene && _Engines_engineStore__WEBPACK_IMPORTED_MODULE_4__["EngineStore"].LastCreatedScene.activeCamera && _Engines_engineStore__WEBPACK_IMPORTED_MODULE_4__["EngineStore"].LastCreatedScene.activeCamera.devicePosition) { var camera = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_4__["EngineStore"].LastCreatedScene.activeCamera; camera._computeDevicePosition(); this._deviceToWorld.setTranslation(camera.devicePosition); if (camera.deviceRotationQuaternion) { var camera = camera; camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Tmp"].Vector3[0]); // Find the radian distance away that the headset is from the controllers rotation var distanceAway = Math.atan2(Math.sin(_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Tmp"].Vector3[0].y - this._draggedRoomRotation), Math.cos(_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Tmp"].Vector3[0].y - this._draggedRoomRotation)); if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) { // Only rotate enouph to be within the _maxRotationDistFromHeadset var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset); this._draggedRoomRotation += rotationAmount; // Rotate controller around headset var sin = Math.sin(-rotationAmount); var cos = Math.cos(-rotationAmount); this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin; this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos; } } } _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition); this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix); _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"].FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion); this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation); if (this._mesh) { this._mesh.position.copyFrom(this.devicePosition); if (this._mesh.rotationQuaternion) { this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion); } } }; /** * Updates the state of the pose enbaled controller based on the raw pose data from the device * @param poseData raw pose fromthe device */ PoseEnabledController.prototype.updateFromDevice = function (poseData) { if (poseData) { this.rawPose = poseData; if (poseData.position) { this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]); if (this._mesh && this._mesh.getScene().useRightHandedSystem) { this._deviceRoomPosition.z *= -1; } if (this._trackPosition) { this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition); } this._calculatedPosition.addInPlace(this.position); } var pose = this.rawPose; if (poseData.orientation && pose.orientation) { this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]); if (this._mesh) { if (this._mesh.getScene().useRightHandedSystem) { this._deviceRoomRotationQuaternion.z *= -1; this._deviceRoomRotationQuaternion.w *= -1; } else { this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion); } } // if the camera is set, rotate to the camera's rotation this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation); } } }; /** * Attaches a mesh to the controller * @param mesh the mesh to be attached */ PoseEnabledController.prototype.attachToMesh = function (mesh) { if (this._mesh) { this._mesh.parent = null; } this._mesh = mesh; if (this._poseControlledCamera) { this._mesh.parent = this._poseControlledCamera; } if (!this._mesh.rotationQuaternion) { this._mesh.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"](); } // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh this._updatePoseAndMesh(); if (this._pointingPoseNode) { var parents = []; var obj = this._pointingPoseNode; while (obj.parent) { parents.push(obj.parent); obj = obj.parent; } parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); }); } this._meshAttachedObservable.notifyObservers(mesh); }; /** * Attaches the controllers mesh to a camera * @param camera the camera the mesh should be attached to */ PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) { this._poseControlledCamera = camera; if (this._mesh) { this._mesh.parent = this._poseControlledCamera; } }; /** * Disposes of the controller */ PoseEnabledController.prototype.dispose = function () { if (this._mesh) { this._mesh.dispose(); } this._mesh = null; _super.prototype.dispose.call(this); }; Object.defineProperty(PoseEnabledController.prototype, "mesh", { /** * The mesh that is attached to the controller */ get: function () { return this._mesh; }, enumerable: true, configurable: true }); /** * Gets the ray of the controller in the direction the controller is pointing * @param length the length the resulting ray should be * @returns a ray in the direction the controller is pointing */ PoseEnabledController.prototype.getForwardRay = function (length) { if (length === void 0) { length = 100; } if (!this.mesh) { return new _Culling_ray__WEBPACK_IMPORTED_MODULE_3__["Ray"](_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0, 0, 1), length); } var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix(); var origin = m.getTranslation(); var forward = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0, 0, -1); var forwardWorld = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformNormal(forward, m); var direction = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Normalize(forwardWorld); return new _Culling_ray__WEBPACK_IMPORTED_MODULE_3__["Ray"](origin, direction, length); }; /** * Name of the child mesh that can be used to cast a ray from the controller */ PoseEnabledController.POINTING_POSE = "POINTING_POSE"; return PoseEnabledController; }(_Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_5__["Gamepad"])); /***/ }), /***/ "./Gamepads/Controllers/viveController.ts": /*!************************************************!*\ !*** ./Gamepads/Controllers/viveController.ts ***! \************************************************/ /*! exports provided: ViveController */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ViveController", function() { return ViveController; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Loading/sceneLoader */ "./Loading/sceneLoader.ts"); /* harmony import */ var _webVRController__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./webVRController */ "./Gamepads/Controllers/webVRController.ts"); /* harmony import */ var _poseEnabledController__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts"); /** * Vive Controller */ var ViveController = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ViveController, _super); /** * Creates a new ViveController from a gamepad * @param vrGamepad the gamepad that the controller should be created from */ function ViveController(vrGamepad) { var _this = _super.call(this, vrGamepad) || this; _this.controllerType = _poseEnabledController__WEBPACK_IMPORTED_MODULE_3__["PoseEnabledControllerType"].VIVE; _this._invertLeftStickY = true; return _this; } /** * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful. * @param scene scene in which to add meshes * @param meshLoaded optional callback function that will be called if the mesh loads successfully. */ ViveController.prototype.initControllerMesh = function (scene, meshLoaded) { var _this = this; _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_1__["SceneLoader"].ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) { /* Parent Mesh name: ViveWand - body - r_gripper - l_gripper - menu_button - system_button - trackpad - trigger - LED */ _this._defaultModel = newMeshes[1]; _this.attachToMesh(_this._defaultModel); if (meshLoaded) { meshLoaded(_this._defaultModel); } }); }; Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", { /** * Fired when the left button on this controller is modified */ get: function () { return this.onMainButtonStateChangedObservable; }, enumerable: true, configurable: true }); Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", { /** * Fired when the right button on this controller is modified */ get: function () { return this.onMainButtonStateChangedObservable; }, enumerable: true, configurable: true }); Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", { /** * Fired when the menu button on this controller is modified */ get: function () { return this.onSecondaryButtonStateChangedObservable; }, enumerable: true, configurable: true }); /** * Called once for each button that changed state since the last frame * Vive mapping: * 0: touchpad * 1: trigger * 2: left AND right buttons * 3: menu button * @param buttonIdx Which button index changed * @param state New state of the button * @param changes Which properties on the state changed since last frame */ ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) { var notifyObject = state; //{ state: state, changes: changes }; switch (buttonIdx) { case 0: this.onPadStateChangedObservable.notifyObservers(notifyObject); return; case 1: // index trigger if (this._defaultModel) { (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15; } this.onTriggerStateChangedObservable.notifyObservers(notifyObject); return; case 2: // left AND right button this.onMainButtonStateChangedObservable.notifyObservers(notifyObject); return; case 3: if (this._defaultModel) { if (notifyObject.pressed) { (this._defaultModel.getChildren()[2]).position.y = -0.001; } else { (this._defaultModel.getChildren()[2]).position.y = 0; } } this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject); return; } }; /** * Base Url for the controller model. */ ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/'; /** * File name for the controller model. */ ViveController.MODEL_FILENAME = 'wand.babylon'; return ViveController; }(_webVRController__WEBPACK_IMPORTED_MODULE_2__["WebVRController"])); _poseEnabledController__WEBPACK_IMPORTED_MODULE_3__["PoseEnabledControllerHelper"]._ControllerFactories.push({ canCreate: function (gamepadInfo) { return gamepadInfo.id.toLowerCase().indexOf('openvr') !== -1; }, create: function (gamepadInfo) { return new ViveController(gamepadInfo); } }); /***/ }), /***/ "./Gamepads/Controllers/webVRController.ts": /*!*************************************************!*\ !*** ./Gamepads/Controllers/webVRController.ts ***! \*************************************************/ /*! exports provided: WebVRController */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebVRController", function() { return WebVRController; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _poseEnabledController__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts"); /** * Defines the WebVRController object that represents controllers tracked in 3D space */ var WebVRController = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](WebVRController, _super); /** * Creates a new WebVRController from a gamepad * @param vrGamepad the gamepad that the WebVRController should be created from */ function WebVRController(vrGamepad) { var _this = _super.call(this, vrGamepad) || this; // Observables /** * Fired when the trigger state has changed */ _this.onTriggerStateChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Fired when the main button state has changed */ _this.onMainButtonStateChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Fired when the secondary button state has changed */ _this.onSecondaryButtonStateChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Fired when the pad state has changed */ _this.onPadStateChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Fired when controllers stick values have changed */ _this.onPadValuesChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * X and Y axis corrisponding to the controllers joystick */ _this.pad = { x: 0, y: 0 }; // avoid GC, store state in a tmp object _this._changes = { pressChanged: false, touchChanged: false, valueChanged: false, changed: false }; _this._buttons = new Array(vrGamepad.buttons.length); _this.hand = vrGamepad.hand; return _this; } /** * Fired when a controller button's state has changed * @param callback the callback containing the button that was modified */ WebVRController.prototype.onButtonStateChange = function (callback) { this._onButtonStateChange = callback; }; Object.defineProperty(WebVRController.prototype, "defaultModel", { /** * The default controller model for the controller */ get: function () { return this._defaultModel; }, enumerable: true, configurable: true }); /** * Updates the state of the controller and mesh based on the current position and rotation of the controller */ WebVRController.prototype.update = function () { _super.prototype.update.call(this); for (var index = 0; index < this._buttons.length; index++) { this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index); } if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) { this.pad.x = this.leftStick.x; this.pad.y = this.leftStick.y; this.onPadValuesChangedObservable.notifyObservers(this.pad); } }; WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) { if (!newState) { newState = { pressed: false, touched: false, value: 0 }; } if (!currentState) { this._buttons[buttonIndex] = { pressed: newState.pressed, touched: newState.touched, value: newState.value }; return; } this._checkChanges(newState, currentState); if (this._changes.changed) { this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState); this._handleButtonChange(buttonIndex, newState, this._changes); } this._buttons[buttonIndex].pressed = newState.pressed; this._buttons[buttonIndex].touched = newState.touched; // oculus triggers are never 0, thou not touched. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value; }; WebVRController.prototype._checkChanges = function (newState, currentState) { this._changes.pressChanged = newState.pressed !== currentState.pressed; this._changes.touchChanged = newState.touched !== currentState.touched; this._changes.valueChanged = newState.value !== currentState.value; this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged; return this._changes; }; /** * Disposes of th webVRCOntroller */ WebVRController.prototype.dispose = function () { _super.prototype.dispose.call(this); this.onTriggerStateChangedObservable.clear(); this.onMainButtonStateChangedObservable.clear(); this.onSecondaryButtonStateChangedObservable.clear(); this.onPadStateChangedObservable.clear(); this.onPadValuesChangedObservable.clear(); }; return WebVRController; }(_poseEnabledController__WEBPACK_IMPORTED_MODULE_2__["PoseEnabledController"])); /***/ }), /***/ "./Gamepads/Controllers/windowsMotionController.ts": /*!*********************************************************!*\ !*** ./Gamepads/Controllers/windowsMotionController.ts ***! \*********************************************************/ /*! exports provided: WindowsMotionController */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WindowsMotionController", function() { return WindowsMotionController; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Meshes/mesh */ "./Meshes/mesh.ts"); /* harmony import */ var _Culling_ray__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Culling/ray */ "./Culling/ray.ts"); /* harmony import */ var _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Loading/sceneLoader */ "./Loading/sceneLoader.ts"); /* harmony import */ var _webVRController__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./webVRController */ "./Gamepads/Controllers/webVRController.ts"); /* harmony import */ var _genericController__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./genericController */ "./Gamepads/Controllers/genericController.ts"); /* harmony import */ var _poseEnabledController__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts"); /** * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh */ var LoadedMeshInfo = /** @class */ (function () { function LoadedMeshInfo() { /** * Map of the button meshes contained in the controller */ this.buttonMeshes = {}; /** * Map of the axis meshes contained in the controller */ this.axisMeshes = {}; } return LoadedMeshInfo; }()); /** * Defines the WindowsMotionController object that the state of the windows motion controller */ var WindowsMotionController = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](WindowsMotionController, _super); /** * Creates a new WindowsMotionController from a gamepad * @param vrGamepad the gamepad that the controller should be created from */ function WindowsMotionController(vrGamepad) { var _this = _super.call(this, vrGamepad) || this; _this._mapping = { // Semantic button names buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'], // A mapping of the button name to glTF model node name // that should be transformed by button value. buttonMeshNames: { 'trigger': 'SELECT', 'menu': 'MENU', 'grip': 'GRASP', 'thumbstick': 'THUMBSTICK_PRESS', 'trackpad': 'TOUCHPAD_PRESS' }, // This mapping is used to translate from the Motion Controller to Babylon semantics buttonObservableNames: { 'trigger': 'onTriggerStateChangedObservable', 'menu': 'onSecondaryButtonStateChangedObservable', 'grip': 'onMainButtonStateChangedObservable', 'thumbstick': 'onPadStateChangedObservable', 'trackpad': 'onTrackpadChangedObservable' }, // A mapping of the axis name to glTF model node name // that should be transformed by axis value. // This array mirrors the browserGamepad.axes array, such that // the mesh corresponding to axis 0 is in this array index 0. axisMeshNames: [ 'THUMBSTICK_X', 'THUMBSTICK_Y', 'TOUCHPAD_TOUCH_X', 'TOUCHPAD_TOUCH_Y' ], pointingPoseMeshName: _poseEnabledController__WEBPACK_IMPORTED_MODULE_9__["PoseEnabledController"].POINTING_POSE }; /** * Fired when the trackpad on this controller is clicked */ _this.onTrackpadChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Fired when the trackpad on this controller is modified */ _this.onTrackpadValuesChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * The current x and y values of this controller's trackpad */ _this.trackpad = { x: 0, y: 0 }; _this.controllerType = _poseEnabledController__WEBPACK_IMPORTED_MODULE_9__["PoseEnabledControllerType"].WINDOWS; _this._loadedMeshInfo = null; return _this; } Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", { /** * Fired when the trigger on this controller is modified */ get: function () { return this.onTriggerStateChangedObservable; }, enumerable: true, configurable: true }); Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", { /** * Fired when the menu button on this controller is modified */ get: function () { return this.onSecondaryButtonStateChangedObservable; }, enumerable: true, configurable: true }); Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", { /** * Fired when the grip button on this controller is modified */ get: function () { return this.onMainButtonStateChangedObservable; }, enumerable: true, configurable: true }); Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", { /** * Fired when the thumbstick button on this controller is modified */ get: function () { return this.onPadStateChangedObservable; }, enumerable: true, configurable: true }); Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", { /** * Fired when the touchpad button on this controller is modified */ get: function () { return this.onTrackpadChangedObservable; }, enumerable: true, configurable: true }); Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", { /** * Fired when the touchpad values on this controller are modified */ get: function () { return this.onTrackpadValuesChangedObservable; }, enumerable: true, configurable: true }); WindowsMotionController.prototype._updateTrackpad = function () { if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) { this.trackpad.x = this.browserGamepad["axes"][2]; this.trackpad.y = this.browserGamepad["axes"][3]; this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad); } }; /** * Called once per frame by the engine. */ WindowsMotionController.prototype.update = function () { _super.prototype.update.call(this); if (this.browserGamepad.axes) { this._updateTrackpad(); // Only need to animate axes if there is a loaded mesh if (this._loadedMeshInfo) { for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) { this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]); } } } }; /** * Called once for each button that changed state since the last frame * @param buttonIdx Which button index changed * @param state New state of the button * @param changes Which properties on the state changed since last frame */ WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) { var buttonName = this._mapping.buttons[buttonIdx]; if (!buttonName) { return; } // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames this._updateTrackpad(); // Only emit events for buttons that we know how to map from index to name var observable = this[(this._mapping.buttonObservableNames)[buttonName]]; if (observable) { observable.notifyObservers(state); } this._lerpButtonTransform(buttonName, state.value); }; /** * Moves the buttons on the controller mesh based on their current state * @param buttonName the name of the button to move * @param buttonValue the value of the button which determines the buttons new position */ WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) { // If there is no loaded mesh, there is nothing to transform. if (!this._loadedMeshInfo) { return; } var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName]; if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) { return; } _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion); _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position); }; /** * Moves the axis on the controller mesh based on its current state * @param axis the index of the axis * @param axisValue the value of the axis which determines the meshes new position * @hidden */ WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) { if (!this._loadedMeshInfo) { return; } var meshInfo = this._loadedMeshInfo.axisMeshes[axis]; if (!meshInfo) { return; } if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) { return; } // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1) var lerpValue = axisValue * 0.5 + 0.5; _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion); _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position); }; /** * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful. * @param scene scene in which to add meshes * @param meshLoaded optional callback function that will be called if the mesh loads successfully. */ WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) { var _this = this; if (forceDefault === void 0) { forceDefault = false; } var path; var filename; // Checking if GLB loader is present if (_Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_6__["SceneLoader"].IsPluginForExtensionAvailable(".glb")) { // Determine the device specific folder based on the ID suffix var device = 'default'; if (this.id && !forceDefault) { var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN); device = ((match && match[0]) || device); } // Hand if (this.hand === 'left') { filename = WindowsMotionController.MODEL_LEFT_FILENAME; } else { // Right is the default if no hand is specified filename = WindowsMotionController.MODEL_RIGHT_FILENAME; } path = WindowsMotionController.MODEL_BASE_URL + device + '/'; } else { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models"); path = _genericController__WEBPACK_IMPORTED_MODULE_8__["GenericController"].MODEL_BASE_URL; filename = _genericController__WEBPACK_IMPORTED_MODULE_8__["GenericController"].MODEL_FILENAME; } _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_6__["SceneLoader"].ImportMesh("", path, filename, scene, function (meshes) { // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format. _this._loadedMeshInfo = _this.processModel(scene, meshes); if (!_this._loadedMeshInfo) { return; } _this._defaultModel = _this._loadedMeshInfo.rootNode; _this.attachToMesh(_this._defaultModel); if (meshLoaded) { meshLoaded(_this._defaultModel); } }, null, function (scene, message) { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Log(message); _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn('Failed to retrieve controller model from the remote server: ' + path + filename); if (!forceDefault) { _this.initControllerMesh(scene, meshLoaded, true); } }); }; /** * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that * can be transformed by button presses and axes values, based on this._mapping. * * @param scene scene in which the meshes exist * @param meshes list of meshes that make up the controller model to process * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed. */ WindowsMotionController.prototype.processModel = function (scene, meshes) { var loadedMeshInfo = null; // Create a new mesh to contain the glTF hierarchy var parentMesh = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"](this.id + " " + this.hand, scene); // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh' var childMesh = null; for (var i = 0; i < meshes.length; i++) { var mesh = meshes[i]; if (!mesh.parent) { // Exclude controller meshes from picking results mesh.isPickable = false; // Handle root node, attach to the new parentMesh childMesh = mesh; break; } } if (childMesh) { childMesh.setParent(parentMesh); // Create our mesh info. Note that this method will always return non-null. loadedMeshInfo = this.createMeshInfo(parentMesh); } else { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn('Could not find root node in model file.'); } return loadedMeshInfo; }; WindowsMotionController.prototype.createMeshInfo = function (rootNode) { var loadedMeshInfo = new LoadedMeshInfo(); var i; loadedMeshInfo.rootNode = rootNode; // Reset the caches loadedMeshInfo.buttonMeshes = {}; loadedMeshInfo.axisMeshes = {}; // Button Meshes for (i = 0; i < this._mapping.buttons.length; i++) { var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]]; if (!buttonMeshName) { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]); continue; } var buttonMesh = getChildByName(rootNode, buttonMeshName); if (!buttonMesh) { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn('Missing button mesh with name: ' + buttonMeshName); continue; } var buttonMeshInfo = { index: i, value: getImmediateChildByName(buttonMesh, 'VALUE'), pressed: getImmediateChildByName(buttonMesh, 'PRESSED'), unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED') }; if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) { loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo; } else { // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes. _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn('Missing button submesh under mesh with name: ' + buttonMeshName + '(VALUE: ' + !!buttonMeshInfo.value + ', PRESSED: ' + !!buttonMeshInfo.pressed + ', UNPRESSED:' + !!buttonMeshInfo.unpressed + ')'); } } // Axis Meshes for (i = 0; i < this._mapping.axisMeshNames.length; i++) { var axisMeshName = this._mapping.axisMeshNames[i]; if (!axisMeshName) { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Log('Skipping unknown axis at index: ' + i); continue; } var axisMesh = getChildByName(rootNode, axisMeshName); if (!axisMesh) { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn('Missing axis mesh with name: ' + axisMeshName); continue; } var axisMeshInfo = { index: i, value: getImmediateChildByName(axisMesh, 'VALUE'), min: getImmediateChildByName(axisMesh, 'MIN'), max: getImmediateChildByName(axisMesh, 'MAX') }; if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) { loadedMeshInfo.axisMeshes[i] = axisMeshInfo; } else { // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change. _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn('Missing axis submesh under mesh with name: ' + axisMeshName + '(VALUE: ' + !!axisMeshInfo.value + ', MIN: ' + !!axisMeshInfo.min + ', MAX:' + !!axisMeshInfo.max + ')'); } } // Pointing Ray loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName); if (!loadedMeshInfo.pointingPoseNode) { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName); } else { this._pointingPoseNode = loadedMeshInfo.pointingPoseNode; } return loadedMeshInfo; // Look through all children recursively. This will return null if no mesh exists with the given name. function getChildByName(node, name) { return node.getChildren(function (n) { return n.name === name; }, false)[0]; } // Look through only immediate children. This will return null if no mesh exists with the given name. function getImmediateChildByName(node, name) { return node.getChildren(function (n) { return n.name == name; }, true)[0]; } }; /** * Gets the ray of the controller in the direction the controller is pointing * @param length the length the resulting ray should be * @returns a ray in the direction the controller is pointing */ WindowsMotionController.prototype.getForwardRay = function (length) { if (length === void 0) { length = 100; } if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) { return _super.prototype.getForwardRay.call(this, length); } var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix(); var origin = m.getTranslation(); var forward = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, -1); var forwardWorld = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformNormal(forward, m); var direction = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Normalize(forwardWorld); return new _Culling_ray__WEBPACK_IMPORTED_MODULE_5__["Ray"](origin, direction, length); }; /** * Disposes of the controller */ WindowsMotionController.prototype.dispose = function () { _super.prototype.dispose.call(this); this.onTrackpadChangedObservable.clear(); }; /** * The base url used to load the left and right controller models */ WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/'; /** * The name of the left controller model file */ WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb'; /** * The name of the right controller model file */ WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb'; /** * The controller name prefix for this controller type */ WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) '; /** * The controller id pattern for this controller type */ WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/; return WindowsMotionController; }(_webVRController__WEBPACK_IMPORTED_MODULE_7__["WebVRController"])); _poseEnabledController__WEBPACK_IMPORTED_MODULE_9__["PoseEnabledControllerHelper"]._ControllerFactories.push({ canCreate: function (gamepadInfo) { return gamepadInfo.id.indexOf(WindowsMotionController.GAMEPAD_ID_PREFIX) === 0; }, create: function (gamepadInfo) { return new WindowsMotionController(gamepadInfo); } }); /***/ }), /***/ "./Gamepads/gamepad.ts": /*!*****************************!*\ !*** ./Gamepads/gamepad.ts ***! \*****************************/ /*! exports provided: StickValues, Gamepad, GenericPad */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StickValues", function() { return StickValues; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Gamepad", function() { return Gamepad; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GenericPad", function() { return GenericPad; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /** * Represents a gamepad control stick position */ var StickValues = /** @class */ (function () { /** * Initializes the gamepad x and y control stick values * @param x The x component of the gamepad control stick value * @param y The y component of the gamepad control stick value */ function StickValues( /** * The x component of the control stick */ x, /** * The y component of the control stick */ y) { this.x = x; this.y = y; } return StickValues; }()); /** * Represents a gamepad */ var Gamepad = /** @class */ (function () { /** * Initializes the gamepad * @param id The id of the gamepad * @param index The index of the gamepad * @param browserGamepad The browser gamepad * @param leftStickX The x component of the left joystick * @param leftStickY The y component of the left joystick * @param rightStickX The x component of the right joystick * @param rightStickY The y component of the right joystick */ function Gamepad( /** * The id of the gamepad */ id, /** * The index of the gamepad */ index, /** * The browser gamepad */ browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) { if (leftStickX === void 0) { leftStickX = 0; } if (leftStickY === void 0) { leftStickY = 1; } if (rightStickX === void 0) { rightStickX = 2; } if (rightStickY === void 0) { rightStickY = 3; } this.id = id; this.index = index; this.browserGamepad = browserGamepad; this._leftStick = { x: 0, y: 0 }; this._rightStick = { x: 0, y: 0 }; /** @hidden */ this._isConnected = true; /** * Specifies whether the left control stick should be Y-inverted */ this._invertLeftStickY = false; this.type = Gamepad.GAMEPAD; this._leftStickAxisX = leftStickX; this._leftStickAxisY = leftStickY; this._rightStickAxisX = rightStickX; this._rightStickAxisY = rightStickY; if (this.browserGamepad.axes.length >= 2) { this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] }; } if (this.browserGamepad.axes.length >= 4) { this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] }; } } Object.defineProperty(Gamepad.prototype, "isConnected", { /** * Specifies if the gamepad has been connected */ get: function () { return this._isConnected; }, enumerable: true, configurable: true }); /** * Callback triggered when the left joystick has changed * @param callback */ Gamepad.prototype.onleftstickchanged = function (callback) { this._onleftstickchanged = callback; }; /** * Callback triggered when the right joystick has changed * @param callback */ Gamepad.prototype.onrightstickchanged = function (callback) { this._onrightstickchanged = callback; }; Object.defineProperty(Gamepad.prototype, "leftStick", { /** * Gets the left joystick */ get: function () { return this._leftStick; }, /** * Sets the left joystick values */ set: function (newValues) { if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) { this._onleftstickchanged(newValues); } this._leftStick = newValues; }, enumerable: true, configurable: true }); Object.defineProperty(Gamepad.prototype, "rightStick", { /** * Gets the right joystick */ get: function () { return this._rightStick; }, /** * Sets the right joystick value */ set: function (newValues) { if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) { this._onrightstickchanged(newValues); } this._rightStick = newValues; }, enumerable: true, configurable: true }); /** * Updates the gamepad joystick positions */ Gamepad.prototype.update = function () { if (this._leftStick) { this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] }; if (this._invertLeftStickY) { this.leftStick.y *= -1; } } if (this._rightStick) { this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] }; } }; /** * Disposes the gamepad */ Gamepad.prototype.dispose = function () { }; /** * Represents a gamepad controller */ Gamepad.GAMEPAD = 0; /** * Represents a generic controller */ Gamepad.GENERIC = 1; /** * Represents an XBox controller */ Gamepad.XBOX = 2; /** * Represents a pose-enabled controller */ Gamepad.POSE_ENABLED = 3; return Gamepad; }()); /** * Represents a generic gamepad */ var GenericPad = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GenericPad, _super); /** * Initializes the generic gamepad * @param id The id of the generic gamepad * @param index The index of the generic gamepad * @param browserGamepad The browser gamepad */ function GenericPad(id, index, browserGamepad) { var _this = _super.call(this, id, index, browserGamepad) || this; /** * Observable triggered when a button has been pressed */ _this.onButtonDownObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Observable triggered when a button has been released */ _this.onButtonUpObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); _this.type = Gamepad.GENERIC; _this._buttons = new Array(browserGamepad.buttons.length); return _this; } /** * Callback triggered when a button has been pressed * @param callback Called when a button has been pressed */ GenericPad.prototype.onbuttondown = function (callback) { this._onbuttondown = callback; }; /** * Callback triggered when a button has been released * @param callback Called when a button has been released */ GenericPad.prototype.onbuttonup = function (callback) { this._onbuttonup = callback; }; GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) { if (newValue !== currentValue) { if (newValue === 1) { if (this._onbuttondown) { this._onbuttondown(buttonIndex); } this.onButtonDownObservable.notifyObservers(buttonIndex); } if (newValue === 0) { if (this._onbuttonup) { this._onbuttonup(buttonIndex); } this.onButtonUpObservable.notifyObservers(buttonIndex); } } return newValue; }; /** * Updates the generic gamepad */ GenericPad.prototype.update = function () { _super.prototype.update.call(this); for (var index = 0; index < this._buttons.length; index++) { this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index); } }; /** * Disposes the generic gamepad */ GenericPad.prototype.dispose = function () { _super.prototype.dispose.call(this); this.onButtonDownObservable.clear(); this.onButtonUpObservable.clear(); }; return GenericPad; }(Gamepad)); /***/ }), /***/ "./Gamepads/gamepadManager.ts": /*!************************************!*\ !*** ./Gamepads/gamepadManager.ts ***! \************************************/ /*! exports provided: GamepadManager */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GamepadManager", function() { return GamepadManager; }); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Misc_domManagement__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/domManagement */ "./Misc/domManagement.ts"); /* harmony import */ var _Gamepads_Controllers_poseEnabledController__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Gamepads/Controllers/poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts"); /* harmony import */ var _xboxGamepad__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./xboxGamepad */ "./Gamepads/xboxGamepad.ts"); /* harmony import */ var _gamepad__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./gamepad */ "./Gamepads/gamepad.ts"); /** * Manager for handling gamepads */ var GamepadManager = /** @class */ (function () { /** * Initializes the gamepad manager * @param _scene BabylonJS scene */ function GamepadManager(_scene) { var _this = this; this._scene = _scene; this._babylonGamepads = []; this._oneGamepadConnected = false; /** @hidden */ this._isMonitoring = false; /** * observable to be triggered when the gamepad controller has been disconnected */ this.onGamepadDisconnectedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); if (!_Misc_domManagement__WEBPACK_IMPORTED_MODULE_2__["DomManagement"].IsWindowObjectExist()) { this._gamepadEventSupported = false; } else { this._gamepadEventSupported = 'GamepadEvent' in window; this._gamepadSupport = (navigator.getGamepads || navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads); } this.onGamepadConnectedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](function (observer) { // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected for (var i in _this._babylonGamepads) { var gamepad = _this._babylonGamepads[i]; if (gamepad && gamepad._isConnected) { _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad); } } }); this._onGamepadConnectedEvent = function (evt) { var gamepad = evt.gamepad; if (gamepad.index in _this._babylonGamepads) { if (_this._babylonGamepads[gamepad.index].isConnected) { return; } } var newGamepad; if (_this._babylonGamepads[gamepad.index]) { newGamepad = _this._babylonGamepads[gamepad.index]; newGamepad.browserGamepad = gamepad; newGamepad._isConnected = true; } else { newGamepad = _this._addNewGamepad(gamepad); } _this.onGamepadConnectedObservable.notifyObservers(newGamepad); _this._startMonitoringGamepads(); }; this._onGamepadDisconnectedEvent = function (evt) { var gamepad = evt.gamepad; // Remove the gamepad from the list of gamepads to monitor. for (var i in _this._babylonGamepads) { if (_this._babylonGamepads[i].index === gamepad.index) { var disconnectedGamepad = _this._babylonGamepads[i]; disconnectedGamepad._isConnected = false; _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad); break; } } }; if (this._gamepadSupport) { //first add already-connected gamepads this._updateGamepadObjects(); if (this._babylonGamepads.length) { this._startMonitoringGamepads(); } // Checking if the gamepad connected event is supported (like in Firefox) if (this._gamepadEventSupported) { window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false); window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false); } else { this._startMonitoringGamepads(); } } } Object.defineProperty(GamepadManager.prototype, "gamepads", { /** * The gamepads in the game pad manager */ get: function () { return this._babylonGamepads; }, enumerable: true, configurable: true }); /** * Get the gamepad controllers based on type * @param type The type of gamepad controller * @returns Nullable gamepad */ GamepadManager.prototype.getGamepadByType = function (type) { if (type === void 0) { type = _gamepad__WEBPACK_IMPORTED_MODULE_5__["Gamepad"].XBOX; } for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) { var gamepad = _a[_i]; if (gamepad && gamepad.type === type) { return gamepad; } } return null; }; /** * Disposes the gamepad manager */ GamepadManager.prototype.dispose = function () { if (this._gamepadEventSupported) { if (this._onGamepadConnectedEvent) { window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent); } if (this._onGamepadDisconnectedEvent) { window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent); } this._onGamepadConnectedEvent = null; this._onGamepadDisconnectedEvent = null; } this._babylonGamepads.forEach(function (gamepad) { gamepad.dispose(); }); this.onGamepadConnectedObservable.clear(); this.onGamepadDisconnectedObservable.clear(); this._oneGamepadConnected = false; this._stopMonitoringGamepads(); this._babylonGamepads = []; }; GamepadManager.prototype._addNewGamepad = function (gamepad) { if (!this._oneGamepadConnected) { this._oneGamepadConnected = true; } var newGamepad; var xboxOne = (gamepad.id.search("Xbox One") !== -1); if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) { newGamepad = new _xboxGamepad__WEBPACK_IMPORTED_MODULE_4__["Xbox360Pad"](gamepad.id, gamepad.index, gamepad, xboxOne); } // if pose is supported, use the (WebVR) pose enabled controller else if (gamepad.pose) { newGamepad = _Gamepads_Controllers_poseEnabledController__WEBPACK_IMPORTED_MODULE_3__["PoseEnabledControllerHelper"].InitiateController(gamepad); } else { newGamepad = new _gamepad__WEBPACK_IMPORTED_MODULE_5__["GenericPad"](gamepad.id, gamepad.index, gamepad); } this._babylonGamepads[newGamepad.index] = newGamepad; return newGamepad; }; GamepadManager.prototype._startMonitoringGamepads = function () { if (!this._isMonitoring) { this._isMonitoring = true; //back-comp if (!this._scene) { this._checkGamepadsStatus(); } } }; GamepadManager.prototype._stopMonitoringGamepads = function () { this._isMonitoring = false; }; /** @hidden */ GamepadManager.prototype._checkGamepadsStatus = function () { var _this = this; // Hack to be compatible Chrome this._updateGamepadObjects(); for (var i in this._babylonGamepads) { var gamepad = this._babylonGamepads[i]; if (!gamepad || !gamepad.isConnected) { continue; } gamepad.update(); } if (this._isMonitoring && !this._scene) { _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].QueueNewFrame(function () { _this._checkGamepadsStatus(); }); } }; // This function is called only on Chrome, which does not properly support // connection/disconnection events and forces you to recopy again the gamepad object GamepadManager.prototype._updateGamepadObjects = function () { var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []); for (var i = 0; i < gamepads.length; i++) { var gamepad = gamepads[i]; if (gamepad) { if (!this._babylonGamepads[gamepad.index]) { var newGamepad = this._addNewGamepad(gamepad); this.onGamepadConnectedObservable.notifyObservers(newGamepad); } else { // Forced to copy again this object for Chrome for unknown reason this._babylonGamepads[i].browserGamepad = gamepad; if (!this._babylonGamepads[i].isConnected) { this._babylonGamepads[i]._isConnected = true; this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]); } } } } }; return GamepadManager; }()); /***/ }), /***/ "./Gamepads/gamepadSceneComponent.ts": /*!*******************************************!*\ !*** ./Gamepads/gamepadSceneComponent.ts ***! \*******************************************/ /*! exports provided: GamepadSystemSceneComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GamepadSystemSceneComponent", function() { return GamepadSystemSceneComponent; }); /* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../scene */ "./scene.ts"); /* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../sceneComponent */ "./sceneComponent.ts"); /* harmony import */ var _gamepadManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./gamepadManager */ "./Gamepads/gamepadManager.ts"); /* harmony import */ var _Cameras_freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Cameras/freeCameraInputsManager */ "./Cameras/freeCameraInputsManager.ts"); /* harmony import */ var _Cameras_Inputs_freeCameraGamepadInput__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Cameras/Inputs/freeCameraGamepadInput */ "./Cameras/Inputs/freeCameraGamepadInput.ts"); /* harmony import */ var _Cameras_arcRotateCameraInputsManager__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Cameras/arcRotateCameraInputsManager */ "./Cameras/arcRotateCameraInputsManager.ts"); /* harmony import */ var _Cameras_Inputs_arcRotateCameraGamepadInput__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Cameras/Inputs/arcRotateCameraGamepadInput */ "./Cameras/Inputs/arcRotateCameraGamepadInput.ts"); Object.defineProperty(_scene__WEBPACK_IMPORTED_MODULE_0__["Scene"].prototype, "gamepadManager", { get: function () { if (!this._gamepadManager) { this._gamepadManager = new _gamepadManager__WEBPACK_IMPORTED_MODULE_2__["GamepadManager"](this); var component = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_GAMEPAD); if (!component) { component = new GamepadSystemSceneComponent(this); this._addComponent(component); } } return this._gamepadManager; }, enumerable: true, configurable: true }); /** * Adds a gamepad to the free camera inputs manager */ _Cameras_freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_3__["FreeCameraInputsManager"].prototype.addGamepad = function () { this.add(new _Cameras_Inputs_freeCameraGamepadInput__WEBPACK_IMPORTED_MODULE_4__["FreeCameraGamepadInput"]()); return this; }; /** * Adds a gamepad to the arc rotate camera inputs manager */ _Cameras_arcRotateCameraInputsManager__WEBPACK_IMPORTED_MODULE_5__["ArcRotateCameraInputsManager"].prototype.addGamepad = function () { this.add(new _Cameras_Inputs_arcRotateCameraGamepadInput__WEBPACK_IMPORTED_MODULE_6__["ArcRotateCameraGamepadInput"]()); return this; }; /** * Defines the gamepad scene component responsible to manage gamepads in a given scene */ var GamepadSystemSceneComponent = /** @class */ (function () { /** * Creates a new instance of the component for the given scene * @param scene Defines the scene to register the component in */ function GamepadSystemSceneComponent(scene) { /** * The component name helpfull to identify the component in the list of scene components. */ this.name = _sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_GAMEPAD; this.scene = scene; } /** * Registers the component in a given scene */ GamepadSystemSceneComponent.prototype.register = function () { this.scene._beforeCameraUpdateStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate); }; /** * Rebuilds the elements related to this component in case of * context lost for instance. */ GamepadSystemSceneComponent.prototype.rebuild = function () { // Nothing to do for gamepads }; /** * Disposes the component and the associated ressources */ GamepadSystemSceneComponent.prototype.dispose = function () { var gamepadManager = this.scene._gamepadManager; if (gamepadManager) { gamepadManager.dispose(); this.scene._gamepadManager = null; } }; GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () { var gamepadManager = this.scene._gamepadManager; if (gamepadManager && gamepadManager._isMonitoring) { gamepadManager._checkGamepadsStatus(); } }; return GamepadSystemSceneComponent; }()); /***/ }), /***/ "./Gamepads/index.ts": /*!***************************!*\ !*** ./Gamepads/index.ts ***! \***************************/ /*! exports provided: DaydreamController, GearVRController, GenericController, OculusTouchController, PoseEnabledControllerType, PoseEnabledControllerHelper, PoseEnabledController, ViveController, WebVRController, WindowsMotionController, StickValues, Gamepad, GenericPad, GamepadManager, GamepadSystemSceneComponent, Xbox360Button, Xbox360Dpad, Xbox360Pad */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _Controllers_index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Controllers/index */ "./Gamepads/Controllers/index.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DaydreamController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["DaydreamController"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GearVRController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["GearVRController"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GenericController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["GenericController"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OculusTouchController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["OculusTouchController"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledControllerType", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["PoseEnabledControllerType"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledControllerHelper", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["PoseEnabledControllerHelper"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["PoseEnabledController"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ViveController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["ViveController"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebVRController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["WebVRController"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WindowsMotionController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["WindowsMotionController"]; }); /* harmony import */ var _gamepad__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./gamepad */ "./Gamepads/gamepad.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StickValues", function() { return _gamepad__WEBPACK_IMPORTED_MODULE_1__["StickValues"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Gamepad", function() { return _gamepad__WEBPACK_IMPORTED_MODULE_1__["Gamepad"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GenericPad", function() { return _gamepad__WEBPACK_IMPORTED_MODULE_1__["GenericPad"]; }); /* harmony import */ var _gamepadManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./gamepadManager */ "./Gamepads/gamepadManager.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GamepadManager", function() { return _gamepadManager__WEBPACK_IMPORTED_MODULE_2__["GamepadManager"]; }); /* harmony import */ var _gamepadSceneComponent__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./gamepadSceneComponent */ "./Gamepads/gamepadSceneComponent.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GamepadSystemSceneComponent", function() { return _gamepadSceneComponent__WEBPACK_IMPORTED_MODULE_3__["GamepadSystemSceneComponent"]; }); /* harmony import */ var _xboxGamepad__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./xboxGamepad */ "./Gamepads/xboxGamepad.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Xbox360Button", function() { return _xboxGamepad__WEBPACK_IMPORTED_MODULE_4__["Xbox360Button"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Xbox360Dpad", function() { return _xboxGamepad__WEBPACK_IMPORTED_MODULE_4__["Xbox360Dpad"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Xbox360Pad", function() { return _xboxGamepad__WEBPACK_IMPORTED_MODULE_4__["Xbox360Pad"]; }); /***/ }), /***/ "./Gamepads/xboxGamepad.ts": /*!*********************************!*\ !*** ./Gamepads/xboxGamepad.ts ***! \*********************************/ /*! exports provided: Xbox360Button, Xbox360Dpad, Xbox360Pad */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Xbox360Button", function() { return Xbox360Button; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Xbox360Dpad", function() { return Xbox360Dpad; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Xbox360Pad", function() { return Xbox360Pad; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Gamepads/gamepad */ "./Gamepads/gamepad.ts"); /** * Defines supported buttons for XBox360 compatible gamepads */ var Xbox360Button; (function (Xbox360Button) { /** A */ Xbox360Button[Xbox360Button["A"] = 0] = "A"; /** B */ Xbox360Button[Xbox360Button["B"] = 1] = "B"; /** X */ Xbox360Button[Xbox360Button["X"] = 2] = "X"; /** Y */ Xbox360Button[Xbox360Button["Y"] = 3] = "Y"; /** Start */ Xbox360Button[Xbox360Button["Start"] = 4] = "Start"; /** Back */ Xbox360Button[Xbox360Button["Back"] = 5] = "Back"; /** Left button */ Xbox360Button[Xbox360Button["LB"] = 6] = "LB"; /** Right button */ Xbox360Button[Xbox360Button["RB"] = 7] = "RB"; /** Left stick */ Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick"; /** Right stick */ Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick"; })(Xbox360Button || (Xbox360Button = {})); /** Defines values for XBox360 DPad */ var Xbox360Dpad; (function (Xbox360Dpad) { /** Up */ Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up"; /** Down */ Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down"; /** Left */ Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left"; /** Right */ Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right"; })(Xbox360Dpad || (Xbox360Dpad = {})); /** * Defines a XBox360 gamepad */ var Xbox360Pad = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Xbox360Pad, _super); /** * Creates a new XBox360 gamepad object * @param id defines the id of this gamepad * @param index defines its index * @param gamepad defines the internal HTML gamepad object * @param xboxOne defines if it is a XBox One gamepad */ function Xbox360Pad(id, index, gamepad, xboxOne) { if (xboxOne === void 0) { xboxOne = false; } var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this; _this._leftTrigger = 0; _this._rightTrigger = 0; /** Observable raised when a button is pressed */ _this.onButtonDownObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** Observable raised when a button is released */ _this.onButtonUpObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** Observable raised when a pad is pressed */ _this.onPadDownObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** Observable raised when a pad is released */ _this.onPadUpObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); _this._buttonA = 0; _this._buttonB = 0; _this._buttonX = 0; _this._buttonY = 0; _this._buttonBack = 0; _this._buttonStart = 0; _this._buttonLB = 0; _this._buttonRB = 0; _this._buttonLeftStick = 0; _this._buttonRightStick = 0; _this._dPadUp = 0; _this._dPadDown = 0; _this._dPadLeft = 0; _this._dPadRight = 0; _this._isXboxOnePad = false; _this.type = _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_2__["Gamepad"].XBOX; _this._isXboxOnePad = xboxOne; return _this; } /** * Defines the callback to call when left trigger is pressed * @param callback defines the callback to use */ Xbox360Pad.prototype.onlefttriggerchanged = function (callback) { this._onlefttriggerchanged = callback; }; /** * Defines the callback to call when right trigger is pressed * @param callback defines the callback to use */ Xbox360Pad.prototype.onrighttriggerchanged = function (callback) { this._onrighttriggerchanged = callback; }; Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", { /** * Gets the left trigger value */ get: function () { return this._leftTrigger; }, /** * Sets the left trigger value */ set: function (newValue) { if (this._onlefttriggerchanged && this._leftTrigger !== newValue) { this._onlefttriggerchanged(newValue); } this._leftTrigger = newValue; }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", { /** * Gets the right trigger value */ get: function () { return this._rightTrigger; }, /** * Sets the right trigger value */ set: function (newValue) { if (this._onrighttriggerchanged && this._rightTrigger !== newValue) { this._onrighttriggerchanged(newValue); } this._rightTrigger = newValue; }, enumerable: true, configurable: true }); /** * Defines the callback to call when a button is pressed * @param callback defines the callback to use */ Xbox360Pad.prototype.onbuttondown = function (callback) { this._onbuttondown = callback; }; /** * Defines the callback to call when a button is released * @param callback defines the callback to use */ Xbox360Pad.prototype.onbuttonup = function (callback) { this._onbuttonup = callback; }; /** * Defines the callback to call when a pad is pressed * @param callback defines the callback to use */ Xbox360Pad.prototype.ondpaddown = function (callback) { this._ondpaddown = callback; }; /** * Defines the callback to call when a pad is released * @param callback defines the callback to use */ Xbox360Pad.prototype.ondpadup = function (callback) { this._ondpadup = callback; }; Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) { if (newValue !== currentValue) { if (newValue === 1) { if (this._onbuttondown) { this._onbuttondown(buttonType); } this.onButtonDownObservable.notifyObservers(buttonType); } if (newValue === 0) { if (this._onbuttonup) { this._onbuttonup(buttonType); } this.onButtonUpObservable.notifyObservers(buttonType); } } return newValue; }; Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) { if (newValue !== currentValue) { if (newValue === 1) { if (this._ondpaddown) { this._ondpaddown(buttonType); } this.onPadDownObservable.notifyObservers(buttonType); } if (newValue === 0) { if (this._ondpadup) { this._ondpadup(buttonType); } this.onPadUpObservable.notifyObservers(buttonType); } } return newValue; }; Object.defineProperty(Xbox360Pad.prototype, "buttonA", { /** * Gets the value of the `A` button */ get: function () { return this._buttonA; }, /** * Sets the value of the `A` button */ set: function (value) { this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "buttonB", { /** * Gets the value of the `B` button */ get: function () { return this._buttonB; }, /** * Sets the value of the `B` button */ set: function (value) { this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "buttonX", { /** * Gets the value of the `X` button */ get: function () { return this._buttonX; }, /** * Sets the value of the `X` button */ set: function (value) { this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "buttonY", { /** * Gets the value of the `Y` button */ get: function () { return this._buttonY; }, /** * Sets the value of the `Y` button */ set: function (value) { this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "buttonStart", { /** * Gets the value of the `Start` button */ get: function () { return this._buttonStart; }, /** * Sets the value of the `Start` button */ set: function (value) { this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "buttonBack", { /** * Gets the value of the `Back` button */ get: function () { return this._buttonBack; }, /** * Sets the value of the `Back` button */ set: function (value) { this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "buttonLB", { /** * Gets the value of the `Left` button */ get: function () { return this._buttonLB; }, /** * Sets the value of the `Left` button */ set: function (value) { this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "buttonRB", { /** * Gets the value of the `Right` button */ get: function () { return this._buttonRB; }, /** * Sets the value of the `Right` button */ set: function (value) { this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", { /** * Gets the value of the Left joystick */ get: function () { return this._buttonLeftStick; }, /** * Sets the value of the Left joystick */ set: function (value) { this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", { /** * Gets the value of the Right joystick */ get: function () { return this._buttonRightStick; }, /** * Sets the value of the Right joystick */ set: function (value) { this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "dPadUp", { /** * Gets the value of D-pad up */ get: function () { return this._dPadUp; }, /** * Sets the value of D-pad up */ set: function (value) { this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "dPadDown", { /** * Gets the value of D-pad down */ get: function () { return this._dPadDown; }, /** * Sets the value of D-pad down */ set: function (value) { this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", { /** * Gets the value of D-pad left */ get: function () { return this._dPadLeft; }, /** * Sets the value of D-pad left */ set: function (value) { this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left); }, enumerable: true, configurable: true }); Object.defineProperty(Xbox360Pad.prototype, "dPadRight", { /** * Gets the value of D-pad right */ get: function () { return this._dPadRight; }, /** * Sets the value of D-pad right */ set: function (value) { this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right); }, enumerable: true, configurable: true }); /** * Force the gamepad to synchronize with device values */ Xbox360Pad.prototype.update = function () { _super.prototype.update.call(this); if (this._isXboxOnePad) { this.buttonA = this.browserGamepad.buttons[0].value; this.buttonB = this.browserGamepad.buttons[1].value; this.buttonX = this.browserGamepad.buttons[2].value; this.buttonY = this.browserGamepad.buttons[3].value; this.buttonLB = this.browserGamepad.buttons[4].value; this.buttonRB = this.browserGamepad.buttons[5].value; this.leftTrigger = this.browserGamepad.axes[2]; this.rightTrigger = this.browserGamepad.axes[5]; this.buttonBack = this.browserGamepad.buttons[9].value; this.buttonStart = this.browserGamepad.buttons[8].value; this.buttonLeftStick = this.browserGamepad.buttons[6].value; this.buttonRightStick = this.browserGamepad.buttons[7].value; this.dPadUp = this.browserGamepad.buttons[11].value; this.dPadDown = this.browserGamepad.buttons[12].value; this.dPadLeft = this.browserGamepad.buttons[13].value; this.dPadRight = this.browserGamepad.buttons[14].value; } else { this.buttonA = this.browserGamepad.buttons[0].value; this.buttonB = this.browserGamepad.buttons[1].value; this.buttonX = this.browserGamepad.buttons[2].value; this.buttonY = this.browserGamepad.buttons[3].value; this.buttonLB = this.browserGamepad.buttons[4].value; this.buttonRB = this.browserGamepad.buttons[5].value; this.leftTrigger = this.browserGamepad.buttons[6].value; this.rightTrigger = this.browserGamepad.buttons[7].value; this.buttonBack = this.browserGamepad.buttons[8].value; this.buttonStart = this.browserGamepad.buttons[9].value; this.buttonLeftStick = this.browserGamepad.buttons[10].value; this.buttonRightStick = this.browserGamepad.buttons[11].value; this.dPadUp = this.browserGamepad.buttons[12].value; this.dPadDown = this.browserGamepad.buttons[13].value; this.dPadLeft = this.browserGamepad.buttons[14].value; this.dPadRight = this.browserGamepad.buttons[15].value; } }; /** * Disposes the gamepad */ Xbox360Pad.prototype.dispose = function () { _super.prototype.dispose.call(this); this.onButtonDownObservable.clear(); this.onButtonUpObservable.clear(); this.onPadDownObservable.clear(); this.onPadUpObservable.clear(); }; return Xbox360Pad; }(_Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_2__["Gamepad"])); /***/ }), /***/ "./Gizmos/axisDragGizmo.ts": /*!*********************************!*\ !*** ./Gizmos/axisDragGizmo.ts ***! \*********************************/ /*! exports provided: AxisDragGizmo */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AxisDragGizmo", function() { return AxisDragGizmo; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Meshes/transformNode */ "./Meshes/transformNode.ts"); /* harmony import */ var _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/Builders/cylinderBuilder */ "./Meshes/Builders/cylinderBuilder.ts"); /* harmony import */ var _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Behaviors/Meshes/pointerDragBehavior */ "./Behaviors/Meshes/pointerDragBehavior.ts"); /* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts"); /* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts"); /* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts"); /** * Single axis drag gizmo */ var AxisDragGizmo = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AxisDragGizmo, _super); /** * Creates an AxisDragGizmo * @param gizmoLayer The utility layer the gizmo will be added to * @param dragAxis The axis which the gizmo will be able to drag on * @param color The color of the gizmo */ function AxisDragGizmo(dragAxis, color, gizmoLayer) { if (color === void 0) { color = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"].Gray(); } if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_7__["UtilityLayerRenderer"].DefaultUtilityLayer; } var _this = _super.call(this, gizmoLayer) || this; _this._pointerObserver = null; /** * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0) */ _this.snapDistance = 0; /** * Event that fires each time the gizmo snaps to a new location. * * snapDistance is the the change in distance */ _this.onSnapObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); // Create Material var coloredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_8__["StandardMaterial"]("", gizmoLayer.utilityLayerScene); coloredMaterial.diffuseColor = color; coloredMaterial.specularColor = color.subtract(new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"](0.1, 0.1, 0.1)); var hoverMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_8__["StandardMaterial"]("", gizmoLayer.utilityLayerScene); hoverMaterial.diffuseColor = color.add(new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"](0.3, 0.3, 0.3)); // Build mesh on root node var arrow = AxisDragGizmo._CreateArrow(gizmoLayer.utilityLayerScene, coloredMaterial); arrow.lookAt(_this._rootMesh.position.add(dragAxis)); arrow.scaling.scaleInPlace(1 / 3); arrow.parent = _this._rootMesh; var currentSnapDragDistance = 0; var tmpVector = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](); var tmpSnapEvent = { snapDistance: 0 }; // Add drag behavior to handle events when the gizmo is dragged _this.dragBehavior = new _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_5__["PointerDragBehavior"]({ dragAxis: dragAxis }); _this.dragBehavior.moveAttached = false; _this._rootMesh.addBehavior(_this.dragBehavior); var localDelta = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](); var tmpMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"](); _this.dragBehavior.onDragObservable.add(function (event) { if (_this.attachedMesh) { // Convert delta to local translation if it has a parent if (_this.attachedMesh.parent) { _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix); tmpMatrix.setTranslationFromFloats(0, 0, 0); _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta); } else { localDelta.copyFrom(event.delta); } // Snapping logic if (_this.snapDistance == 0) { _this.attachedMesh.position.addInPlace(localDelta); } else { currentSnapDragDistance += event.dragDistance; if (Math.abs(currentSnapDragDistance) > _this.snapDistance) { var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance); currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance; localDelta.normalizeToRef(tmpVector); tmpVector.scaleInPlace(_this.snapDistance * dragSteps); _this.attachedMesh.position.addInPlace(tmpVector); tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps; _this.onSnapObservable.notifyObservers(tmpSnapEvent); } } } }); _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo) { if (_this._customMeshSet) { return; } var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1); var material = isHovered ? hoverMaterial : coloredMaterial; _this._rootMesh.getChildMeshes().forEach(function (m) { m.material = material; if (m.color) { m.color = material.diffuseColor; } }); }); var light = gizmoLayer._getSharedGizmoLight(); light.includedOnlyMeshes = light.includedOnlyMeshes.concat(_this._rootMesh.getChildMeshes(false)); return _this; } /** @hidden */ AxisDragGizmo._CreateArrow = function (scene, material) { var arrow = new _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_3__["TransformNode"]("arrow", scene); var cylinder = _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_4__["CylinderBuilder"].CreateCylinder("cylinder", { diameterTop: 0, height: 0.075, diameterBottom: 0.0375, tessellation: 96 }, scene); var line = _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_4__["CylinderBuilder"].CreateCylinder("cylinder", { diameterTop: 0.005, height: 0.275, diameterBottom: 0.005, tessellation: 96 }, scene); line.material = material; cylinder.parent = arrow; line.parent = arrow; // Position arrow pointing in its drag axis cylinder.material = material; cylinder.rotation.x = Math.PI / 2; cylinder.position.z += 0.3; line.position.z += 0.275 / 2; line.rotation.x = Math.PI / 2; return arrow; }; /** @hidden */ AxisDragGizmo._CreateArrowInstance = function (scene, arrow) { var instance = new _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_3__["TransformNode"]("arrow", scene); for (var _i = 0, _a = arrow.getChildMeshes(); _i < _a.length; _i++) { var mesh = _a[_i]; var childInstance = mesh.createInstance(mesh.name); childInstance.parent = instance; } return instance; }; AxisDragGizmo.prototype._attachedMeshChanged = function (value) { if (this.dragBehavior) { this.dragBehavior.enabled = value ? true : false; } }; /** * Disposes of the gizmo */ AxisDragGizmo.prototype.dispose = function () { this.onSnapObservable.clear(); this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver); this.dragBehavior.detach(); _super.prototype.dispose.call(this); }; return AxisDragGizmo; }(_gizmo__WEBPACK_IMPORTED_MODULE_6__["Gizmo"])); /***/ }), /***/ "./Gizmos/axisScaleGizmo.ts": /*!**********************************!*\ !*** ./Gizmos/axisScaleGizmo.ts ***! \**********************************/ /*! exports provided: AxisScaleGizmo */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AxisScaleGizmo", function() { return AxisScaleGizmo; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts"); /* harmony import */ var _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/Builders/boxBuilder */ "./Meshes/Builders/boxBuilder.ts"); /* harmony import */ var _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Meshes/Builders/cylinderBuilder */ "./Meshes/Builders/cylinderBuilder.ts"); /* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts"); /* harmony import */ var _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Behaviors/Meshes/pointerDragBehavior */ "./Behaviors/Meshes/pointerDragBehavior.ts"); /* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts"); /* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts"); /** * Single axis scale gizmo */ var AxisScaleGizmo = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](AxisScaleGizmo, _super); /** * Creates an AxisScaleGizmo * @param gizmoLayer The utility layer the gizmo will be added to * @param dragAxis The axis which the gizmo will be able to scale on * @param color The color of the gizmo */ function AxisScaleGizmo(dragAxis, color, gizmoLayer) { if (color === void 0) { color = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"].Gray(); } if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_9__["UtilityLayerRenderer"].DefaultUtilityLayer; } var _this = _super.call(this, gizmoLayer) || this; _this._pointerObserver = null; /** * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0) */ _this.snapDistance = 0; /** * Event that fires each time the gizmo snaps to a new location. * * snapDistance is the the change in distance */ _this.onSnapObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * If the scaling operation should be done on all axis (default: false) */ _this.uniformScaling = false; // Create Material _this._coloredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_6__["StandardMaterial"]("", gizmoLayer.utilityLayerScene); _this._coloredMaterial.diffuseColor = color; _this._coloredMaterial.specularColor = color.subtract(new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"](0.1, 0.1, 0.1)); var hoverMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_6__["StandardMaterial"]("", gizmoLayer.utilityLayerScene); hoverMaterial.diffuseColor = color.add(new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"](0.3, 0.3, 0.3)); // Build mesh on root node var arrow = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_3__["AbstractMesh"]("", gizmoLayer.utilityLayerScene); var arrowMesh = _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_4__["BoxBuilder"].CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene); var arrowTail = _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_5__["CylinderBuilder"].CreateCylinder("cylinder", { diameterTop: 0.005, height: 0.275, diameterBottom: 0.005, tessellation: 96 }, gizmoLayer.utilityLayerScene); arrowTail.material = _this._coloredMaterial; arrow.addChild(arrowMesh); arrow.addChild(arrowTail); // Position arrow pointing in its drag axis arrowMesh.scaling.scaleInPlace(0.1); arrowMesh.material = _this._coloredMaterial; arrowMesh.rotation.x = Math.PI / 2; arrowMesh.position.z += 0.3; arrowTail.position.z += 0.275 / 2; arrowTail.rotation.x = Math.PI / 2; arrow.lookAt(_this._rootMesh.position.add(dragAxis)); _this._rootMesh.addChild(arrow); arrow.scaling.scaleInPlace(1 / 3); // Add drag behavior to handle events when the gizmo is dragged _this.dragBehavior = new _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_7__["PointerDragBehavior"]({ dragAxis: dragAxis }); _this.dragBehavior.moveAttached = false; _this._rootMesh.addBehavior(_this.dragBehavior); var currentSnapDragDistance = 0; var tmpVector = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](); var tmpSnapEvent = { snapDistance: 0 }; _this.dragBehavior.onDragObservable.add(function (event) { if (_this.attachedMesh) { // Snapping logic var snapped = false; var dragSteps = 0; if (_this.uniformScaling) { _this.attachedMesh.scaling.normalizeToRef(tmpVector); if (tmpVector.y < 0) { tmpVector.scaleInPlace(-1); } } else { tmpVector.copyFrom(dragAxis); } if (_this.snapDistance == 0) { tmpVector.scaleToRef(event.dragDistance, tmpVector); } else { currentSnapDragDistance += event.dragDistance; if (Math.abs(currentSnapDragDistance) > _this.snapDistance) { dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance); if (currentSnapDragDistance < 0) { dragSteps *= -1; } currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance; tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector); snapped = true; } else { tmpVector.scaleInPlace(0); } } _this.attachedMesh.scaling.addInPlace(tmpVector); if (snapped) { tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps; _this.onSnapObservable.notifyObservers(tmpSnapEvent); } } }); _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo) { if (_this._customMeshSet) { return; } var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1); var material = isHovered ? hoverMaterial : _this._coloredMaterial; _this._rootMesh.getChildMeshes().forEach(function (m) { m.material = material; if (m.color) { m.color = material.diffuseColor; } }); }); var light = gizmoLayer._getSharedGizmoLight(); light.includedOnlyMeshes = light.includedOnlyMeshes.concat(_this._rootMesh.getChildMeshes()); return _this; } AxisScaleGizmo.prototype._attachedMeshChanged = function (value) { if (this.dragBehavior) { this.dragBehavior.enabled = value ? true : false; } }; /** * Disposes of the gizmo */ AxisScaleGizmo.prototype.dispose = function () { this.onSnapObservable.clear(); this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver); this.dragBehavior.detach(); _super.prototype.dispose.call(this); }; /** * Disposes and replaces the current meshes in the gizmo with the specified mesh * @param mesh The mesh to replace the default mesh of the gizmo * @param useGizmoMaterial If the gizmo's default material should be used (default: false) */ AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) { var _this = this; if (useGizmoMaterial === void 0) { useGizmoMaterial = false; } _super.prototype.setCustomMesh.call(this, mesh); if (useGizmoMaterial) { this._rootMesh.getChildMeshes().forEach(function (m) { m.material = _this._coloredMaterial; if (m.color) { m.color = _this._coloredMaterial.diffuseColor; } }); this._customMeshSet = false; } }; return AxisScaleGizmo; }(_gizmo__WEBPACK_IMPORTED_MODULE_8__["Gizmo"])); /***/ }), /***/ "./Gizmos/boundingBoxGizmo.ts": /*!************************************!*\ !*** ./Gizmos/boundingBoxGizmo.ts ***! \************************************/ /*! exports provided: BoundingBoxGizmo */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoundingBoxGizmo", function() { return BoundingBoxGizmo; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts"); /* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts"); /* harmony import */ var _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Meshes/Builders/sphereBuilder */ "./Meshes/Builders/sphereBuilder.ts"); /* harmony import */ var _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Meshes/Builders/boxBuilder */ "./Meshes/Builders/boxBuilder.ts"); /* harmony import */ var _Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Meshes/Builders/linesBuilder */ "./Meshes/Builders/linesBuilder.ts"); /* harmony import */ var _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Behaviors/Meshes/pointerDragBehavior */ "./Behaviors/Meshes/pointerDragBehavior.ts"); /* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts"); /* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts"); /* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts"); /* harmony import */ var _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Misc/pivotTools */ "./Misc/pivotTools.ts"); /** * Bounding box gizmo */ var BoundingBoxGizmo = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BoundingBoxGizmo, _super); /** * Creates an BoundingBoxGizmo * @param gizmoLayer The utility layer the gizmo will be added to * @param color The color of the gizmo */ function BoundingBoxGizmo(color, gizmoLayer) { if (color === void 0) { color = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Gray(); } if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_11__["UtilityLayerRenderer"].DefaultKeepDepthUtilityLayer; } var _this = _super.call(this, gizmoLayer) || this; _this._boundingDimensions = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](1, 1, 1); _this._renderObserver = null; _this._pointerObserver = null; _this._scaleDragSpeed = 0.2; _this._tmpQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); _this._tmpVector = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); _this._tmpRotationMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"](); /** * If child meshes should be ignored when calculating the boudning box. This should be set to true to avoid perf hits with heavily nested meshes (Default: false) */ _this.ignoreChildren = false; /** * Returns true if a descendant should be included when computing the bounding box. When null, all descendants are included. If ignoreChildren is set this will be ignored. (Default: null) */ _this.includeChildPredicate = null; /** * The size of the rotation spheres attached to the bounding box (Default: 0.1) */ _this.rotationSphereSize = 0.1; /** * The size of the scale boxes attached to the bounding box (Default: 0.1) */ _this.scaleBoxSize = 0.1; /** * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false) */ _this.fixedDragMeshScreenSize = false; /** * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10) */ _this.fixedDragMeshScreenSizeDistanceFactor = 10; /** * Fired when a rotation sphere or scale box is dragged */ _this.onDragStartObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Fired when a scale box is dragged */ _this.onScaleBoxDragObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Fired when a scale box drag is ended */ _this.onScaleBoxDragEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Fired when a rotation sphere is dragged */ _this.onRotationSphereDragObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Fired when a rotation sphere drag is ended */ _this.onRotationSphereDragEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Relative bounding box pivot used when scaling the attached mesh. When null object with scale from the opposite corner. 0.5,0.5,0.5 for center and 0.5,0,0.5 for bottom (Default: null) */ _this.scalePivot = null; _this._existingMeshScale = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](); // Dragging _this._dragMesh = null; _this.pointerDragBehavior = new _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_9__["PointerDragBehavior"](); // Do not update the gizmo's scale so it has a fixed size to the object its attached to _this._updateScale = false; _this._anchorMesh = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_4__["AbstractMesh"]("anchor", gizmoLayer.utilityLayerScene); // Create Materials _this.coloredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_12__["StandardMaterial"]("", gizmoLayer.utilityLayerScene); _this.coloredMaterial.disableLighting = true; _this.hoverColoredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_12__["StandardMaterial"]("", gizmoLayer.utilityLayerScene); _this.hoverColoredMaterial.disableLighting = true; // Build bounding box out of lines _this._lineBoundingBox = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_4__["AbstractMesh"]("", gizmoLayer.utilityLayerScene); _this._lineBoundingBox.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); var lines = []; lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene)); lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene)); lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene)); lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, 0, 0), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene)); lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, 0, 0), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene)); lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, _this._boundingDimensions.y, 0), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene)); lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, _this._boundingDimensions.y, 0), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene)); lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, _this._boundingDimensions.z), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene)); lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, _this._boundingDimensions.z), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene)); lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene)); lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene)); lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene)); lines.forEach(function (l) { l.color = color; l.position.addInPlace(new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2)); l.isPickable = false; _this._lineBoundingBox.addChild(l); }); _this._rootMesh.addChild(_this._lineBoundingBox); _this.setColor(color); // Create rotation spheres _this._rotateSpheresParent = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_4__["AbstractMesh"]("", gizmoLayer.utilityLayerScene); _this._rotateSpheresParent.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); var _loop_1 = function (i_1) { var sphere = _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_6__["SphereBuilder"].CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene); sphere.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); sphere.material = this_1.coloredMaterial; // Drag behavior _dragBehavior = new _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_9__["PointerDragBehavior"]({}); _dragBehavior.moveAttached = false; _dragBehavior.updateDragPlane = false; sphere.addBehavior(_dragBehavior); var startingTurnDirection = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](1, 0, 0); var totalTurnAmountOfDrag = 0; _dragBehavior.onDragStartObservable.add(function () { startingTurnDirection.copyFrom(sphere.forward); totalTurnAmountOfDrag = 0; }); _dragBehavior.onDragObservable.add(function (event) { _this.onRotationSphereDragObservable.notifyObservers({}); if (_this.attachedMesh) { var originalParent = _this.attachedMesh.parent; if (originalParent && (originalParent.scaling && originalParent.scaling.isNonUniformWithinEpsilon(0.001))) { _Misc_logger__WEBPACK_IMPORTED_MODULE_2__["Logger"].Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling"); return; } _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__["PivotTools"]._RemoveAndStorePivotPoint(_this.attachedMesh); var worldDragDirection = startingTurnDirection; // Project the world right on to the drag plane var toSub = event.dragPlaneNormal.scale(_Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Dot(event.dragPlaneNormal, worldDragDirection)); var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew(); // project drag delta on to the resulting drag axis and rotate based on that var projectDist = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Dot(dragAxis, event.delta) < 0 ? Math.abs(event.delta.length()) : -Math.abs(event.delta.length()); // Make rotation relative to size of mesh. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length(); // Rotate based on axis if (!_this.attachedMesh.rotationQuaternion) { _this.attachedMesh.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z); } if (!_this._anchorMesh.rotationQuaternion) { _this._anchorMesh.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z); } // Do not allow the object to turn more than a full circle totalTurnAmountOfDrag += projectDist; if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) { if (i_1 >= 8) { _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion); } else if (i_1 >= 4) { _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion); } else { _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion); } // Rotate around center of bounding box _this._anchorMesh.addChild(_this.attachedMesh); _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion); _this._anchorMesh.removeChild(_this.attachedMesh); _this.attachedMesh.setParent(originalParent); } _this.updateBoundingBox(); _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__["PivotTools"]._RestorePivotPoint(_this.attachedMesh); } _this._updateDummy(); }); // Selection/deselection _dragBehavior.onDragStartObservable.add(function () { _this.onDragStartObservable.notifyObservers({}); _this._selectNode(sphere); }); _dragBehavior.onDragEndObservable.add(function () { _this.onRotationSphereDragEndObservable.notifyObservers({}); _this._selectNode(null); _this._updateDummy(); }); this_1._rotateSpheresParent.addChild(sphere); }; var this_1 = this, _dragBehavior; for (var i_1 = 0; i_1 < 12; i_1++) { _loop_1(i_1); } _this._rootMesh.addChild(_this._rotateSpheresParent); // Create scale cubes _this._scaleBoxesParent = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_4__["AbstractMesh"]("", gizmoLayer.utilityLayerScene); _this._scaleBoxesParent.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); for (var i = 0; i < 2; i++) { for (var j = 0; j < 2; j++) { var _loop_2 = function () { var box = _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_7__["BoxBuilder"].CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene); box.material = this_2.coloredMaterial; // Dragging logic var dragAxis = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1); _dragBehavior = new _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_9__["PointerDragBehavior"]({ dragAxis: dragAxis }); _dragBehavior.moveAttached = false; box.addBehavior(_dragBehavior); _dragBehavior.onDragObservable.add(function (event) { _this.onScaleBoxDragObservable.notifyObservers({}); if (_this.attachedMesh) { var originalParent = _this.attachedMesh.parent; if (originalParent && (originalParent.scaling && originalParent.scaling.isNonUniformWithinEpsilon(0.001))) { _Misc_logger__WEBPACK_IMPORTED_MODULE_2__["Logger"].Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling"); return; } _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__["PivotTools"]._RemoveAndStorePivotPoint(_this.attachedMesh); var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length(); var deltaScale = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](relativeDragDistance, relativeDragDistance, relativeDragDistance); deltaScale.scaleInPlace(_this._scaleDragSpeed); _this.updateBoundingBox(); if (_this.scalePivot) { _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix); // Move anchor to desired pivot point (Bottom left corner + dimension/2) _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector); _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector); _this._anchorMesh.position.subtractInPlace(_this._tmpVector); _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector); _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector); _this._anchorMesh.position.addInPlace(_this._tmpVector); } else { // Scale from the position of the opposite corner box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector); _this._anchorMesh.position.subtractInPlace(_this._tmpVector); } _this._anchorMesh.addChild(_this.attachedMesh); _this._anchorMesh.scaling.addInPlace(deltaScale); if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) { _this._anchorMesh.scaling.subtractInPlace(deltaScale); } _this._anchorMesh.removeChild(_this.attachedMesh); _this.attachedMesh.setParent(originalParent); _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__["PivotTools"]._RestorePivotPoint(_this.attachedMesh); } _this._updateDummy(); }); // Selection/deselection _dragBehavior.onDragStartObservable.add(function () { _this.onDragStartObservable.notifyObservers({}); _this._selectNode(box); }); _dragBehavior.onDragEndObservable.add(function () { _this.onScaleBoxDragEndObservable.notifyObservers({}); _this._selectNode(null); _this._updateDummy(); }); this_2._scaleBoxesParent.addChild(box); }; var this_2 = this, _dragBehavior; for (var k = 0; k < 2; k++) { _loop_2(); } } } _this._rootMesh.addChild(_this._scaleBoxesParent); // Hover color change var pointerIds = new Array(); _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo) { if (!pointerIds[pointerInfo.event.pointerId]) { _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) { if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) { pointerIds[pointerInfo.event.pointerId] = mesh; mesh.material = _this.hoverColoredMaterial; } }); } else { if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) { pointerIds[pointerInfo.event.pointerId].material = _this.coloredMaterial; delete pointerIds[pointerInfo.event.pointerId]; } } }); // Update bounding box positions _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () { // Only update the bouding box if scaling has changed if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) { _this.updateBoundingBox(); } else if (_this.fixedDragMeshScreenSize) { _this._updateRotationSpheres(); _this._updateScaleBoxes(); } // If dragg mesh is enabled and dragging, update the attached mesh pose to match the drag mesh if (_this._dragMesh && _this.attachedMesh && _this.pointerDragBehavior.dragging) { _this._lineBoundingBox.position.rotateByQuaternionToRef(_this._rootMesh.rotationQuaternion, _this._tmpVector); _this.attachedMesh.setAbsolutePosition(_this._dragMesh.position.add(_this._tmpVector.scale(-1))); } }); _this.updateBoundingBox(); return _this; } /** * Sets the color of the bounding box gizmo * @param color the color to set */ BoundingBoxGizmo.prototype.setColor = function (color) { this.coloredMaterial.emissiveColor = color; this.hoverColoredMaterial.emissiveColor = color.clone().add(new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"](0.3, 0.3, 0.3)); this._lineBoundingBox.getChildren().forEach(function (l) { if (l.color) { l.color = color; } }); }; BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) { var _this = this; if (value) { // Reset anchor mesh to match attached mesh's scale // This is needed to avoid invalid box/sphere position on first drag _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__["PivotTools"]._RemoveAndStorePivotPoint(value); var originalParent = value.parent; this._anchorMesh.addChild(value); this._anchorMesh.removeChild(value); value.setParent(originalParent); _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__["PivotTools"]._RestorePivotPoint(value); this.updateBoundingBox(); value.getChildMeshes(false).forEach(function (m) { m.markAsDirty("scaling"); }); this.gizmoLayer.utilityLayerScene.onAfterRenderObservable.addOnce(function () { _this._updateDummy(); }); } }; BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) { this._rotateSpheresParent.getChildMeshes() .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m) { m.isVisible = (!selectedMesh || m == selectedMesh); }); }; /** * Updates the bounding box information for the Gizmo */ BoundingBoxGizmo.prototype.updateBoundingBox = function () { if (this.attachedMesh) { _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__["PivotTools"]._RemoveAndStorePivotPoint(this.attachedMesh); var originalParent = this.attachedMesh.parent; this.attachedMesh.setParent(null); this._update(); // Rotate based on axis if (!this.attachedMesh.rotationQuaternion) { this.attachedMesh.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z); } if (!this._anchorMesh.rotationQuaternion) { this._anchorMesh.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z); } this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion); // Store original position and reset mesh to origin before computing the bounding box this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion); this._tmpVector.copyFrom(this.attachedMesh.position); this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1); this.attachedMesh.position.set(0, 0, 0); // Update bounding dimensions/positions var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate); boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions); // Update gizmo to match bounding box scaling and rotation this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions); this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2); this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position); this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position); this._lineBoundingBox.computeWorldMatrix(); this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition); // restore position/rotation values this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion); this.attachedMesh.position.copyFrom(this._tmpVector); this.attachedMesh.setParent(originalParent); } this._updateRotationSpheres(); this._updateScaleBoxes(); if (this.attachedMesh) { this._existingMeshScale.copyFrom(this.attachedMesh.scaling); _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__["PivotTools"]._RestorePivotPoint(this.attachedMesh); } }; BoundingBoxGizmo.prototype._updateRotationSpheres = function () { var rotateSpheres = this._rotateSpheresParent.getChildMeshes(); for (var i = 0; i < 3; i++) { for (var j = 0; j < 2; j++) { for (var k = 0; k < 2; k++) { var index = ((i * 4) + (j * 2)) + k; if (i == 0) { rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k); rotateSpheres[index].position.addInPlace(new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2)); rotateSpheres[index].lookAt(_Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Cross(rotateSpheres[index].position.normalizeToNew(), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Right()).normalizeToNew().add(rotateSpheres[index].position)); } if (i == 1) { rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k); rotateSpheres[index].position.addInPlace(new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2)); rotateSpheres[index].lookAt(_Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Cross(rotateSpheres[index].position.normalizeToNew(), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Up()).normalizeToNew().add(rotateSpheres[index].position)); } if (i == 2) { rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2); rotateSpheres[index].position.addInPlace(new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2)); rotateSpheres[index].lookAt(_Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Cross(rotateSpheres[index].position.normalizeToNew(), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Forward()).normalizeToNew().add(rotateSpheres[index].position)); } if (this.fixedDragMeshScreenSize && this.gizmoLayer.utilityLayerScene.activeCamera) { rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector); var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor; rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera); } else { rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize); } } } } }; BoundingBoxGizmo.prototype._updateScaleBoxes = function () { var scaleBoxes = this._scaleBoxesParent.getChildMeshes(); for (var i = 0; i < 2; i++) { for (var j = 0; j < 2; j++) { for (var k = 0; k < 2; k++) { var index = ((i * 4) + (j * 2)) + k; if (scaleBoxes[index]) { scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k); scaleBoxes[index].position.addInPlace(new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2)); if (this.fixedDragMeshScreenSize && this.gizmoLayer.utilityLayerScene.activeCamera) { scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector); var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor; scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera); } else { scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize); } } } } } }; /** * Enables rotation on the specified axis and disables rotation on the others * @param axis The list of axis that should be enabled (eg. "xy" or "xyz") */ BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) { this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) { if (i < 4) { m.setEnabled(axis.indexOf("x") != -1); } else if (i < 8) { m.setEnabled(axis.indexOf("y") != -1); } else { m.setEnabled(axis.indexOf("z") != -1); } }); }; /** * Enables/disables scaling * @param enable if scaling should be enabled */ BoundingBoxGizmo.prototype.setEnabledScaling = function (enable) { this._scaleBoxesParent.getChildMeshes().forEach(function (m, i) { m.setEnabled(enable); }); }; BoundingBoxGizmo.prototype._updateDummy = function () { if (this._dragMesh) { this._dragMesh.position.copyFrom(this._lineBoundingBox.getAbsolutePosition()); this._dragMesh.scaling.copyFrom(this._lineBoundingBox.scaling); this._dragMesh.rotationQuaternion.copyFrom(this._rootMesh.rotationQuaternion); } }; /** * Enables a pointer drag behavior on the bounding box of the gizmo */ BoundingBoxGizmo.prototype.enableDragBehavior = function () { this._dragMesh = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__["Mesh"].CreateBox("dummy", 1, this.gizmoLayer.utilityLayerScene); this._dragMesh.visibility = 0; this._dragMesh.rotationQuaternion = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); this.pointerDragBehavior.useObjectOrienationForDragging = false; this._dragMesh.addBehavior(this.pointerDragBehavior); }; /** * Disposes of the gizmo */ BoundingBoxGizmo.prototype.dispose = function () { this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver); this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver); this._lineBoundingBox.dispose(); this._rotateSpheresParent.dispose(); this._scaleBoxesParent.dispose(); if (this._dragMesh) { this._dragMesh.dispose(); } _super.prototype.dispose.call(this); }; /** * Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry) * @param mesh the mesh to wrap in the bounding box mesh and make not pickable * @returns the bounding box mesh with the passed in mesh as a child */ BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) { var makeNotPickable = function (root) { root.isPickable = false; root.getChildMeshes().forEach(function (c) { makeNotPickable(c); }); }; makeNotPickable(mesh); // Reset position to get boudning box from origin with no rotation if (!mesh.rotationQuaternion) { mesh.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z); } var oldPos = mesh.position.clone(); var oldRot = mesh.rotationQuaternion.clone(); mesh.rotationQuaternion.set(0, 0, 0, 1); mesh.position.set(0, 0, 0); // Update bounding dimensions/positions var box = _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_7__["BoxBuilder"].CreateBox("box", { size: 1 }, mesh.getScene()); var boundingMinMax = mesh.getHierarchyBoundingVectors(); boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling); // Adjust scale to avoid undefined behavior when adding child if (box.scaling.y === 0) { box.scaling.y = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]; } if (box.scaling.x === 0) { box.scaling.x = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]; } if (box.scaling.z === 0) { box.scaling.z = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Epsilon"]; } box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2); // Restore original positions mesh.addChild(box); mesh.rotationQuaternion.copyFrom(oldRot); mesh.position.copyFrom(oldPos); // Reverse parenting mesh.removeChild(box); box.addChild(mesh); box.visibility = 0; return box; }; /** * CustomMeshes are not supported by this gizmo * @param mesh The mesh to replace the default mesh of the gizmo */ BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) { _Misc_logger__WEBPACK_IMPORTED_MODULE_2__["Logger"].Error("Custom meshes are not supported on this gizmo"); }; return BoundingBoxGizmo; }(_gizmo__WEBPACK_IMPORTED_MODULE_10__["Gizmo"])); /***/ }), /***/ "./Gizmos/gizmo.ts": /*!*************************!*\ !*** ./Gizmos/gizmo.ts ***! \*************************/ /*! exports provided: Gizmo */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Gizmo", function() { return Gizmo; }); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts"); /* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts"); /** * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc. */ var Gizmo = /** @class */ (function () { /** * Creates a gizmo * @param gizmoLayer The utility layer the gizmo will be added to */ function Gizmo( /** The utility layer the gizmo will be added to */ gizmoLayer) { if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_2__["UtilityLayerRenderer"].DefaultUtilityLayer; } var _this = this; this.gizmoLayer = gizmoLayer; /** * Ratio for the scale of the gizmo (Default: 1) */ this.scaleRatio = 1; this._tmpMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"](); /** * If a custom mesh has been set (Default: false) */ this._customMeshSet = false; /** * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true) */ this.updateGizmoRotationToMatchAttachedMesh = true; /** * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true) */ this.updateGizmoPositionToMatchAttachedMesh = true; /** * When set, the gizmo will always appear the same size no matter where the camera is (default: false) */ this._updateScale = true; this._interactionsEnabled = true; this._tempVector = new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](); this._rootMesh = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_1__["Mesh"]("gizmoRootNode", gizmoLayer.utilityLayerScene); this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () { _this._update(); }); this.attachedMesh = null; } Object.defineProperty(Gizmo.prototype, "attachedMesh", { /** * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged) * * When set, interactions will be enabled */ get: function () { return this._attachedMesh; }, set: function (value) { this._attachedMesh = value; this._rootMesh.setEnabled(value ? true : false); this._attachedMeshChanged(value); }, enumerable: true, configurable: true }); /** * Disposes and replaces the current meshes in the gizmo with the specified mesh * @param mesh The mesh to replace the default mesh of the gizmo */ Gizmo.prototype.setCustomMesh = function (mesh) { if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) { throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)"; } this._rootMesh.getChildMeshes().forEach(function (c) { c.dispose(); }); mesh.parent = this._rootMesh; this._customMeshSet = true; }; Gizmo.prototype._attachedMeshChanged = function (value) { }; /** * @hidden * Updates the gizmo to match the attached mesh's position/rotation */ Gizmo.prototype._update = function () { if (this.attachedMesh) { var effectiveMesh = this.attachedMesh._effectiveMesh || this.attachedMesh; if (this.updateGizmoRotationToMatchAttachedMesh) { if (!this._rootMesh.rotationQuaternion) { this._rootMesh.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z); } // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale this._tempVector.copyFrom(effectiveMesh.scaling); if (effectiveMesh.scaling.x < 0) { effectiveMesh.scaling.x *= -1; } if (effectiveMesh.scaling.y < 0) { effectiveMesh.scaling.y *= -1; } if (effectiveMesh.scaling.z < 0) { effectiveMesh.scaling.z *= -1; } effectiveMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix); effectiveMesh.scaling.copyFrom(this._tempVector); effectiveMesh.computeWorldMatrix(); _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion); } else if (this._rootMesh.rotationQuaternion) { this._rootMesh.rotationQuaternion.set(0, 0, 0, 1); } if (this.updateGizmoPositionToMatchAttachedMesh) { this._rootMesh.position.copyFrom(effectiveMesh.absolutePosition); } if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) { var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.globalPosition; if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) { cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition; } this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector); var dist = this._tempVector.length() * this.scaleRatio; this._rootMesh.scaling.set(dist, dist, dist); } } }; /** * Disposes of the gizmo */ Gizmo.prototype.dispose = function () { this._rootMesh.dispose(); if (this._beforeRenderObserver) { this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver); } }; return Gizmo; }()); /***/ }), /***/ "./Gizmos/gizmoManager.ts": /*!********************************!*\ !*** ./Gizmos/gizmoManager.ts ***! \********************************/ /*! exports provided: GizmoManager */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GizmoManager", function() { return GizmoManager; }); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/pointerEvents */ "./Events/pointerEvents.ts"); /* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts"); /* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Behaviors_Meshes_sixDofDragBehavior__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Behaviors/Meshes/sixDofDragBehavior */ "./Behaviors/Meshes/sixDofDragBehavior.ts"); /* harmony import */ var _rotationGizmo__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./rotationGizmo */ "./Gizmos/rotationGizmo.ts"); /* harmony import */ var _positionGizmo__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./positionGizmo */ "./Gizmos/positionGizmo.ts"); /* harmony import */ var _scaleGizmo__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./scaleGizmo */ "./Gizmos/scaleGizmo.ts"); /* harmony import */ var _boundingBoxGizmo__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./boundingBoxGizmo */ "./Gizmos/boundingBoxGizmo.ts"); /** * Helps setup gizmo's in the scene to rotate/scale/position meshes */ var GizmoManager = /** @class */ (function () { /** * Instatiates a gizmo manager * @param scene the scene to overlay the gizmos on top of */ function GizmoManager(scene) { var _this = this; this.scene = scene; /** When true, the gizmo will be detached from the current object when a pointer down occurs with an empty picked mesh */ this.clearGizmoOnEmptyPointerEvent = false; /** Fires an event when the manager is attached to a mesh */ this.onAttachedToMeshObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false }; this._pointerObserver = null; this._attachedMesh = null; this._boundingBoxColor = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Color3"].FromHexString("#0984e3"); /** * When bounding box gizmo is enabled, this can be used to track drag/end events */ this.boundingBoxDragBehavior = new _Behaviors_Meshes_sixDofDragBehavior__WEBPACK_IMPORTED_MODULE_5__["SixDofDragBehavior"](); /** * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null) */ this.attachableMeshes = null; /** * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true) */ this.usePointerToAttachGizmos = true; this._defaultKeepDepthUtilityLayer = new _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_3__["UtilityLayerRenderer"](scene); this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false; this._defaultUtilityLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_3__["UtilityLayerRenderer"].DefaultUtilityLayer; this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null }; // Instatiate/dispose gizmos based on pointer actions this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo) { if (!_this.usePointerToAttachGizmos) { return; } if (pointerInfo.type == _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_1__["PointerEventTypes"].POINTERDOWN) { if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) { var node = pointerInfo.pickInfo.pickedMesh; if (_this.attachableMeshes == null) { // Attach to the most parent node while (node && node.parent != null) { node = node.parent; } } else { // Attach to the parent node that is an attachableMesh var found = false; _this.attachableMeshes.forEach(function (mesh) { if (node && (node == mesh || node.isDescendantOf(mesh))) { node = mesh; found = true; } }); if (!found) { node = null; } } if (node instanceof _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_2__["AbstractMesh"]) { if (_this._attachedMesh != node) { _this.attachToMesh(node); } } else { if (_this.clearGizmoOnEmptyPointerEvent) { _this.attachToMesh(null); } } } else { if (_this.clearGizmoOnEmptyPointerEvent) { _this.attachToMesh(null); } } } }); } /** * Attaches a set of gizmos to the specified mesh * @param mesh The mesh the gizmo's should be attached to */ GizmoManager.prototype.attachToMesh = function (mesh) { if (this._attachedMesh) { this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior); } this._attachedMesh = mesh; for (var key in this.gizmos) { var gizmo = (this.gizmos[key]); if (gizmo && this._gizmosEnabled[key]) { gizmo.attachedMesh = mesh; } } if (this.boundingBoxGizmoEnabled && this._attachedMesh) { this._attachedMesh.addBehavior(this.boundingBoxDragBehavior); } this.onAttachedToMeshObservable.notifyObservers(mesh); }; Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", { get: function () { return this._gizmosEnabled.positionGizmo; }, /** * If the position gizmo is enabled */ set: function (value) { if (value) { if (!this.gizmos.positionGizmo) { this.gizmos.positionGizmo = new _positionGizmo__WEBPACK_IMPORTED_MODULE_7__["PositionGizmo"](this._defaultUtilityLayer); } this.gizmos.positionGizmo.attachedMesh = this._attachedMesh; } else if (this.gizmos.positionGizmo) { this.gizmos.positionGizmo.attachedMesh = null; } this._gizmosEnabled.positionGizmo = value; }, enumerable: true, configurable: true }); Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", { get: function () { return this._gizmosEnabled.rotationGizmo; }, /** * If the rotation gizmo is enabled */ set: function (value) { if (value) { if (!this.gizmos.rotationGizmo) { this.gizmos.rotationGizmo = new _rotationGizmo__WEBPACK_IMPORTED_MODULE_6__["RotationGizmo"](this._defaultUtilityLayer); } this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh; } else if (this.gizmos.rotationGizmo) { this.gizmos.rotationGizmo.attachedMesh = null; } this._gizmosEnabled.rotationGizmo = value; }, enumerable: true, configurable: true }); Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", { get: function () { return this._gizmosEnabled.scaleGizmo; }, /** * If the scale gizmo is enabled */ set: function (value) { if (value) { this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new _scaleGizmo__WEBPACK_IMPORTED_MODULE_8__["ScaleGizmo"](this._defaultUtilityLayer); this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh; } else if (this.gizmos.scaleGizmo) { this.gizmos.scaleGizmo.attachedMesh = null; } this._gizmosEnabled.scaleGizmo = value; }, enumerable: true, configurable: true }); Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", { get: function () { return this._gizmosEnabled.boundingBoxGizmo; }, /** * If the boundingBox gizmo is enabled */ set: function (value) { if (value) { this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new _boundingBoxGizmo__WEBPACK_IMPORTED_MODULE_9__["BoundingBoxGizmo"](this._boundingBoxColor, this._defaultKeepDepthUtilityLayer); this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh; if (this._attachedMesh) { this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior); this._attachedMesh.addBehavior(this.boundingBoxDragBehavior); } } else if (this.gizmos.boundingBoxGizmo) { if (this._attachedMesh) { this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior); } this.gizmos.boundingBoxGizmo.attachedMesh = null; } this._gizmosEnabled.boundingBoxGizmo = value; }, enumerable: true, configurable: true }); /** * Disposes of the gizmo manager */ GizmoManager.prototype.dispose = function () { this.scene.onPointerObservable.remove(this._pointerObserver); for (var key in this.gizmos) { var gizmo = (this.gizmos[key]); if (gizmo) { gizmo.dispose(); } } this._defaultKeepDepthUtilityLayer.dispose(); this.boundingBoxDragBehavior.detach(); this.onAttachedToMeshObservable.clear(); }; return GizmoManager; }()); /***/ }), /***/ "./Gizmos/index.ts": /*!*************************!*\ !*** ./Gizmos/index.ts ***! \*************************/ /*! exports provided: AxisDragGizmo, AxisScaleGizmo, BoundingBoxGizmo, Gizmo, GizmoManager, PlaneRotationGizmo, PositionGizmo, RotationGizmo, ScaleGizmo, LightGizmo */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _axisDragGizmo__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./axisDragGizmo */ "./Gizmos/axisDragGizmo.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AxisDragGizmo", function() { return _axisDragGizmo__WEBPACK_IMPORTED_MODULE_0__["AxisDragGizmo"]; }); /* harmony import */ var _axisScaleGizmo__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./axisScaleGizmo */ "./Gizmos/axisScaleGizmo.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AxisScaleGizmo", function() { return _axisScaleGizmo__WEBPACK_IMPORTED_MODULE_1__["AxisScaleGizmo"]; }); /* harmony import */ var _boundingBoxGizmo__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./boundingBoxGizmo */ "./Gizmos/boundingBoxGizmo.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingBoxGizmo", function() { return _boundingBoxGizmo__WEBPACK_IMPORTED_MODULE_2__["BoundingBoxGizmo"]; }); /* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Gizmo", function() { return _gizmo__WEBPACK_IMPORTED_MODULE_3__["Gizmo"]; }); /* harmony import */ var _gizmoManager__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./gizmoManager */ "./Gizmos/gizmoManager.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GizmoManager", function() { return _gizmoManager__WEBPACK_IMPORTED_MODULE_4__["GizmoManager"]; }); /* harmony import */ var _planeRotationGizmo__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./planeRotationGizmo */ "./Gizmos/planeRotationGizmo.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlaneRotationGizmo", function() { return _planeRotationGizmo__WEBPACK_IMPORTED_MODULE_5__["PlaneRotationGizmo"]; }); /* harmony import */ var _positionGizmo__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./positionGizmo */ "./Gizmos/positionGizmo.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PositionGizmo", function() { return _positionGizmo__WEBPACK_IMPORTED_MODULE_6__["PositionGizmo"]; }); /* harmony import */ var _rotationGizmo__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./rotationGizmo */ "./Gizmos/rotationGizmo.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RotationGizmo", function() { return _rotationGizmo__WEBPACK_IMPORTED_MODULE_7__["RotationGizmo"]; }); /* harmony import */ var _scaleGizmo__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./scaleGizmo */ "./Gizmos/scaleGizmo.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScaleGizmo", function() { return _scaleGizmo__WEBPACK_IMPORTED_MODULE_8__["ScaleGizmo"]; }); /* harmony import */ var _lightGizmo__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./lightGizmo */ "./Gizmos/lightGizmo.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LightGizmo", function() { return _lightGizmo__WEBPACK_IMPORTED_MODULE_9__["LightGizmo"]; }); /***/ }), /***/ "./Gizmos/lightGizmo.ts": /*!******************************!*\ !*** ./Gizmos/lightGizmo.ts ***! \******************************/ /*! exports provided: LightGizmo */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LightGizmo", function() { return LightGizmo; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts"); /* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts"); /* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts"); /* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts"); /* harmony import */ var _Lights_hemisphericLight__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Lights/hemisphericLight */ "./Lights/hemisphericLight.ts"); /* harmony import */ var _Lights_directionalLight__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Lights/directionalLight */ "./Lights/directionalLight.ts"); /* harmony import */ var _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Meshes/Builders/sphereBuilder */ "./Meshes/Builders/sphereBuilder.ts"); /* harmony import */ var _Meshes_Builders_hemisphereBuilder__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Meshes/Builders/hemisphereBuilder */ "./Meshes/Builders/hemisphereBuilder.ts"); /* harmony import */ var _Lights_spotLight__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Lights/spotLight */ "./Lights/spotLight.ts"); /** * Gizmo that enables viewing a light */ var LightGizmo = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](LightGizmo, _super); /** * Creates a LightGizmo * @param gizmoLayer The utility layer the gizmo will be added to */ function LightGizmo(gizmoLayer) { var _this = _super.call(this, gizmoLayer) || this; _this._light = null; _this.attachedMesh = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_2__["AbstractMesh"]("", _this.gizmoLayer.utilityLayerScene); _this._material = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_5__["StandardMaterial"]("light", _this.gizmoLayer.originalScene); _this._material.diffuseColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color3"](0.5, 0.5, 0.5); _this._material.specularColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color3"](0.1, 0.1, 0.1); return _this; } Object.defineProperty(LightGizmo.prototype, "light", { get: function () { return this._light; }, /** * The light that the gizmo is attached to */ set: function (light) { var _this = this; this._light = light; if (light) { // Create the mesh for the given light type if (this._lightMesh) { this._lightMesh.dispose(); } if (light instanceof _Lights_hemisphericLight__WEBPACK_IMPORTED_MODULE_6__["HemisphericLight"]) { this._lightMesh = LightGizmo._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene); } else if (light instanceof _Lights_directionalLight__WEBPACK_IMPORTED_MODULE_7__["DirectionalLight"]) { this._lightMesh = LightGizmo._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene); } else if (light instanceof _Lights_spotLight__WEBPACK_IMPORTED_MODULE_10__["SpotLight"]) { this._lightMesh = LightGizmo._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene); } else { this._lightMesh = LightGizmo._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene); } this._lightMesh.getChildMeshes(false).forEach(function (m) { m.material = _this._material; }); this._lightMesh.parent = this._rootMesh; // Add lighting to the light gizmo var gizmoLight = this.gizmoLayer._getSharedGizmoLight(); gizmoLight.includedOnlyMeshes = gizmoLight.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(false)); // Get update position and direction if the light has it if (light.position) { this.attachedMesh.position.copyFrom(light.position); } if (light.direction) { this._lightMesh.setDirection(light.direction); } } }, enumerable: true, configurable: true }); /** * @hidden * Updates the gizmo to match the attached mesh's position/rotation */ LightGizmo.prototype._update = function () { _super.prototype._update.call(this); if (!this._light) { return; } if (this._light.position) { this._light.position.copyFrom(this.attachedMesh.position); } if (this._light.direction) { this._light.direction.copyFrom(this._lightMesh.forward); } if (!this._light.isEnabled()) { this._material.diffuseColor.set(0, 0, 0); } else { this._material.diffuseColor.set(this._light.diffuse.r / 3, this._light.diffuse.g / 3, this._light.diffuse.b / 3); } }; LightGizmo._CreateHemisphericLightMesh = function (scene) { var root = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"]("hemisphereLight", scene); var hemisphere = _Meshes_Builders_hemisphereBuilder__WEBPACK_IMPORTED_MODULE_9__["HemisphereBuilder"].CreateHemisphere(root.name, { segments: 10, diameter: 1 }, scene); hemisphere.position.z = -0.15; hemisphere.rotation.x = Math.PI / 2; hemisphere.parent = root; var lines = this._createLightLines(3, scene); lines.parent = root; lines.position.z - 0.15; root.scaling.scaleInPlace(LightGizmo._Scale); root.rotation.x = Math.PI / 2; return root; }; LightGizmo._CreatePointLightMesh = function (scene) { var root = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"]("pointLight", scene); var sphere = _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_8__["SphereBuilder"].CreateSphere(root.name, { segments: 10, diameter: 1 }, scene); sphere.rotation.x = Math.PI / 2; sphere.parent = root; var lines = this._createLightLines(5, scene); lines.parent = root; root.scaling.scaleInPlace(LightGizmo._Scale); root.rotation.x = Math.PI / 2; return root; }; LightGizmo._CreateSpotLightMesh = function (scene) { var root = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"]("spotLight", scene); var sphere = _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_8__["SphereBuilder"].CreateSphere(root.name, { segments: 10, diameter: 1 }, scene); sphere.parent = root; var hemisphere = _Meshes_Builders_hemisphereBuilder__WEBPACK_IMPORTED_MODULE_9__["HemisphereBuilder"].CreateHemisphere(root.name, { segments: 10, diameter: 2 }, scene); hemisphere.parent = root; hemisphere.rotation.x = -Math.PI / 2; var lines = this._createLightLines(2, scene); lines.parent = root; root.scaling.scaleInPlace(LightGizmo._Scale); root.rotation.x = Math.PI / 2; return root; }; LightGizmo._CreateDirectionalLightMesh = function (scene) { var root = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"]("directionalLight", scene); var mesh = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"](root.name, scene); mesh.parent = root; var sphere = _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_8__["SphereBuilder"].CreateSphere(root.name, { diameter: 1.2, segments: 10 }, scene); sphere.parent = mesh; var line = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"].CreateCylinder(root.name, 6, 0.3, 0.3, 6, 1, scene); line.parent = mesh; var left = line.clone(root.name); left.scaling.y = 0.5; left.position.x += 1.25; var right = line.clone(root.name); right.scaling.y = 0.5; right.position.x += -1.25; var arrowHead = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"].CreateCylinder(root.name, 1, 0, 0.6, 6, 1, scene); arrowHead.position.y += 3; arrowHead.parent = mesh; var left = arrowHead.clone(root.name); left.position.y = 1.5; left.position.x += 1.25; var right = arrowHead.clone(root.name); right.position.y = 1.5; right.position.x += -1.25; mesh.scaling.scaleInPlace(LightGizmo._Scale); mesh.rotation.z = Math.PI / 2; mesh.rotation.y = Math.PI / 2; return root; }; // Static helper methods LightGizmo._Scale = 0.007; /** * Creates the lines for a light mesh */ LightGizmo._createLightLines = function (levels, scene) { var distFromSphere = 1.2; var root = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"]("root", scene); root.rotation.x = Math.PI / 2; // Create the top line, this will be cloned for all other lines var linePivot = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"]("linePivot", scene); linePivot.parent = root; var line = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"].CreateCylinder("line", 2, 0.2, 0.3, 6, 1, scene); line.position.y = line.scaling.y / 2 + distFromSphere; line.parent = linePivot; if (levels < 2) { return linePivot; } for (var i = 0; i < 4; i++) { var l = linePivot.clone("lineParentClone"); l.rotation.z = Math.PI / 4; l.rotation.y = (Math.PI / 2) + (Math.PI / 2 * i); l.getChildMeshes()[0].scaling.y = 0.5; l.getChildMeshes()[0].scaling.x = l.getChildMeshes()[0].scaling.z = 0.8; l.getChildMeshes()[0].position.y = l.getChildMeshes()[0].scaling.y / 2 + distFromSphere; } if (levels < 3) { return root; } for (var i = 0; i < 4; i++) { var l = linePivot.clone("linePivotClone"); l.rotation.z = Math.PI / 2; l.rotation.y = (Math.PI / 2 * i); } if (levels < 4) { return root; } for (var i = 0; i < 4; i++) { var l = linePivot.clone("linePivotClone"); l.rotation.z = Math.PI + (Math.PI / 4); l.rotation.y = (Math.PI / 2) + (Math.PI / 2 * i); l.getChildMeshes()[0].scaling.y = 0.5; l.getChildMeshes()[0].scaling.x = l.getChildMeshes()[0].scaling.z = 0.8; l.getChildMeshes()[0].position.y = l.getChildMeshes()[0].scaling.y / 2 + distFromSphere; } if (levels < 5) { return root; } var l = linePivot.clone("linePivotClone"); l.rotation.z = Math.PI; return root; }; return LightGizmo; }(_gizmo__WEBPACK_IMPORTED_MODULE_4__["Gizmo"])); /***/ }), /***/ "./Gizmos/planeRotationGizmo.ts": /*!**************************************!*\ !*** ./Gizmos/planeRotationGizmo.ts ***! \**************************************/ /*! exports provided: PlaneRotationGizmo */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaneRotationGizmo", function() { return PlaneRotationGizmo; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts"); /* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts"); /* harmony import */ var _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Behaviors/Meshes/pointerDragBehavior */ "./Behaviors/Meshes/pointerDragBehavior.ts"); /* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts"); /* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts"); /* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts"); /* harmony import */ var _Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Meshes/Builders/linesBuilder */ "./Meshes/Builders/linesBuilder.ts"); /** * Single plane rotation gizmo */ var PlaneRotationGizmo = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PlaneRotationGizmo, _super); /** * Creates a PlaneRotationGizmo * @param gizmoLayer The utility layer the gizmo will be added to * @param planeNormal The normal of the plane which the gizmo will be able to rotate on * @param color The color of the gizmo * @param tessellation Amount of tessellation to be used when creating rotation circles */ function PlaneRotationGizmo(planeNormal, color, gizmoLayer, tessellation) { if (color === void 0) { color = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"].Gray(); } if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_7__["UtilityLayerRenderer"].DefaultUtilityLayer; } if (tessellation === void 0) { tessellation = 32; } var _this = _super.call(this, gizmoLayer) || this; _this._pointerObserver = null; /** * Rotation distance in radians that the gizmo will snap to (Default: 0) */ _this.snapDistance = 0; /** * Event that fires each time the gizmo snaps to a new location. * * snapDistance is the the change in distance */ _this.onSnapObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); // Create Material var coloredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_8__["StandardMaterial"]("", gizmoLayer.utilityLayerScene); coloredMaterial.diffuseColor = color; coloredMaterial.specularColor = color.subtract(new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"](0.1, 0.1, 0.1)); var hoverMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_8__["StandardMaterial"]("", gizmoLayer.utilityLayerScene); hoverMaterial.diffuseColor = color.add(new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"](0.3, 0.3, 0.3)); // Build mesh on root node var parentMesh = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_3__["AbstractMesh"]("", gizmoLayer.utilityLayerScene); var drag = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"].CreateTorus("", 0.6, 0.03, tessellation, gizmoLayer.utilityLayerScene); drag.visibility = 0; var rotationMesh = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"].CreateTorus("", 0.6, 0.005, tessellation, gizmoLayer.utilityLayerScene); rotationMesh.material = coloredMaterial; // Position arrow pointing in its drag axis rotationMesh.rotation.x = Math.PI / 2; drag.rotation.x = Math.PI / 2; parentMesh.addChild(rotationMesh); parentMesh.addChild(drag); parentMesh.lookAt(_this._rootMesh.position.add(planeNormal)); _this._rootMesh.addChild(parentMesh); parentMesh.scaling.scaleInPlace(1 / 3); // Add drag behavior to handle events when the gizmo is dragged _this.dragBehavior = new _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_5__["PointerDragBehavior"]({ dragPlaneNormal: planeNormal }); _this.dragBehavior.moveAttached = false; _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20; _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true; _this._rootMesh.addBehavior(_this.dragBehavior); var lastDragPosition = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](); _this.dragBehavior.onDragStartObservable.add(function (e) { if (_this.attachedMesh) { lastDragPosition.copyFrom(e.dragPlanePoint); } }); var rotationMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"](); var planeNormalTowardsCamera = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](); var localPlaneNormalTowardsCamera = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](); var tmpSnapEvent = { snapDistance: 0 }; var currentSnapDragDistance = 0; var tmpMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"](); var tmpVector = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](); var amountToRotate = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"](); _this.dragBehavior.onDragObservable.add(function (event) { if (_this.attachedMesh) { if (!_this.attachedMesh.rotationQuaternion) { _this.attachedMesh.rotationQuaternion = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"].RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z); } // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360) var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize(); var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize(); var cross = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Cross(newVector, originalVector); var dot = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Dot(newVector, originalVector); var angle = Math.atan2(cross.length(), dot); planeNormalTowardsCamera.copyFrom(planeNormal); localPlaneNormalTowardsCamera.copyFrom(planeNormal); if (_this.updateGizmoRotationToMatchAttachedMesh) { _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix); localPlaneNormalTowardsCamera = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinates(planeNormalTowardsCamera, rotationMatrix); } // Flip up vector depending on which side the camera is on if (gizmoLayer.utilityLayerScene.activeCamera) { var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position); if (_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Dot(camVec, localPlaneNormalTowardsCamera) > 0) { planeNormalTowardsCamera.scaleInPlace(-1); localPlaneNormalTowardsCamera.scaleInPlace(-1); } } var halfCircleSide = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Dot(localPlaneNormalTowardsCamera, cross) > 0.0; if (halfCircleSide) { angle = -angle; } // Snapping logic var snapped = false; if (_this.snapDistance != 0) { currentSnapDragDistance += angle; if (Math.abs(currentSnapDragDistance) > _this.snapDistance) { var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance); if (currentSnapDragDistance < 0) { dragSteps *= -1; } currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance; angle = _this.snapDistance * dragSteps; snapped = true; } else { angle = 0; } } // If the mesh has a parent, convert needed world rotation to local rotation tmpMatrix.reset(); if (_this.attachedMesh.parent) { _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix); tmpMatrix.getRotationMatrixToRef(tmpMatrix); _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera); } // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm) var quaternionCoefficient = Math.sin(angle / 2); amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2)); // If the meshes local scale is inverted (eg. loaded gltf file parent with z scale of -1) the rotation needs to be inverted on the y axis if (tmpMatrix.determinant() > 0) { amountToRotate.toEulerAnglesToRef(tmpVector); _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Quaternion"].RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate); } if (_this.updateGizmoRotationToMatchAttachedMesh) { // Rotate selected mesh quaternion over fixed axis _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion); } else { // Rotate selected mesh quaternion over rotated axis amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion); } lastDragPosition.copyFrom(event.dragPlanePoint); if (snapped) { tmpSnapEvent.snapDistance = angle; _this.onSnapObservable.notifyObservers(tmpSnapEvent); } } }); _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo) { if (_this._customMeshSet) { return; } var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1); var material = isHovered ? hoverMaterial : coloredMaterial; _this._rootMesh.getChildMeshes().forEach(function (m) { m.material = material; if (m.color) { m.color = material.diffuseColor; } }); }); var light = gizmoLayer._getSharedGizmoLight(); light.includedOnlyMeshes = light.includedOnlyMeshes.concat(_this._rootMesh.getChildMeshes(false)); return _this; } PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) { if (this.dragBehavior) { this.dragBehavior.enabled = value ? true : false; } }; /** * Disposes of the gizmo */ PlaneRotationGizmo.prototype.dispose = function () { this.onSnapObservable.clear(); this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver); this.dragBehavior.detach(); _super.prototype.dispose.call(this); }; return PlaneRotationGizmo; }(_gizmo__WEBPACK_IMPORTED_MODULE_6__["Gizmo"])); /***/ }), /***/ "./Gizmos/positionGizmo.ts": /*!*********************************!*\ !*** ./Gizmos/positionGizmo.ts ***! \*********************************/ /*! exports provided: PositionGizmo */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PositionGizmo", function() { return PositionGizmo; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts"); /* harmony import */ var _axisDragGizmo__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./axisDragGizmo */ "./Gizmos/axisDragGizmo.ts"); /* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts"); /** * Gizmo that enables dragging a mesh along 3 axis */ var PositionGizmo = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PositionGizmo, _super); /** * Creates a PositionGizmo * @param gizmoLayer The utility layer the gizmo will be added to */ function PositionGizmo(gizmoLayer) { if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_6__["UtilityLayerRenderer"].DefaultUtilityLayer; } var _this = _super.call(this, gizmoLayer) || this; /** Fires an event when any of it's sub gizmos are dragged */ _this.onDragStartObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** Fires an event when any of it's sub gizmos are released from dragging */ _this.onDragEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); _this.xGizmo = new _axisDragGizmo__WEBPACK_IMPORTED_MODULE_5__["AxisDragGizmo"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](1, 0, 0), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Red().scale(0.5), gizmoLayer); _this.yGizmo = new _axisDragGizmo__WEBPACK_IMPORTED_MODULE_5__["AxisDragGizmo"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 1, 0), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Green().scale(0.5), gizmoLayer); _this.zGizmo = new _axisDragGizmo__WEBPACK_IMPORTED_MODULE_5__["AxisDragGizmo"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 1), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Blue().scale(0.5), gizmoLayer); // Relay drag events [_this.xGizmo, _this.yGizmo, _this.zGizmo].forEach(function (gizmo) { gizmo.dragBehavior.onDragStartObservable.add(function () { _this.onDragStartObservable.notifyObservers({}); }); gizmo.dragBehavior.onDragEndObservable.add(function () { _this.onDragEndObservable.notifyObservers({}); }); }); _this.attachedMesh = null; return _this; } Object.defineProperty(PositionGizmo.prototype, "attachedMesh", { get: function () { return this.xGizmo.attachedMesh; }, set: function (mesh) { if (this.xGizmo) { this.xGizmo.attachedMesh = mesh; this.yGizmo.attachedMesh = mesh; this.zGizmo.attachedMesh = mesh; } }, enumerable: true, configurable: true }); Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", { get: function () { return this.xGizmo.updateGizmoRotationToMatchAttachedMesh; }, set: function (value) { if (this.xGizmo) { this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value; this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value; this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value; } }, enumerable: true, configurable: true }); Object.defineProperty(PositionGizmo.prototype, "snapDistance", { get: function () { return this.xGizmo.snapDistance; }, /** * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0) */ set: function (value) { if (this.xGizmo) { this.xGizmo.snapDistance = value; this.yGizmo.snapDistance = value; this.zGizmo.snapDistance = value; } }, enumerable: true, configurable: true }); Object.defineProperty(PositionGizmo.prototype, "scaleRatio", { get: function () { return this.xGizmo.scaleRatio; }, /** * Ratio for the scale of the gizmo (Default: 1) */ set: function (value) { if (this.xGizmo) { this.xGizmo.scaleRatio = value; this.yGizmo.scaleRatio = value; this.zGizmo.scaleRatio = value; } }, enumerable: true, configurable: true }); /** * Disposes of the gizmo */ PositionGizmo.prototype.dispose = function () { this.xGizmo.dispose(); this.yGizmo.dispose(); this.zGizmo.dispose(); this.onDragStartObservable.clear(); this.onDragEndObservable.clear(); }; /** * CustomMeshes are not supported by this gizmo * @param mesh The mesh to replace the default mesh of the gizmo */ PositionGizmo.prototype.setCustomMesh = function (mesh) { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)"); }; return PositionGizmo; }(_gizmo__WEBPACK_IMPORTED_MODULE_4__["Gizmo"])); /***/ }), /***/ "./Gizmos/rotationGizmo.ts": /*!*********************************!*\ !*** ./Gizmos/rotationGizmo.ts ***! \*********************************/ /*! exports provided: RotationGizmo */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RotationGizmo", function() { return RotationGizmo; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts"); /* harmony import */ var _planeRotationGizmo__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./planeRotationGizmo */ "./Gizmos/planeRotationGizmo.ts"); /* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts"); /** * Gizmo that enables rotating a mesh along 3 axis */ var RotationGizmo = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RotationGizmo, _super); /** * Creates a RotationGizmo * @param gizmoLayer The utility layer the gizmo will be added to * @param tessellation Amount of tessellation to be used when creating rotation circles */ function RotationGizmo(gizmoLayer, tessellation) { if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_6__["UtilityLayerRenderer"].DefaultUtilityLayer; } if (tessellation === void 0) { tessellation = 32; } var _this = _super.call(this, gizmoLayer) || this; /** Fires an event when any of it's sub gizmos are dragged */ _this.onDragStartObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** Fires an event when any of it's sub gizmos are released from dragging */ _this.onDragEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); _this.xGizmo = new _planeRotationGizmo__WEBPACK_IMPORTED_MODULE_5__["PlaneRotationGizmo"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](1, 0, 0), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Red().scale(0.5), gizmoLayer, tessellation); _this.yGizmo = new _planeRotationGizmo__WEBPACK_IMPORTED_MODULE_5__["PlaneRotationGizmo"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 1, 0), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Green().scale(0.5), gizmoLayer, tessellation); _this.zGizmo = new _planeRotationGizmo__WEBPACK_IMPORTED_MODULE_5__["PlaneRotationGizmo"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 1), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Blue().scale(0.5), gizmoLayer, tessellation); // Relay drag events [_this.xGizmo, _this.yGizmo, _this.zGizmo].forEach(function (gizmo) { gizmo.dragBehavior.onDragStartObservable.add(function () { _this.onDragStartObservable.notifyObservers({}); }); gizmo.dragBehavior.onDragEndObservable.add(function () { _this.onDragEndObservable.notifyObservers({}); }); }); _this.attachedMesh = null; return _this; } Object.defineProperty(RotationGizmo.prototype, "attachedMesh", { get: function () { return this.xGizmo.attachedMesh; }, set: function (mesh) { if (this.xGizmo) { this.xGizmo.attachedMesh = mesh; this.yGizmo.attachedMesh = mesh; this.zGizmo.attachedMesh = mesh; } }, enumerable: true, configurable: true }); Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", { get: function () { return this.xGizmo.updateGizmoRotationToMatchAttachedMesh; }, set: function (value) { if (this.xGizmo) { this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value; this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value; this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value; } }, enumerable: true, configurable: true }); Object.defineProperty(RotationGizmo.prototype, "snapDistance", { get: function () { return this.xGizmo.snapDistance; }, /** * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0) */ set: function (value) { if (this.xGizmo) { this.xGizmo.snapDistance = value; this.yGizmo.snapDistance = value; this.zGizmo.snapDistance = value; } }, enumerable: true, configurable: true }); Object.defineProperty(RotationGizmo.prototype, "scaleRatio", { get: function () { return this.xGizmo.scaleRatio; }, /** * Ratio for the scale of the gizmo (Default: 1) */ set: function (value) { if (this.xGizmo) { this.xGizmo.scaleRatio = value; this.yGizmo.scaleRatio = value; this.zGizmo.scaleRatio = value; } }, enumerable: true, configurable: true }); /** * Disposes of the gizmo */ RotationGizmo.prototype.dispose = function () { this.xGizmo.dispose(); this.yGizmo.dispose(); this.zGizmo.dispose(); this.onDragStartObservable.clear(); this.onDragEndObservable.clear(); }; /** * CustomMeshes are not supported by this gizmo * @param mesh The mesh to replace the default mesh of the gizmo */ RotationGizmo.prototype.setCustomMesh = function (mesh) { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)"); }; return RotationGizmo; }(_gizmo__WEBPACK_IMPORTED_MODULE_4__["Gizmo"])); /***/ }), /***/ "./Gizmos/scaleGizmo.ts": /*!******************************!*\ !*** ./Gizmos/scaleGizmo.ts ***! \******************************/ /*! exports provided: ScaleGizmo */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ScaleGizmo", function() { return ScaleGizmo; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Meshes_Builders_polyhedronBuilder__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/Builders/polyhedronBuilder */ "./Meshes/Builders/polyhedronBuilder.ts"); /* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts"); /* harmony import */ var _axisScaleGizmo__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./axisScaleGizmo */ "./Gizmos/axisScaleGizmo.ts"); /* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts"); /** * Gizmo that enables scaling a mesh along 3 axis */ var ScaleGizmo = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ScaleGizmo, _super); /** * Creates a ScaleGizmo * @param gizmoLayer The utility layer the gizmo will be added to */ function ScaleGizmo(gizmoLayer) { if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_7__["UtilityLayerRenderer"].DefaultUtilityLayer; } var _this = _super.call(this, gizmoLayer) || this; /** Fires an event when any of it's sub gizmos are dragged */ _this.onDragStartObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** Fires an event when any of it's sub gizmos are released from dragging */ _this.onDragEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); _this.xGizmo = new _axisScaleGizmo__WEBPACK_IMPORTED_MODULE_6__["AxisScaleGizmo"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](1, 0, 0), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Red().scale(0.5), gizmoLayer); _this.yGizmo = new _axisScaleGizmo__WEBPACK_IMPORTED_MODULE_6__["AxisScaleGizmo"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 1, 0), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Green().scale(0.5), gizmoLayer); _this.zGizmo = new _axisScaleGizmo__WEBPACK_IMPORTED_MODULE_6__["AxisScaleGizmo"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 1), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Blue().scale(0.5), gizmoLayer); // Create uniform scale gizmo _this.uniformScaleGizmo = new _axisScaleGizmo__WEBPACK_IMPORTED_MODULE_6__["AxisScaleGizmo"](new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 1, 0), _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"].Yellow().scale(0.5), gizmoLayer); _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false; _this.uniformScaleGizmo.uniformScaling = true; var uniformScalingMesh = _Meshes_Builders_polyhedronBuilder__WEBPACK_IMPORTED_MODULE_4__["PolyhedronBuilder"].CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene); uniformScalingMesh.scaling.scaleInPlace(0.02); uniformScalingMesh.visibility = 0; var octahedron = _Meshes_Builders_polyhedronBuilder__WEBPACK_IMPORTED_MODULE_4__["PolyhedronBuilder"].CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene); octahedron.scaling.scaleInPlace(0.007); uniformScalingMesh.addChild(octahedron); _this.uniformScaleGizmo.setCustomMesh(uniformScalingMesh, true); var light = gizmoLayer._getSharedGizmoLight(); light.includedOnlyMeshes = light.includedOnlyMeshes.concat(octahedron); // Relay drag events [_this.xGizmo, _this.yGizmo, _this.zGizmo, _this.uniformScaleGizmo].forEach(function (gizmo) { gizmo.dragBehavior.onDragStartObservable.add(function () { _this.onDragStartObservable.notifyObservers({}); }); gizmo.dragBehavior.onDragEndObservable.add(function () { _this.onDragEndObservable.notifyObservers({}); }); }); _this.attachedMesh = null; return _this; } Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", { get: function () { return this.xGizmo.attachedMesh; }, set: function (mesh) { if (this.xGizmo) { this.xGizmo.attachedMesh = mesh; this.yGizmo.attachedMesh = mesh; this.zGizmo.attachedMesh = mesh; this.uniformScaleGizmo.attachedMesh = mesh; } }, enumerable: true, configurable: true }); Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", { get: function () { return this.xGizmo.updateGizmoRotationToMatchAttachedMesh; }, set: function (value) { if (!value) { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported."); } if (this.xGizmo) { this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value; this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value; this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value; } }, enumerable: true, configurable: true }); Object.defineProperty(ScaleGizmo.prototype, "snapDistance", { get: function () { return this.xGizmo.snapDistance; }, /** * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0) */ set: function (value) { if (this.xGizmo) { this.xGizmo.snapDistance = value; this.yGizmo.snapDistance = value; this.zGizmo.snapDistance = value; this.uniformScaleGizmo.snapDistance = value; } }, enumerable: true, configurable: true }); Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", { get: function () { return this.xGizmo.scaleRatio; }, /** * Ratio for the scale of the gizmo (Default: 1) */ set: function (value) { if (this.xGizmo) { this.xGizmo.scaleRatio = value; this.yGizmo.scaleRatio = value; this.zGizmo.scaleRatio = value; this.uniformScaleGizmo.scaleRatio = value; } }, enumerable: true, configurable: true }); /** * Disposes of the gizmo */ ScaleGizmo.prototype.dispose = function () { this.xGizmo.dispose(); this.yGizmo.dispose(); this.zGizmo.dispose(); this.uniformScaleGizmo.dispose(); this.onDragStartObservable.clear(); this.onDragEndObservable.clear(); }; return ScaleGizmo; }(_gizmo__WEBPACK_IMPORTED_MODULE_5__["Gizmo"])); /***/ }), /***/ "./Helpers/environmentHelper.ts": /*!**************************************!*\ !*** ./Helpers/environmentHelper.ts ***! \**************************************/ /*! exports provided: EnvironmentHelper */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EnvironmentHelper", function() { return EnvironmentHelper; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Cameras/arcRotateCamera */ "./Cameras/arcRotateCamera.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts"); /* harmony import */ var _Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Materials/Textures/baseTexture */ "./Materials/Textures/baseTexture.ts"); /* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); /* harmony import */ var _Materials_Textures_mirrorTexture__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Materials/Textures/mirrorTexture */ "./Materials/Textures/mirrorTexture.ts"); /* harmony import */ var _Materials_Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Materials/Textures/cubeTexture */ "./Materials/Textures/cubeTexture.ts"); /* harmony import */ var _Materials_Background_backgroundMaterial__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Materials/Background/backgroundMaterial */ "./Materials/Background/backgroundMaterial.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); /* harmony import */ var _Meshes_Builders_planeBuilder__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Meshes/Builders/planeBuilder */ "./Meshes/Builders/planeBuilder.ts"); /* harmony import */ var _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Meshes/Builders/boxBuilder */ "./Meshes/Builders/boxBuilder.ts"); /** * The Environment helper class can be used to add a fully featuread none expensive background to your scene. * It includes by default a skybox and a ground relying on the BackgroundMaterial. * It also helps with the default setup of your imageProcessing configuration. */ var EnvironmentHelper = /** @class */ (function () { /** * constructor * @param options Defines the options we want to customize the helper * @param scene The scene to add the material to */ function EnvironmentHelper(options, scene) { var _this = this; this._errorHandler = function (message, exception) { _this.onErrorObservable.notifyObservers({ message: message, exception: exception }); }; this._options = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, EnvironmentHelper._getDefaultOptions(), options); this._scene = scene; this.onErrorObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); this._setupBackground(); this._setupImageProcessing(); } /** * Creates the default options for the helper. */ EnvironmentHelper._getDefaultOptions = function () { return { createGround: true, groundSize: 15, groundTexture: this._groundTextureCDNUrl, groundColor: new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"](0.2, 0.2, 0.3).toLinearSpace().scale(3), groundOpacity: 0.9, enableGroundShadow: true, groundShadowLevel: 0.5, enableGroundMirror: false, groundMirrorSizeRatio: 0.3, groundMirrorBlurKernel: 64, groundMirrorAmount: 1, groundMirrorFresnelWeight: 1, groundMirrorFallOffDistance: 0, groundMirrorTextureType: _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_UNSIGNED_INT, groundYBias: 0.00001, createSkybox: true, skyboxSize: 20, skyboxTexture: this._skyboxTextureCDNUrl, skyboxColor: new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"](0.2, 0.2, 0.3).toLinearSpace().scale(3), backgroundYRotation: 0, sizeAuto: true, rootPosition: _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), setupImageProcessing: true, environmentTexture: this._environmentTextureCDNUrl, cameraExposure: 0.8, cameraContrast: 1.2, toneMappingEnabled: true, }; }; Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", { /** * Gets the root mesh created by the helper. */ get: function () { return this._rootMesh; }, enumerable: true, configurable: true }); Object.defineProperty(EnvironmentHelper.prototype, "skybox", { /** * Gets the skybox created by the helper. */ get: function () { return this._skybox; }, enumerable: true, configurable: true }); Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", { /** * Gets the skybox texture created by the helper. */ get: function () { return this._skyboxTexture; }, enumerable: true, configurable: true }); Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", { /** * Gets the skybox material created by the helper. */ get: function () { return this._skyboxMaterial; }, enumerable: true, configurable: true }); Object.defineProperty(EnvironmentHelper.prototype, "ground", { /** * Gets the ground mesh created by the helper. */ get: function () { return this._ground; }, enumerable: true, configurable: true }); Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", { /** * Gets the ground texture created by the helper. */ get: function () { return this._groundTexture; }, enumerable: true, configurable: true }); Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", { /** * Gets the ground mirror created by the helper. */ get: function () { return this._groundMirror; }, enumerable: true, configurable: true }); Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", { /** * Gets the ground mirror render list to helps pushing the meshes * you wish in the ground reflection. */ get: function () { if (this._groundMirror) { return this._groundMirror.renderList; } return null; }, enumerable: true, configurable: true }); Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", { /** * Gets the ground material created by the helper. */ get: function () { return this._groundMaterial; }, enumerable: true, configurable: true }); /** * Updates the background according to the new options * @param options */ EnvironmentHelper.prototype.updateOptions = function (options) { var newOptions = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({}, this._options, options); if (this._ground && !newOptions.createGround) { this._ground.dispose(); this._ground = null; } if (this._groundMaterial && !newOptions.createGround) { this._groundMaterial.dispose(); this._groundMaterial = null; } if (this._groundTexture) { if (this._options.groundTexture != newOptions.groundTexture) { this._groundTexture.dispose(); this._groundTexture = null; } } if (this._skybox && !newOptions.createSkybox) { this._skybox.dispose(); this._skybox = null; } if (this._skyboxMaterial && !newOptions.createSkybox) { this._skyboxMaterial.dispose(); this._skyboxMaterial = null; } if (this._skyboxTexture) { if (this._options.skyboxTexture != newOptions.skyboxTexture) { this._skyboxTexture.dispose(); this._skyboxTexture = null; } } if (this._groundMirror && !newOptions.enableGroundMirror) { this._groundMirror.dispose(); this._groundMirror = null; } if (this._scene.environmentTexture) { if (this._options.environmentTexture != newOptions.environmentTexture) { this._scene.environmentTexture.dispose(); } } this._options = newOptions; this._setupBackground(); this._setupImageProcessing(); }; /** * Sets the primary color of all the available elements. * @param color the main color to affect to the ground and the background */ EnvironmentHelper.prototype.setMainColor = function (color) { if (this.groundMaterial) { this.groundMaterial.primaryColor = color; } if (this.skyboxMaterial) { this.skyboxMaterial.primaryColor = color; } if (this.groundMirror) { this.groundMirror.clearColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color4"](color.r, color.g, color.b, 1.0); } }; /** * Setup the image processing according to the specified options. */ EnvironmentHelper.prototype._setupImageProcessing = function () { if (this._options.setupImageProcessing) { this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast; this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure; this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled; this._setupEnvironmentTexture(); } }; /** * Setup the environment texture according to the specified options. */ EnvironmentHelper.prototype._setupEnvironmentTexture = function () { if (this._scene.environmentTexture) { return; } if (this._options.environmentTexture instanceof _Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_5__["BaseTexture"]) { this._scene.environmentTexture = this._options.environmentTexture; return; } var environmentTexture = _Materials_Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_8__["CubeTexture"].CreateFromPrefilteredData(this._options.environmentTexture, this._scene); this._scene.environmentTexture = environmentTexture; }; /** * Setup the background according to the specified options. */ EnvironmentHelper.prototype._setupBackground = function () { if (!this._rootMesh) { this._rootMesh = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"]("BackgroundHelper", this._scene); } this._rootMesh.rotation.y = this._options.backgroundYRotation; var sceneSize = this._getSceneSize(); if (this._options.createGround) { this._setupGround(sceneSize); this._setupGroundMaterial(); this._setupGroundDiffuseTexture(); if (this._options.enableGroundMirror) { this._setupGroundMirrorTexture(sceneSize); } this._setupMirrorInGroundMaterial(); } if (this._options.createSkybox) { this._setupSkybox(sceneSize); this._setupSkyboxMaterial(); this._setupSkyboxReflectionTexture(); } this._rootMesh.position.x = sceneSize.rootPosition.x; this._rootMesh.position.z = sceneSize.rootPosition.z; this._rootMesh.position.y = sceneSize.rootPosition.y; }; /** * Get the scene sizes according to the setup. */ EnvironmentHelper.prototype._getSceneSize = function () { var _this = this; var groundSize = this._options.groundSize; var skyboxSize = this._options.skyboxSize; var rootPosition = this._options.rootPosition; if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition }; } var sceneExtends = this._scene.getWorldExtends(function (mesh) { return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox); }); var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min); if (this._options.sizeAuto) { if (this._scene.activeCamera instanceof _Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_2__["ArcRotateCamera"] && this._scene.activeCamera.upperRadiusLimit) { groundSize = this._scene.activeCamera.upperRadiusLimit * 2; skyboxSize = groundSize; } var sceneDiagonalLenght = sceneDiagonal.length(); if (sceneDiagonalLenght > groundSize) { groundSize = sceneDiagonalLenght * 2; skyboxSize = groundSize; } // 10 % bigger. groundSize *= 1.1; skyboxSize *= 1.5; rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5)); rootPosition.y = sceneExtends.min.y - this._options.groundYBias; } return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition }; }; /** * Setup the ground according to the specified options. */ EnvironmentHelper.prototype._setupGround = function (sceneSize) { var _this = this; if (!this._ground || this._ground.isDisposed()) { this._ground = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"].CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene); this._ground.rotation.x = Math.PI / 2; // Face up by default. this._ground.parent = this._rootMesh; this._ground.onDisposeObservable.add(function () { _this._ground = null; }); } this._ground.receiveShadows = this._options.enableGroundShadow; }; /** * Setup the ground material according to the specified options. */ EnvironmentHelper.prototype._setupGroundMaterial = function () { if (!this._groundMaterial) { this._groundMaterial = new _Materials_Background_backgroundMaterial__WEBPACK_IMPORTED_MODULE_9__["BackgroundMaterial"]("BackgroundPlaneMaterial", this._scene); } this._groundMaterial.alpha = this._options.groundOpacity; this._groundMaterial.alphaMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ALPHA_PREMULTIPLIED_PORTERDUFF; this._groundMaterial.shadowLevel = this._options.groundShadowLevel; this._groundMaterial.primaryColor = this._options.groundColor; this._groundMaterial.useRGBColor = false; this._groundMaterial.enableNoise = true; if (this._ground) { this._ground.material = this._groundMaterial; } }; /** * Setup the ground diffuse texture according to the specified options. */ EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () { if (!this._groundMaterial) { return; } if (this._groundTexture) { return; } if (this._options.groundTexture instanceof _Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_5__["BaseTexture"]) { this._groundMaterial.diffuseTexture = this._options.groundTexture; return; } var diffuseTexture = new _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"](this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler); diffuseTexture.gammaSpace = false; diffuseTexture.hasAlpha = true; this._groundMaterial.diffuseTexture = diffuseTexture; }; /** * Setup the ground mirror texture according to the specified options. */ EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) { var wrapping = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].CLAMP_ADDRESSMODE; if (!this._groundMirror) { this._groundMirror = new _Materials_Textures_mirrorTexture__WEBPACK_IMPORTED_MODULE_7__["MirrorTexture"]("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].BILINEAR_SAMPLINGMODE, true); this._groundMirror.mirrorPlane = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Plane"](0, -1, 0, sceneSize.rootPosition.y); this._groundMirror.anisotropicFilteringLevel = 1; this._groundMirror.wrapU = wrapping; this._groundMirror.wrapV = wrapping; this._groundMirror.gammaSpace = false; if (this._groundMirror.renderList) { for (var i = 0; i < this._scene.meshes.length; i++) { var mesh = this._scene.meshes[i]; if (mesh !== this._ground && mesh !== this._skybox && mesh !== this._rootMesh) { this._groundMirror.renderList.push(mesh); } } } } this._groundMirror.clearColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color4"](this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1); this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel; }; /** * Setup the ground to receive the mirror texture. */ EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () { if (this._groundMaterial) { this._groundMaterial.reflectionTexture = this._groundMirror; this._groundMaterial.reflectionFresnel = true; this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount; this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight; this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance; } }; /** * Setup the skybox according to the specified options. */ EnvironmentHelper.prototype._setupSkybox = function (sceneSize) { var _this = this; if (!this._skybox || this._skybox.isDisposed()) { this._skybox = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"].CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"].BACKSIDE); this._skybox.onDisposeObservable.add(function () { _this._skybox = null; }); } this._skybox.parent = this._rootMesh; }; /** * Setup the skybox material according to the specified options. */ EnvironmentHelper.prototype._setupSkyboxMaterial = function () { if (!this._skybox) { return; } if (!this._skyboxMaterial) { this._skyboxMaterial = new _Materials_Background_backgroundMaterial__WEBPACK_IMPORTED_MODULE_9__["BackgroundMaterial"]("BackgroundSkyboxMaterial", this._scene); } this._skyboxMaterial.useRGBColor = false; this._skyboxMaterial.primaryColor = this._options.skyboxColor; this._skyboxMaterial.enableNoise = true; this._skybox.material = this._skyboxMaterial; }; /** * Setup the skybox reflection texture according to the specified options. */ EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () { if (!this._skyboxMaterial) { return; } if (this._skyboxTexture) { return; } if (this._options.skyboxTexture instanceof _Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_5__["BaseTexture"]) { this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture; return; } this._skyboxTexture = new _Materials_Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_8__["CubeTexture"](this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler); this._skyboxTexture.coordinatesMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].SKYBOX_MODE; this._skyboxTexture.gammaSpace = false; this._skyboxMaterial.reflectionTexture = this._skyboxTexture; }; /** * Dispose all the elements created by the Helper. */ EnvironmentHelper.prototype.dispose = function () { if (this._groundMaterial) { this._groundMaterial.dispose(true, true); } if (this._skyboxMaterial) { this._skyboxMaterial.dispose(true, true); } this._rootMesh.dispose(false); }; /** * Default ground texture URL. */ EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png"; /** * Default skybox texture URL. */ EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds"; /** * Default environment texture URL. */ EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env"; return EnvironmentHelper; }()); /***/ }), /***/ "./Helpers/index.ts": /*!**************************!*\ !*** ./Helpers/index.ts ***! \**************************/ /*! exports provided: EnvironmentHelper, PhotoDome, _forceSceneHelpersToBundle, VideoDome */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _environmentHelper__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./environmentHelper */ "./Helpers/environmentHelper.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EnvironmentHelper", function() { return _environmentHelper__WEBPACK_IMPORTED_MODULE_0__["EnvironmentHelper"]; }); /* harmony import */ var _photoDome__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./photoDome */ "./Helpers/photoDome.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhotoDome", function() { return _photoDome__WEBPACK_IMPORTED_MODULE_1__["PhotoDome"]; }); /* harmony import */ var _sceneHelpers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./sceneHelpers */ "./Helpers/sceneHelpers.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_forceSceneHelpersToBundle", function() { return _sceneHelpers__WEBPACK_IMPORTED_MODULE_2__["_forceSceneHelpersToBundle"]; }); /* harmony import */ var _videoDome__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./videoDome */ "./Helpers/videoDome.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VideoDome", function() { return _videoDome__WEBPACK_IMPORTED_MODULE_3__["VideoDome"]; }); /***/ }), /***/ "./Helpers/photoDome.ts": /*!******************************!*\ !*** ./Helpers/photoDome.ts ***! \******************************/ /*! exports provided: PhotoDome */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PhotoDome", function() { return PhotoDome; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Meshes/transformNode */ "./Meshes/transformNode.ts"); /* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts"); /* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); /* harmony import */ var _Materials_Background_backgroundMaterial__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Materials/Background/backgroundMaterial */ "./Materials/Background/backgroundMaterial.ts"); /* harmony import */ var _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Meshes/Builders/sphereBuilder */ "./Meshes/Builders/sphereBuilder.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /** * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere. * Potential additions to this helper include zoom and and non-infinite distance rendering effects. */ var PhotoDome = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PhotoDome, _super); /** * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh. * @param name Element's name, child elements will append suffixes for their own names. * @param urlsOfPhoto defines the url of the photo to display * @param options defines an object containing optional or exposed sub element properties * @param onError defines a callback called when an error occured while loading the texture */ function PhotoDome(name, urlOfPhoto, options, scene, onError) { if (onError === void 0) { onError = null; } var _this = _super.call(this, name, scene) || this; _this._useDirectMapping = false; /** * Observable raised when an error occured while loading the 360 image */ _this.onLoadErrorObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); // set defaults and manage values name = name || "photoDome"; options.resolution = (Math.abs(options.resolution) | 0) || 32; options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000); if (options.useDirectMapping === undefined) { _this._useDirectMapping = true; } else { _this._useDirectMapping = options.useDirectMapping; } if (options.faceForward === undefined) { options.faceForward = true; } _this._setReady(false); // create var material = _this._material = new _Materials_Background_backgroundMaterial__WEBPACK_IMPORTED_MODULE_5__["BackgroundMaterial"](name + "_material", scene); _this._mesh = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"].CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"].BACKSIDE); // configure material material.opacityFresnel = false; material.useEquirectangularFOV = true; material.fovMultiplier = 1.0; _this.photoTexture = new _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"](urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) { _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured"); if (onError) { onError(message, exception); } }); _this.photoTexture.onLoadObservable.addOnce(function () { _this._setReady(true); }); // configure mesh _this._mesh.material = material; _this._mesh.parent = _this; // Initial rotation if (options.faceForward && scene.activeCamera) { var camera = scene.activeCamera; var forward = _Maths_math__WEBPACK_IMPORTED_MODULE_7__["Vector3"].Forward(); var direction = _Maths_math__WEBPACK_IMPORTED_MODULE_7__["Vector3"].TransformNormal(forward, camera.getViewMatrix()); direction.normalize(); _this.rotation.y = Math.acos(_Maths_math__WEBPACK_IMPORTED_MODULE_7__["Vector3"].Dot(forward, direction)); } return _this; } Object.defineProperty(PhotoDome.prototype, "photoTexture", { /** * Gets or sets the texture being displayed on the sphere */ get: function () { return this._photoTexture; }, set: function (value) { if (this._photoTexture === value) { return; } this._photoTexture = value; if (this._useDirectMapping) { this._photoTexture.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].CLAMP_ADDRESSMODE; this._photoTexture.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].CLAMP_ADDRESSMODE; this._material.diffuseTexture = this._photoTexture; } else { this._photoTexture.coordinatesMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation this._photoTexture.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].CLAMP_ADDRESSMODE; this._material.reflectionTexture = this._photoTexture; } }, enumerable: true, configurable: true }); Object.defineProperty(PhotoDome.prototype, "fovMultiplier", { /** * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out". * Also see the options.resolution property. */ get: function () { return this._material.fovMultiplier; }, set: function (value) { this._material.fovMultiplier = value; }, enumerable: true, configurable: 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) */ PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) { if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; } this._photoTexture.dispose(); this._mesh.dispose(); this._material.dispose(); this.onLoadErrorObservable.clear(); _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures); }; return PhotoDome; }(_Meshes_transformNode__WEBPACK_IMPORTED_MODULE_2__["TransformNode"])); /***/ }), /***/ "./Helpers/sceneHelpers.ts": /*!*********************************!*\ !*** ./Helpers/sceneHelpers.ts ***! \*********************************/ /*! exports provided: _forceSceneHelpersToBundle */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_forceSceneHelpersToBundle", function() { return _forceSceneHelpersToBundle; }); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../scene */ "./scene.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts"); /* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); /* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts"); /* harmony import */ var _Materials_PBR_pbrMaterial__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Materials/PBR/pbrMaterial */ "./Materials/PBR/pbrMaterial.ts"); /* harmony import */ var _Lights_hemisphericLight__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Lights/hemisphericLight */ "./Lights/hemisphericLight.ts"); /* harmony import */ var _environmentHelper__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./environmentHelper */ "./Helpers/environmentHelper.ts"); /* harmony import */ var _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Cameras/freeCamera */ "./Cameras/freeCamera.ts"); /* harmony import */ var _Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Cameras/arcRotateCamera */ "./Cameras/arcRotateCamera.ts"); /* harmony import */ var _Cameras_XR_webXRManagedOutputCanvas__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Cameras/XR/webXRManagedOutputCanvas */ "./Cameras/XR/webXRManagedOutputCanvas.ts"); /* harmony import */ var _Cameras_XR_webXRInput__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Cameras/XR/webXRInput */ "./Cameras/XR/webXRInput.ts"); /* harmony import */ var _Cameras_XR_webXREnterExitUI__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Cameras/XR/webXREnterExitUI */ "./Cameras/XR/webXREnterExitUI.ts"); /* harmony import */ var _Cameras_XR_webXRExperienceHelper__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../Cameras/XR/webXRExperienceHelper */ "./Cameras/XR/webXRExperienceHelper.ts"); /* harmony import */ var _Cameras_VR_vrExperienceHelper__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../Cameras/VR/vrExperienceHelper */ "./Cameras/VR/vrExperienceHelper.ts"); /* harmony import */ var _Materials_Textures_Loaders_ddsTextureLoader__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../Materials/Textures/Loaders/ddsTextureLoader */ "./Materials/Textures/Loaders/ddsTextureLoader.ts"); /* harmony import */ var _Materials_Textures_Loaders_envTextureLoader__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../Materials/Textures/Loaders/envTextureLoader */ "./Materials/Textures/Loaders/envTextureLoader.ts"); /* harmony import */ var _Materials_Textures_Loaders_ktxTextureLoader__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../Materials/Textures/Loaders/ktxTextureLoader */ "./Materials/Textures/Loaders/ktxTextureLoader.ts"); /* harmony import */ var _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../Meshes/Builders/boxBuilder */ "./Meshes/Builders/boxBuilder.ts"); /** @hidden */ var _forceSceneHelpersToBundle = true; _scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].prototype.createDefaultLight = function (replace) { if (replace === void 0) { replace = false; } // Dispose existing light in replace mode. if (replace) { if (this.lights) { for (var i = 0; i < this.lights.length; i++) { this.lights[i].dispose(); } } } // Light if (this.lights.length === 0) { new _Lights_hemisphericLight__WEBPACK_IMPORTED_MODULE_7__["HemisphericLight"]("default light", _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Up(), this); } }; _scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) { if (createArcRotateCamera === void 0) { createArcRotateCamera = false; } if (replace === void 0) { replace = false; } if (attachCameraControls === void 0) { attachCameraControls = false; } // Dispose existing camera in replace mode. if (replace) { if (this.activeCamera) { this.activeCamera.dispose(); this.activeCamera = null; } } // Camera if (!this.activeCamera) { var worldExtends = this.getWorldExtends(); var worldSize = worldExtends.max.subtract(worldExtends.min); var worldCenter = worldExtends.min.add(worldSize.scale(0.5)); var camera; var radius = worldSize.length() * 1.5; // empty scene scenario! if (!isFinite(radius)) { radius = 1; worldCenter.copyFromFloats(0, 0, 0); } if (createArcRotateCamera) { var arcRotateCamera = new _Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_10__["ArcRotateCamera"]("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this); arcRotateCamera.lowerRadiusLimit = radius * 0.01; arcRotateCamera.wheelPrecision = 100 / radius; camera = arcRotateCamera; } else { var freeCamera = new _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_9__["FreeCamera"]("default camera", new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](worldCenter.x, worldCenter.y, -radius), this); freeCamera.setTarget(worldCenter); camera = freeCamera; } camera.minZ = radius * 0.01; camera.maxZ = radius * 1000; camera.speed = radius * 0.2; this.activeCamera = camera; var canvas = this.getEngine().getRenderingCanvas(); if (attachCameraControls && canvas) { camera.attachControl(canvas); } } }; _scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) { if (createArcRotateCamera === void 0) { createArcRotateCamera = false; } if (replace === void 0) { replace = false; } if (attachCameraControls === void 0) { attachCameraControls = false; } this.createDefaultLight(replace); this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls); }; _scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) { if (pbr === void 0) { pbr = false; } if (scale === void 0) { scale = 1000; } if (blur === void 0) { blur = 0; } if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; } if (!environmentTexture) { _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Warn("Can not create default skybox without environment texture."); return null; } if (setGlobalEnvTexture) { if (environmentTexture) { this.environmentTexture = environmentTexture; } } // Skybox var hdrSkybox = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"].CreateBox("hdrSkyBox", scale, this); if (pbr) { var hdrSkyboxMaterial = new _Materials_PBR_pbrMaterial__WEBPACK_IMPORTED_MODULE_6__["PBRMaterial"]("skyBox", this); hdrSkyboxMaterial.backFaceCulling = false; hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone(); if (hdrSkyboxMaterial.reflectionTexture) { hdrSkyboxMaterial.reflectionTexture.coordinatesMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].SKYBOX_MODE; } hdrSkyboxMaterial.microSurface = 1.0 - blur; hdrSkyboxMaterial.disableLighting = true; hdrSkyboxMaterial.twoSidedLighting = true; hdrSkybox.infiniteDistance = true; hdrSkybox.material = hdrSkyboxMaterial; } else { var skyboxMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_5__["StandardMaterial"]("skyBox", this); skyboxMaterial.backFaceCulling = false; skyboxMaterial.reflectionTexture = environmentTexture.clone(); if (skyboxMaterial.reflectionTexture) { skyboxMaterial.reflectionTexture.coordinatesMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].SKYBOX_MODE; } skyboxMaterial.disableLighting = true; hdrSkybox.infiniteDistance = true; hdrSkybox.material = skyboxMaterial; } hdrSkybox.isPickable = false; return hdrSkybox; }; _scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].prototype.createDefaultEnvironment = function (options) { if (_environmentHelper__WEBPACK_IMPORTED_MODULE_8__["EnvironmentHelper"]) { return new _environmentHelper__WEBPACK_IMPORTED_MODULE_8__["EnvironmentHelper"](options, this); } return null; }; _scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].prototype.createDefaultVRExperience = function (webVROptions) { if (webVROptions === void 0) { webVROptions = {}; } return new _Cameras_VR_vrExperienceHelper__WEBPACK_IMPORTED_MODULE_15__["VRExperienceHelper"](this, webVROptions); }; _scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].prototype.createDefaultXRExperienceAsync = function () { var _this = this; return _Cameras_XR_webXRExperienceHelper__WEBPACK_IMPORTED_MODULE_14__["WebXRExperienceHelper"].CreateAsync(this).then(function (helper) { var outputCanvas = new _Cameras_XR_webXRManagedOutputCanvas__WEBPACK_IMPORTED_MODULE_11__["WebXRManagedOutputCanvas"](helper); return _Cameras_XR_webXREnterExitUI__WEBPACK_IMPORTED_MODULE_13__["WebXREnterExitUI"].CreateAsync(_this, helper, { outputCanvasContext: outputCanvas.canvasContext }) .then(function (ui) { new _Cameras_XR_webXRInput__WEBPACK_IMPORTED_MODULE_12__["WebXRInput"](helper); return helper; }); }); }; /***/ }), /***/ "./Helpers/videoDome.ts": /*!******************************!*\ !*** ./Helpers/videoDome.ts ***! \******************************/ /*! exports provided: VideoDome */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VideoDome", function() { return VideoDome; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Meshes/transformNode */ "./Meshes/transformNode.ts"); /* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts"); /* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); /* harmony import */ var _Materials_Textures_videoTexture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Materials/Textures/videoTexture */ "./Materials/Textures/videoTexture.ts"); /* harmony import */ var _Materials_Background_backgroundMaterial__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Materials/Background/backgroundMaterial */ "./Materials/Background/backgroundMaterial.ts"); /* harmony import */ var _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Meshes/Builders/sphereBuilder */ "./Meshes/Builders/sphereBuilder.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /** * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere. * Potential additions to this helper include zoom and and non-infinite distance rendering effects. */ var VideoDome = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](VideoDome, _super); /** * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh. * @param name Element's name, child elements will append suffixes for their own names. * @param urlsOrVideo defines the url(s) or the video element to use * @param options An object containing optional or exposed sub element properties */ function VideoDome(name, urlsOrVideo, options, scene) { var _this = _super.call(this, name, scene) || this; _this._useDirectMapping = false; _this._videoMode = VideoDome.MODE_MONOSCOPIC; /** * Oberserver used in Stereoscopic VR Mode. */ _this._onBeforeCameraRenderObserver = null; scene = _this.getScene(); // set defaults and manage values name = name || "videoDome"; options.resolution = (Math.abs(options.resolution) | 0) || 32; options.clickToPlay = Boolean(options.clickToPlay); options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay); options.loop = options.loop === undefined ? true : Boolean(options.loop); options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000); if (options.useDirectMapping === undefined) { _this._useDirectMapping = true; } else { _this._useDirectMapping = options.useDirectMapping; } if (options.faceForward === undefined) { options.faceForward = true; } _this._setReady(false); // create var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster }; var material = _this._material = new _Materials_Background_backgroundMaterial__WEBPACK_IMPORTED_MODULE_5__["BackgroundMaterial"](name + "_material", scene); var texture = _this._videoTexture = new _Materials_Textures_videoTexture__WEBPACK_IMPORTED_MODULE_4__["VideoTexture"](name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__["Texture"].TRILINEAR_SAMPLINGMODE, tempOptions); _this._mesh = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_2__["Mesh"].CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, _Meshes_mesh__WEBPACK_IMPORTED_MODULE_2__["Mesh"].BACKSIDE); texture.onLoadObservable.addOnce(function () { _this._setReady(true); }); // configure material material.useEquirectangularFOV = true; material.fovMultiplier = 1.0; material.opacityFresnel = false; if (_this._useDirectMapping) { texture.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__["Texture"].CLAMP_ADDRESSMODE; texture.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__["Texture"].CLAMP_ADDRESSMODE; material.diffuseTexture = texture; } else { texture.coordinatesMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__["Texture"].FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation texture.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__["Texture"].CLAMP_ADDRESSMODE; material.reflectionTexture = texture; } // configure mesh _this._mesh.material = material; _this._mesh.parent = _this; // optional configuration if (options.clickToPlay) { scene.onPointerUp = function () { _this._videoTexture.video.play(); }; } // Initial rotation if (options.faceForward && scene.activeCamera) { var camera = scene.activeCamera; var forward = _Maths_math__WEBPACK_IMPORTED_MODULE_7__["Vector3"].Forward(); var direction = _Maths_math__WEBPACK_IMPORTED_MODULE_7__["Vector3"].TransformNormal(forward, camera.getViewMatrix()); direction.normalize(); _this.rotation.y = Math.acos(_Maths_math__WEBPACK_IMPORTED_MODULE_7__["Vector3"].Dot(forward, direction)); } return _this; } Object.defineProperty(VideoDome.prototype, "videoTexture", { /** * Gets the video texture being displayed on the sphere */ get: function () { return this._videoTexture; }, enumerable: true, configurable: true }); Object.defineProperty(VideoDome.prototype, "fovMultiplier", { /** * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out". * Also see the options.resolution property. */ get: function () { return this._material.fovMultiplier; }, set: function (value) { this._material.fovMultiplier = value; }, enumerable: true, configurable: true }); Object.defineProperty(VideoDome.prototype, "videoMode", { /** * Gets or set the current video mode for the video. It can be: * * VideoDome.MODE_MONOSCOPIC : Define the video source as a Monoscopic panoramic 360 video. * * VideoDome.MODE_TOPBOTTOM : Define the video source as a Stereoscopic TopBottom/OverUnder panoramic 360 video. * * VideoDome.MODE_SIDEBYSIDE : Define the video source as a Stereoscopic Side by Side panoramic 360 video. */ get: function () { return this._videoMode; }, set: function (value) { if (this._videoMode === value) { return; } this._changeVideoMode(value); }, enumerable: true, configurable: true }); VideoDome.prototype._changeVideoMode = function (value) { var _this = this; this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver); this._videoMode = value; // Default Setup and Reset. this._videoTexture.uScale = 1; this._videoTexture.vScale = 1; this._videoTexture.uOffset = 0; this._videoTexture.vOffset = 0; switch (value) { case VideoDome.MODE_SIDEBYSIDE: this._videoTexture.uScale = 0.5; this._onBeforeCameraRenderObserver = this._scene.onBeforeCameraRenderObservable.add(function (camera) { _this._videoTexture.uOffset = camera.isRightCamera ? 0.5 : 0.0; }); break; case VideoDome.MODE_TOPBOTTOM: this._videoTexture.vScale = 0.5; this._onBeforeCameraRenderObserver = this._scene.onBeforeCameraRenderObservable.add(function (camera) { _this._videoTexture.vOffset = camera.isRightCamera ? 0.5 : 0.0; }); break; } }; /** * 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) */ VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) { if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; } this._videoTexture.dispose(); this._mesh.dispose(); this._material.dispose(); this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver); _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures); }; /** * Define the video source as a Monoscopic panoramic 360 video. */ VideoDome.MODE_MONOSCOPIC = 0; /** * Define the video source as a Stereoscopic TopBottom/OverUnder panoramic 360 video. */ VideoDome.MODE_TOPBOTTOM = 1; /** * Define the video source as a Stereoscopic Side by Side panoramic 360 video. */ VideoDome.MODE_SIDEBYSIDE = 2; return VideoDome; }(_Meshes_transformNode__WEBPACK_IMPORTED_MODULE_1__["TransformNode"])); /***/ }), /***/ "./Instrumentation/engineInstrumentation.ts": /*!**************************************************!*\ !*** ./Instrumentation/engineInstrumentation.ts ***! \**************************************************/ /*! exports provided: EngineInstrumentation */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EngineInstrumentation", function() { return EngineInstrumentation; }); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); /** * This class can be used to get instrumentation data from a Babylon engine * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation */ var EngineInstrumentation = /** @class */ (function () { /** * Instantiates a new engine instrumentation. * This class can be used to get instrumentation data from a Babylon engine * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation * @param engine Defines the engine to instrument */ function EngineInstrumentation( /** * Define the instrumented engine. */ engine) { this.engine = engine; this._captureGPUFrameTime = false; this._gpuFrameTime = new _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"](); this._captureShaderCompilationTime = false; this._shaderCompilationTime = new _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"](); // Observers this._onBeginFrameObserver = null; this._onEndFrameObserver = null; this._onBeforeShaderCompilationObserver = null; this._onAfterShaderCompilationObserver = null; } Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", { // Properties /** * Gets the perf counter used for GPU frame time */ get: function () { return this._gpuFrameTime; }, enumerable: true, configurable: true }); Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", { /** * Gets the GPU frame time capture status */ get: function () { return this._captureGPUFrameTime; }, /** * Enable or disable the GPU frame time capture */ set: function (value) { var _this = this; if (value === this._captureGPUFrameTime) { return; } this._captureGPUFrameTime = value; if (value) { this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () { if (!_this._gpuFrameTimeToken) { _this._gpuFrameTimeToken = _this.engine.startTimeQuery(); } }); this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () { if (!_this._gpuFrameTimeToken) { return; } var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken); if (time > -1) { _this._gpuFrameTimeToken = null; _this._gpuFrameTime.fetchNewFrame(); _this._gpuFrameTime.addCount(time, true); } }); } else { this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver); this._onBeginFrameObserver = null; this.engine.onEndFrameObservable.remove(this._onEndFrameObserver); this._onEndFrameObserver = null; } }, enumerable: true, configurable: true }); Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", { /** * Gets the perf counter used for shader compilation time */ get: function () { return this._shaderCompilationTime; }, enumerable: true, configurable: true }); Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", { /** * Gets the shader compilation time capture status */ get: function () { return this._captureShaderCompilationTime; }, /** * Enable or disable the shader compilation time capture */ set: function (value) { var _this = this; if (value === this._captureShaderCompilationTime) { return; } this._captureShaderCompilationTime = value; if (value) { this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () { _this._shaderCompilationTime.fetchNewFrame(); _this._shaderCompilationTime.beginMonitoring(); }); this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () { _this._shaderCompilationTime.endMonitoring(); }); } else { this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver); this._onBeforeShaderCompilationObserver = null; this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver); this._onAfterShaderCompilationObserver = null; } }, enumerable: true, configurable: true }); /** * Dispose and release associated resources. */ EngineInstrumentation.prototype.dispose = function () { this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver); this._onBeginFrameObserver = null; this.engine.onEndFrameObservable.remove(this._onEndFrameObserver); this._onEndFrameObserver = null; this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver); this._onBeforeShaderCompilationObserver = null; this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver); this._onAfterShaderCompilationObserver = null; this.engine = null; }; return EngineInstrumentation; }()); /***/ }), /***/ "./Instrumentation/index.ts": /*!**********************************!*\ !*** ./Instrumentation/index.ts ***! \**********************************/ /*! exports provided: EngineInstrumentation, SceneInstrumentation, _TimeToken */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _engineInstrumentation__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./engineInstrumentation */ "./Instrumentation/engineInstrumentation.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EngineInstrumentation", function() { return _engineInstrumentation__WEBPACK_IMPORTED_MODULE_0__["EngineInstrumentation"]; }); /* harmony import */ var _sceneInstrumentation__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./sceneInstrumentation */ "./Instrumentation/sceneInstrumentation.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneInstrumentation", function() { return _sceneInstrumentation__WEBPACK_IMPORTED_MODULE_1__["SceneInstrumentation"]; }); /* harmony import */ var _timeToken__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./timeToken */ "./Instrumentation/timeToken.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_TimeToken", function() { return _timeToken__WEBPACK_IMPORTED_MODULE_2__["_TimeToken"]; }); /***/ }), /***/ "./Instrumentation/sceneInstrumentation.ts": /*!*************************************************!*\ !*** ./Instrumentation/sceneInstrumentation.ts ***! \*************************************************/ /*! exports provided: SceneInstrumentation */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SceneInstrumentation", function() { return SceneInstrumentation; }); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); /** * This class can be used to get instrumentation data from a Babylon engine * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation */ var SceneInstrumentation = /** @class */ (function () { /** * Instantiates a new scene instrumentation. * This class can be used to get instrumentation data from a Babylon engine * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation * @param scene Defines the scene to instrument */ function SceneInstrumentation( /** * Defines the scene to instrument */ scene) { var _this = this; this.scene = scene; this._captureActiveMeshesEvaluationTime = false; this._activeMeshesEvaluationTime = new _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"](); this._captureRenderTargetsRenderTime = false; this._renderTargetsRenderTime = new _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"](); this._captureFrameTime = false; this._frameTime = new _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"](); this._captureRenderTime = false; this._renderTime = new _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"](); this._captureInterFrameTime = false; this._interFrameTime = new _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"](); this._captureParticlesRenderTime = false; this._particlesRenderTime = new _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"](); this._captureSpritesRenderTime = false; this._spritesRenderTime = new _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"](); this._capturePhysicsTime = false; this._physicsTime = new _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"](); this._captureAnimationsTime = false; this._animationsTime = new _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"](); this._captureCameraRenderTime = false; this._cameraRenderTime = new _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"](); // Observers this._onBeforeActiveMeshesEvaluationObserver = null; this._onAfterActiveMeshesEvaluationObserver = null; this._onBeforeRenderTargetsRenderObserver = null; this._onAfterRenderTargetsRenderObserver = null; this._onAfterRenderObserver = null; this._onBeforeDrawPhaseObserver = null; this._onAfterDrawPhaseObserver = null; this._onBeforeAnimationsObserver = null; this._onBeforeParticlesRenderingObserver = null; this._onAfterParticlesRenderingObserver = null; this._onBeforeSpritesRenderingObserver = null; this._onAfterSpritesRenderingObserver = null; this._onBeforePhysicsObserver = null; this._onAfterPhysicsObserver = null; this._onAfterAnimationsObserver = null; this._onBeforeCameraRenderObserver = null; this._onAfterCameraRenderObserver = null; // Before render this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () { if (_this._captureActiveMeshesEvaluationTime) { _this._activeMeshesEvaluationTime.fetchNewFrame(); } if (_this._captureRenderTargetsRenderTime) { _this._renderTargetsRenderTime.fetchNewFrame(); } if (_this._captureFrameTime) { _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Scene rendering"); _this._frameTime.beginMonitoring(); } if (_this._captureInterFrameTime) { _this._interFrameTime.endMonitoring(); } if (_this._captureParticlesRenderTime) { _this._particlesRenderTime.fetchNewFrame(); } if (_this._captureSpritesRenderTime) { _this._spritesRenderTime.fetchNewFrame(); } if (_this._captureAnimationsTime) { _this._animationsTime.beginMonitoring(); } _this.scene.getEngine()._drawCalls.fetchNewFrame(); }); // After render this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () { if (_this._captureFrameTime) { _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Scene rendering"); _this._frameTime.endMonitoring(); } if (_this._captureRenderTime) { _this._renderTime.endMonitoring(false); } if (_this._captureInterFrameTime) { _this._interFrameTime.beginMonitoring(); } }); } Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", { // Properties /** * Gets the perf counter used for active meshes evaluation time */ get: function () { return this._activeMeshesEvaluationTime; }, enumerable: true, configurable: true }); Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", { /** * Gets the active meshes evaluation time capture status */ get: function () { return this._captureActiveMeshesEvaluationTime; }, /** * Enable or disable the active meshes evaluation time capture */ set: function (value) { var _this = this; if (value === this._captureActiveMeshesEvaluationTime) { return; } this._captureActiveMeshesEvaluationTime = value; if (value) { this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () { _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Active meshes evaluation"); _this._activeMeshesEvaluationTime.beginMonitoring(); }); this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () { _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Active meshes evaluation"); _this._activeMeshesEvaluationTime.endMonitoring(); }); } else { this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver); this._onBeforeActiveMeshesEvaluationObserver = null; this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver); this._onAfterActiveMeshesEvaluationObserver = null; } }, enumerable: true, configurable: true }); Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", { /** * Gets the perf counter used for render targets render time */ get: function () { return this._renderTargetsRenderTime; }, enumerable: true, configurable: true }); Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", { /** * Gets the render targets render time capture status */ get: function () { return this._captureRenderTargetsRenderTime; }, /** * Enable or disable the render targets render time capture */ set: function (value) { var _this = this; if (value === this._captureRenderTargetsRenderTime) { return; } this._captureRenderTargetsRenderTime = value; if (value) { this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () { _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Render targets rendering"); _this._renderTargetsRenderTime.beginMonitoring(); }); this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () { _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Render targets rendering"); _this._renderTargetsRenderTime.endMonitoring(false); }); } else { this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver); this._onBeforeRenderTargetsRenderObserver = null; this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver); this._onAfterRenderTargetsRenderObserver = null; } }, enumerable: true, configurable: true }); Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", { /** * Gets the perf counter used for particles render time */ get: function () { return this._particlesRenderTime; }, enumerable: true, configurable: true }); Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", { /** * Gets the particles render time capture status */ get: function () { return this._captureParticlesRenderTime; }, /** * Enable or disable the particles render time capture */ set: function (value) { var _this = this; if (value === this._captureParticlesRenderTime) { return; } this._captureParticlesRenderTime = value; if (value) { this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () { _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Particles"); _this._particlesRenderTime.beginMonitoring(); }); this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () { _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Particles"); _this._particlesRenderTime.endMonitoring(false); }); } else { this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver); this._onBeforeParticlesRenderingObserver = null; this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver); this._onAfterParticlesRenderingObserver = null; } }, enumerable: true, configurable: true }); Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", { /** * Gets the perf counter used for sprites render time */ get: function () { return this._spritesRenderTime; }, enumerable: true, configurable: true }); Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", { /** * Gets the sprites render time capture status */ get: function () { return this._captureSpritesRenderTime; }, /** * Enable or disable the sprites render time capture */ set: function (value) { var _this = this; if (value === this._captureSpritesRenderTime) { return; } this._captureSpritesRenderTime = value; if (!this.scene.spriteManagers) { return; } if (value) { this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () { _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Sprites"); _this._spritesRenderTime.beginMonitoring(); }); this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () { _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Sprites"); _this._spritesRenderTime.endMonitoring(false); }); } else { this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver); this._onBeforeSpritesRenderingObserver = null; this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver); this._onAfterSpritesRenderingObserver = null; } }, enumerable: true, configurable: true }); Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", { /** * Gets the perf counter used for physics time */ get: function () { return this._physicsTime; }, enumerable: true, configurable: true }); Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", { /** * Gets the physics time capture status */ get: function () { return this._capturePhysicsTime; }, /** * Enable or disable the physics time capture */ set: function (value) { var _this = this; if (value === this._capturePhysicsTime) { return; } if (!this.scene.onBeforePhysicsObservable) { return; } this._capturePhysicsTime = value; if (value) { this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () { _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Physics"); _this._physicsTime.beginMonitoring(); }); this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () { _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Physics"); _this._physicsTime.endMonitoring(); }); } else { this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver); this._onBeforePhysicsObserver = null; this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver); this._onAfterPhysicsObserver = null; } }, enumerable: true, configurable: true }); Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", { /** * Gets the perf counter used for animations time */ get: function () { return this._animationsTime; }, enumerable: true, configurable: true }); Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", { /** * Gets the animations time capture status */ get: function () { return this._captureAnimationsTime; }, /** * Enable or disable the animations time capture */ set: function (value) { var _this = this; if (value === this._captureAnimationsTime) { return; } this._captureAnimationsTime = value; if (value) { this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () { _this._animationsTime.endMonitoring(); }); } else { this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver); this._onAfterAnimationsObserver = null; } }, enumerable: true, configurable: true }); Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", { /** * Gets the perf counter used for frame time capture */ get: function () { return this._frameTime; }, enumerable: true, configurable: true }); Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", { /** * Gets the frame time capture status */ get: function () { return this._captureFrameTime; }, /** * Enable or disable the frame time capture */ set: function (value) { this._captureFrameTime = value; }, enumerable: true, configurable: true }); Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", { /** * Gets the perf counter used for inter-frames time capture */ get: function () { return this._interFrameTime; }, enumerable: true, configurable: true }); Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", { /** * Gets the inter-frames time capture status */ get: function () { return this._captureInterFrameTime; }, /** * Enable or disable the inter-frames time capture */ set: function (value) { this._captureInterFrameTime = value; }, enumerable: true, configurable: true }); Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", { /** * Gets the perf counter used for render time capture */ get: function () { return this._renderTime; }, enumerable: true, configurable: true }); Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", { /** * Gets the render time capture status */ get: function () { return this._captureRenderTime; }, /** * Enable or disable the render time capture */ set: function (value) { var _this = this; if (value === this._captureRenderTime) { return; } this._captureRenderTime = value; if (value) { this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () { _this._renderTime.beginMonitoring(); _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Main render"); }); this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () { _this._renderTime.endMonitoring(false); _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Main render"); }); } else { this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver); this._onBeforeDrawPhaseObserver = null; this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver); this._onAfterDrawPhaseObserver = null; } }, enumerable: true, configurable: true }); Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", { /** * Gets the perf counter used for camera render time capture */ get: function () { return this._cameraRenderTime; }, enumerable: true, configurable: true }); Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", { /** * Gets the camera render time capture status */ get: function () { return this._captureCameraRenderTime; }, /** * Enable or disable the camera render time capture */ set: function (value) { var _this = this; if (value === this._captureCameraRenderTime) { return; } this._captureCameraRenderTime = value; if (value) { this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) { _this._cameraRenderTime.beginMonitoring(); _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Rendering camera " + camera.name); }); this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) { _this._cameraRenderTime.endMonitoring(false); _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Rendering camera " + camera.name); }); } else { this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver); this._onBeforeCameraRenderObserver = null; this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver); this._onAfterCameraRenderObserver = null; } }, enumerable: true, configurable: true }); Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", { /** * Gets the perf counter used for draw calls */ get: function () { return this.scene.getEngine()._drawCalls; }, enumerable: true, configurable: true }); /** * Dispose and release associated resources. */ SceneInstrumentation.prototype.dispose = function () { this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver); this._onAfterRenderObserver = null; this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver); this._onBeforeActiveMeshesEvaluationObserver = null; this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver); this._onAfterActiveMeshesEvaluationObserver = null; this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver); this._onBeforeRenderTargetsRenderObserver = null; this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver); this._onAfterRenderTargetsRenderObserver = null; this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver); this._onBeforeAnimationsObserver = null; this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver); this._onBeforeParticlesRenderingObserver = null; this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver); this._onAfterParticlesRenderingObserver = null; if (this._onBeforeSpritesRenderingObserver) { this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver); this._onBeforeSpritesRenderingObserver = null; } if (this._onAfterSpritesRenderingObserver) { this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver); this._onAfterSpritesRenderingObserver = null; } this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver); this._onBeforeDrawPhaseObserver = null; this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver); this._onAfterDrawPhaseObserver = null; if (this._onBeforePhysicsObserver) { this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver); this._onBeforePhysicsObserver = null; } if (this._onAfterPhysicsObserver) { this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver); this._onAfterPhysicsObserver = null; } this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver); this._onAfterAnimationsObserver = null; this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver); this._onBeforeCameraRenderObserver = null; this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver); this._onAfterCameraRenderObserver = null; this.scene = null; }; return SceneInstrumentation; }()); /***/ }), /***/ "./Instrumentation/timeToken.ts": /*!**************************************!*\ !*** ./Instrumentation/timeToken.ts ***! \**************************************/ /*! exports provided: _TimeToken */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_TimeToken", function() { return _TimeToken; }); /** * @hidden **/ var _TimeToken = /** @class */ (function () { function _TimeToken() { this._timeElapsedQueryEnded = false; } return _TimeToken; }()); /***/ }), /***/ "./Layers/effectLayer.ts": /*!*******************************!*\ !*** ./Layers/effectLayer.ts ***! \*******************************/ /*! exports provided: EffectLayer */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EffectLayer", function() { return EffectLayer; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts"); /* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Meshes/buffer */ "./Meshes/buffer.ts"); /* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); /* harmony import */ var _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Materials/Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts"); /* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Materials/material */ "./Materials/material.ts"); /* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Materials/materialHelper */ "./Materials/materialHelper.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); /* harmony import */ var _Shaders_glowMapGeneration_fragment__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Shaders/glowMapGeneration.fragment */ "./Shaders/glowMapGeneration.fragment.ts"); /* harmony import */ var _Shaders_glowMapGeneration_vertex__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Shaders/glowMapGeneration.vertex */ "./Shaders/glowMapGeneration.vertex.ts"); /* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../Misc/devTools */ "./Misc/devTools.ts"); /** * The effect layer Helps adding post process effect blended with the main pass. * * This can be for instance use to generate glow or higlight effects on the scene. * * The effect layer class can not be used directly and is intented to inherited from to be * customized per effects. */ var EffectLayer = /** @class */ (function () { /** * Instantiates a new effect Layer and references it in the scene. * @param name The name of the layer * @param scene The scene to use the layer in */ function EffectLayer( /** The Friendly of the effect in the scene */ name, scene) { this._vertexBuffers = {}; this._maxSize = 0; this._mainTextureDesiredSize = { width: 0, height: 0 }; this._shouldRender = true; this._postProcesses = []; this._textures = []; this._emissiveTextureAndColor = { texture: null, color: new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Color4"]() }; /** * The clear color of the texture used to generate the glow map. */ this.neutralColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Color4"](); /** * Specifies wether the highlight layer is enabled or not. */ this.isEnabled = true; /** * An event triggered when the effect layer has been disposed. */ this.onDisposeObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](); /** * An event triggered when the effect layer is about rendering the main texture with the glowy parts. */ this.onBeforeRenderMainTextureObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](); /** * An event triggered when the generated texture is being merged in the scene. */ this.onBeforeComposeObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](); /** * An event triggered when the generated texture has been merged in the scene. */ this.onAfterComposeObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](); /** * An event triggered when the efffect layer changes its size. */ this.onSizeChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](); this.name = name; this._scene = scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; EffectLayer._SceneComponentInitialization(this._scene); this._engine = this._scene.getEngine(); this._maxSize = this._engine.getCaps().maxTextureSize; this._scene.effectLayers.push(this); // Generate Buffers this._generateIndexBuffer(); this._genrateVertexBuffer(); } Object.defineProperty(EffectLayer.prototype, "camera", { /** * Gets the camera attached to the layer. */ get: function () { return this._effectLayerOptions.camera; }, enumerable: true, configurable: true }); Object.defineProperty(EffectLayer.prototype, "renderingGroupId", { /** * Gets the rendering group id the layer should render in. */ get: function () { return this._effectLayerOptions.renderingGroupId; }, enumerable: true, configurable: true }); /** * Initializes the effect layer with the required options. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information) */ EffectLayer.prototype._init = function (options) { // Adapt options this._effectLayerOptions = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ mainTextureRatio: 0.5, alphaBlendingMode: _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options); this._setMainTextureSize(); this._createMainTexture(); this._createTextureAndPostProcesses(); this._mergeEffect = this._createMergeEffect(); }; /** * Generates the index buffer of the full screen quad blending to the main canvas. */ EffectLayer.prototype._generateIndexBuffer = function () { // Indices var indices = []; indices.push(0); indices.push(1); indices.push(2); indices.push(0); indices.push(2); indices.push(3); this._indexBuffer = this._engine.createIndexBuffer(indices); }; /** * Generates the vertex buffer of the full screen quad blending to the main canvas. */ EffectLayer.prototype._genrateVertexBuffer = function () { // VBO var vertices = []; vertices.push(1, 1); vertices.push(-1, 1); vertices.push(-1, -1); vertices.push(1, -1); var vertexBuffer = new _Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"](this._engine, vertices, _Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].PositionKind, false, false, 2); this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].PositionKind] = vertexBuffer; }; /** * Sets the main texture desired size which is the closest power of two * of the engine canvas size. */ EffectLayer.prototype._setMainTextureSize = function () { if (this._effectLayerOptions.mainTextureFixedSize) { this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize; this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize; } else { this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio; this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio; this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width; this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height; } this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width); this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height); }; /** * Creates the main texture for the effect layer. */ EffectLayer.prototype._createMainTexture = function () { var _this = this; this._mainTexture = new _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_8__["RenderTargetTexture"]("HighlightLayerMainRTT", { width: this._mainTextureDesiredSize.width, height: this._mainTextureDesiredSize.height }, this._scene, false, true, _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURETYPE_UNSIGNED_INT); this._mainTexture.activeCamera = this._effectLayerOptions.camera; this._mainTexture.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].CLAMP_ADDRESSMODE; this._mainTexture.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].CLAMP_ADDRESSMODE; this._mainTexture.anisotropicFilteringLevel = 1; this._mainTexture.updateSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].BILINEAR_SAMPLINGMODE); this._mainTexture.renderParticles = false; this._mainTexture.renderList = null; this._mainTexture.ignoreCameraViewport = true; // Custom render function this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) { _this.onBeforeRenderMainTextureObservable.notifyObservers(_this); var index; var engine = _this._scene.getEngine(); if (depthOnlySubMeshes.length) { engine.setColorWrite(false); for (index = 0; index < depthOnlySubMeshes.length; index++) { _this._renderSubMesh(depthOnlySubMeshes.data[index]); } engine.setColorWrite(true); } for (index = 0; index < opaqueSubMeshes.length; index++) { _this._renderSubMesh(opaqueSubMeshes.data[index]); } for (index = 0; index < alphaTestSubMeshes.length; index++) { _this._renderSubMesh(alphaTestSubMeshes.data[index]); } for (index = 0; index < transparentSubMeshes.length; index++) { _this._renderSubMesh(transparentSubMeshes.data[index]); } }; this._mainTexture.onClearObservable.add(function (engine) { engine.clear(_this.neutralColor, true, true, true); }); }; /** * Adds specific effects defines. * @param defines The defines to add specifics to. */ EffectLayer.prototype._addCustomEffectDefines = function (defines) { // Nothing to add by default. }; /** * Checks for the readiness of the element composing the layer. * @param subMesh the mesh to check for * @param useInstances specify wether or not to use instances to render the mesh * @param emissiveTexture the associated emissive texture used to generate the glow * @return true if ready otherwise, false */ EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) { var material = subMesh.getMaterial(); if (!material) { return false; } if (!material.isReadyForSubMesh(subMesh.getMesh(), subMesh, useInstances)) { return false; } var defines = []; var attribs = [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].PositionKind]; var mesh = subMesh.getMesh(); var uv1 = false; var uv2 = false; // Diffuse if (material) { var needAlphaTest = material.needAlphaTesting(); var diffuseTexture = material.getAlphaTestTexture(); var needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha && (material.useAlphaFromDiffuseTexture || material._useAlphaFromAlbedoTexture); if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) { defines.push("#define DIFFUSE"); if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].UV2Kind) && diffuseTexture.coordinatesIndex === 1) { defines.push("#define DIFFUSEUV2"); uv2 = true; } else if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].UVKind)) { defines.push("#define DIFFUSEUV1"); uv1 = true; } if (needAlphaTest) { defines.push("#define ALPHATEST"); defines.push("#define ALPHATESTVALUE 0.4"); } } var opacityTexture = material.opacityTexture; if (opacityTexture) { defines.push("#define OPACITY"); if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].UV2Kind) && opacityTexture.coordinatesIndex === 1) { defines.push("#define OPACITYUV2"); uv2 = true; } else if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].UVKind)) { defines.push("#define OPACITYUV1"); uv1 = true; } } } // Emissive if (emissiveTexture) { defines.push("#define EMISSIVE"); if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].UV2Kind) && emissiveTexture.coordinatesIndex === 1) { defines.push("#define EMISSIVEUV2"); uv2 = true; } else if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].UVKind)) { defines.push("#define EMISSIVEUV1"); uv1 = true; } } // Vertex if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].ColorKind) && mesh.hasVertexAlpha) { attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].ColorKind); defines.push("#define VERTEXALPHA"); } if (uv1) { attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].UVKind); defines.push("#define UV1"); } if (uv2) { attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].UV2Kind); defines.push("#define UV2"); } // Bones if (mesh.useBones && mesh.computeBonesUsingShaders) { attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].MatricesIndicesKind); attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].MatricesWeightsKind); if (mesh.numBoneInfluencers > 4) { attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].MatricesIndicesExtraKind); attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].MatricesWeightsExtraKind); } defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0)); } else { defines.push("#define NUM_BONE_INFLUENCERS 0"); } // Morph targets var manager = mesh.morphTargetManager; var morphInfluencers = 0; if (manager) { if (manager.numInfluencers > 0) { defines.push("#define MORPHTARGETS"); morphInfluencers = manager.numInfluencers; defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers); _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_10__["MaterialHelper"].PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers }); } } // Instances if (useInstances) { defines.push("#define INSTANCES"); attribs.push("world0"); attribs.push("world1"); attribs.push("world2"); attribs.push("world3"); } this._addCustomEffectDefines(defines); // Get correct effect var join = defines.join("\n"); if (this._cachedDefines !== join) { this._cachedDefines = join; this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "color", "morphTargetInfluences", "diffuseMatrix", "emissiveMatrix", "opacityMatrix", "opacityIntensity"], ["diffuseSampler", "emissiveSampler", "opacitySampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers }); } return this._effectLayerMapGenerationEffect.isReady(); }; /** * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene. */ EffectLayer.prototype.render = function () { var currentEffect = this._mergeEffect; // Check if (!currentEffect.isReady()) { return; } for (var i = 0; i < this._postProcesses.length; i++) { if (!this._postProcesses[i].isReady()) { return; } } var engine = this._scene.getEngine(); this.onBeforeComposeObservable.notifyObservers(this); // Render engine.enableEffect(currentEffect); engine.setState(false); // VBOs engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect); // Cache var previousAlphaMode = engine.getAlphaMode(); // Go Blend. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode); // Blends the map on the main canvas. this._internalRender(currentEffect); // Restore Alpha engine.setAlphaMode(previousAlphaMode); this.onAfterComposeObservable.notifyObservers(this); // Handle size changes. var size = this._mainTexture.getSize(); this._setMainTextureSize(); if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) { // Recreate RTT and post processes on size change. this.onSizeChangedObservable.notifyObservers(this); this._disposeTextureAndPostProcesses(); this._createMainTexture(); this._createTextureAndPostProcesses(); } }; /** * Determine if a given mesh will be used in the current effect. * @param mesh mesh to test * @returns true if the mesh will be used */ EffectLayer.prototype.hasMesh = function (mesh) { if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) { return true; } return false; }; /** * Returns true if the layer contains information to display, otherwise false. * @returns true if the glow layer should be rendered */ EffectLayer.prototype.shouldRender = function () { return this.isEnabled && this._shouldRender; }; /** * Returns true if the mesh should render, otherwise false. * @param mesh The mesh to render * @returns true if it should render otherwise false */ EffectLayer.prototype._shouldRenderMesh = function (mesh) { return true; }; /** * Returns true if the mesh can be rendered, otherwise false. * @param mesh The mesh to render * @param material The material used on the mesh * @returns true if it can be rendered otherwise false */ EffectLayer.prototype._canRenderMesh = function (mesh, material) { return !material.needAlphaBlendingForMesh(mesh); }; /** * Returns true if the mesh should render, otherwise false. * @param mesh The mesh to render * @returns true if it should render otherwise false */ EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function () { return true; }; /** * Renders the submesh passed in parameter to the generation map. */ EffectLayer.prototype._renderSubMesh = function (subMesh) { var _this = this; if (!this.shouldRender()) { return; } var material = subMesh.getMaterial(); var mesh = subMesh.getRenderingMesh(); var scene = this._scene; var engine = scene.getEngine(); if (!material) { return; } // Do not block in blend mode. if (!this._canRenderMesh(mesh, material)) { return; } // Culling engine.setState(material.backFaceCulling); // Managing instances var batch = mesh._getInstancesRenderList(subMesh._id); if (batch.mustReturn) { return; } // Early Exit per mesh if (!this._shouldRenderMesh(mesh)) { return; } var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined); this._setEmissiveTextureAndColor(mesh, subMesh, material); if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) { engine.enableEffect(this._effectLayerMapGenerationEffect); mesh._bind(subMesh, this._effectLayerMapGenerationEffect, _Materials_material__WEBPACK_IMPORTED_MODULE_9__["Material"].TriangleFillMode); this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix()); this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a); var needAlphaTest = material.needAlphaTesting(); var diffuseTexture = material.getAlphaTestTexture(); var needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha && (material.useAlphaFromDiffuseTexture || material._useAlphaFromAlbedoTexture); if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) { this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", diffuseTexture); var textureMatrix = diffuseTexture.getTextureMatrix(); if (textureMatrix) { this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix); } } var opacityTexture = material.opacityTexture; if (opacityTexture) { this._effectLayerMapGenerationEffect.setTexture("opacitySampler", opacityTexture); this._effectLayerMapGenerationEffect.setFloat("opacityIntensity", opacityTexture.level); var textureMatrix = opacityTexture.getTextureMatrix(); if (textureMatrix) { this._effectLayerMapGenerationEffect.setMatrix("opacityMatrix", textureMatrix); } } // Glow emissive only if (this._emissiveTextureAndColor.texture) { this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture); this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix()); } // Bones if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh)); } // Morph targets _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_10__["MaterialHelper"].BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect); // Draw mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, _Materials_material__WEBPACK_IMPORTED_MODULE_9__["Material"].TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); }); } else { // Need to reset refresh rate of the main map this._mainTexture.resetRefreshCounter(); } }; /** * Rebuild the required buffers. * @hidden Internal use only. */ EffectLayer.prototype._rebuild = function () { var vb = this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].PositionKind]; if (vb) { vb._rebuild(); } this._generateIndexBuffer(); }; /** * Dispose only the render target textures and post process. */ EffectLayer.prototype._disposeTextureAndPostProcesses = function () { this._mainTexture.dispose(); for (var i = 0; i < this._postProcesses.length; i++) { if (this._postProcesses[i]) { this._postProcesses[i].dispose(); } } this._postProcesses = []; for (var i = 0; i < this._textures.length; i++) { if (this._textures[i]) { this._textures[i].dispose(); } } this._textures = []; }; /** * Dispose the highlight layer and free resources. */ EffectLayer.prototype.dispose = function () { var vertexBuffer = this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].PositionKind]; if (vertexBuffer) { vertexBuffer.dispose(); this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_6__["VertexBuffer"].PositionKind] = null; } if (this._indexBuffer) { this._scene.getEngine()._releaseBuffer(this._indexBuffer); this._indexBuffer = null; } // Clean textures and post processes this._disposeTextureAndPostProcesses(); // Remove from scene var index = this._scene.effectLayers.indexOf(this, 0); if (index > -1) { this._scene.effectLayers.splice(index, 1); } // Callback this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); this.onBeforeRenderMainTextureObservable.clear(); this.onBeforeComposeObservable.clear(); this.onAfterComposeObservable.clear(); this.onSizeChangedObservable.clear(); }; /** * Gets the class name of the effect layer * @returns the string with the class name of the effect layer */ EffectLayer.prototype.getClassName = function () { return "EffectLayer"; }; /** * Creates an effect layer from parsed effect layer data * @param parsedEffectLayer defines effect layer data * @param scene defines the current scene * @param rootUrl defines the root URL containing the effect layer information * @returns a parsed effect Layer */ EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) { var effectLayerType = _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].Instantiate(parsedEffectLayer.customType); return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl); }; /** @hidden */ EffectLayer._SceneComponentInitialization = function (_) { throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_14__["_DevTools"].WarnImport("EffectLayerSceneComponent"); }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], EffectLayer.prototype, "name", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor4"])() ], EffectLayer.prototype, "neutralColor", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], EffectLayer.prototype, "isEnabled", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsCameraReference"])() ], EffectLayer.prototype, "camera", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], EffectLayer.prototype, "renderingGroupId", null); return EffectLayer; }()); /***/ }), /***/ "./Layers/effectLayerSceneComponent.ts": /*!*********************************************!*\ !*** ./Layers/effectLayerSceneComponent.ts ***! \*********************************************/ /*! exports provided: EffectLayerSceneComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EffectLayerSceneComponent", function() { return EffectLayerSceneComponent; }); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../sceneComponent */ "./sceneComponent.ts"); /* harmony import */ var _effectLayer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./effectLayer */ "./Layers/effectLayer.ts"); /* harmony import */ var _abstractScene__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../abstractScene */ "./abstractScene.ts"); // Adds the parser to the scene parsers. _abstractScene__WEBPACK_IMPORTED_MODULE_3__["AbstractScene"].AddParser(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) { if (parsedData.effectLayers) { if (!container.effectLayers) { container.effectLayers = new Array(); } for (var index = 0; index < parsedData.effectLayers.length; index++) { var effectLayer = _effectLayer__WEBPACK_IMPORTED_MODULE_2__["EffectLayer"].Parse(parsedData.effectLayers[index], scene, rootUrl); container.effectLayers.push(effectLayer); } } }); _abstractScene__WEBPACK_IMPORTED_MODULE_3__["AbstractScene"].prototype.removeEffectLayer = function (toRemove) { var index = this.effectLayers.indexOf(toRemove); if (index !== -1) { this.effectLayers.splice(index, 1); } return index; }; _abstractScene__WEBPACK_IMPORTED_MODULE_3__["AbstractScene"].prototype.addEffectLayer = function (newEffectLayer) { this.effectLayers.push(newEffectLayer); }; /** * Defines the layer scene component responsible to manage any effect layers * in a given scene. */ var EffectLayerSceneComponent = /** @class */ (function () { /** * Creates a new instance of the component for the given scene * @param scene Defines the scene to register the component in */ function EffectLayerSceneComponent(scene) { /** * The component name helpfull to identify the component in the list of scene components. */ this.name = _sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_EFFECTLAYER; this._renderEffects = false; this._needStencil = false; this._previousStencilState = false; this.scene = scene; this._engine = scene.getEngine(); scene.effectLayers = new Array(); } /** * Registers the component in a given scene */ EffectLayerSceneComponent.prototype.register = function () { this.scene._isReadyForMeshStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh); this.scene._cameraDrawRenderTargetStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture); this.scene._beforeCameraDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil); this.scene._afterRenderingGroupDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup); this.scene._afterCameraDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack); this.scene._afterCameraDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera); }; /** * Rebuilds the elements related to this component in case of * context lost for instance. */ EffectLayerSceneComponent.prototype.rebuild = function () { var layers = this.scene.effectLayers; for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) { var effectLayer = layers_1[_i]; effectLayer._rebuild(); } }; /** * Serializes the component data to the specified json object * @param serializationObject The object to serialize to */ EffectLayerSceneComponent.prototype.serialize = function (serializationObject) { // Effect layers serializationObject.effectLayers = []; var layers = this.scene.effectLayers; for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) { var effectLayer = layers_2[_i]; if (effectLayer.serialize) { serializationObject.effectLayers.push(effectLayer.serialize()); } } }; /** * Adds all the element from the container to the scene * @param container the container holding the elements */ EffectLayerSceneComponent.prototype.addFromContainer = function (container) { var _this = this; if (!container.effectLayers) { return; } container.effectLayers.forEach(function (o) { _this.scene.addEffectLayer(o); }); }; /** * Removes all the elements in the container from the scene * @param container contains the elements to remove * @param dispose if the removed element should be disposed (default: false) */ EffectLayerSceneComponent.prototype.removeFromContainer = function (container, dispose) { var _this = this; if (!container.effectLayers) { return; } container.effectLayers.forEach(function (o) { _this.scene.removeEffectLayer(o); if (dispose) { o.dispose(); } }); }; /** * Disposes the component and the associated ressources. */ EffectLayerSceneComponent.prototype.dispose = function () { var layers = this.scene.effectLayers; while (layers.length) { layers[0].dispose(); } }; EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) { var layers = this.scene.effectLayers; for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) { var layer = layers_3[_i]; if (!layer.hasMesh(mesh)) { continue; } for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) { var subMesh = _b[_a]; if (!layer.isReady(subMesh, hardwareInstancedRendering)) { return false; } } } return true; }; EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) { this._renderEffects = false; this._needStencil = false; var layers = this.scene.effectLayers; if (layers && layers.length > 0) { this._previousStencilState = this._engine.getStencilBuffer(); for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) { var effectLayer = layers_4[_i]; if (effectLayer.shouldRender() && (!effectLayer.camera || (effectLayer.camera.cameraRigMode === _Cameras_camera__WEBPACK_IMPORTED_MODULE_0__["Camera"].RIG_MODE_NONE && camera === effectLayer.camera) || (effectLayer.camera.cameraRigMode !== _Cameras_camera__WEBPACK_IMPORTED_MODULE_0__["Camera"].RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) { this._renderEffects = true; this._needStencil = this._needStencil || effectLayer.needStencil(); var renderTarget = effectLayer._mainTexture; if (renderTarget._shouldRender()) { this.scene.incrementRenderId(); renderTarget.render(false, false); } } } this.scene.incrementRenderId(); } }; EffectLayerSceneComponent.prototype._setStencil = function () { // Activate effect Layer stencil if (this._needStencil) { this._engine.setStencilBuffer(true); } }; EffectLayerSceneComponent.prototype._setStencilBack = function () { // Restore effect Layer stencil if (this._needStencil) { this._engine.setStencilBuffer(this._previousStencilState); } }; EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) { if (this._renderEffects) { this._engine.setDepthBuffer(false); var layers = this.scene.effectLayers; for (var i = 0; i < layers.length; i++) { var effectLayer = layers[i]; if (effectLayer.renderingGroupId === renderingGroupId) { if (effectLayer.shouldRender()) { effectLayer.render(); } } } this._engine.setDepthBuffer(true); } }; EffectLayerSceneComponent.prototype._drawCamera = function () { if (this._renderEffects) { this._draw(-1); } }; EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) { if (!this.scene._isInIntermediateRendering() && this._renderEffects) { this._draw(index); } }; return EffectLayerSceneComponent; }()); _effectLayer__WEBPACK_IMPORTED_MODULE_2__["EffectLayer"]._SceneComponentInitialization = function (scene) { var component = scene._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_EFFECTLAYER); if (!component) { component = new EffectLayerSceneComponent(scene); scene._addComponent(component); } }; /***/ }), /***/ "./Layers/glowLayer.ts": /*!*****************************!*\ !*** ./Layers/glowLayer.ts ***! \*****************************/ /*! exports provided: GlowLayer */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GlowLayer", function() { return GlowLayer; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/buffer */ "./Meshes/buffer.ts"); /* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); /* harmony import */ var _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Materials/Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts"); /* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Materials/material */ "./Materials/material.ts"); /* harmony import */ var _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../PostProcesses/blurPostProcess */ "./PostProcesses/blurPostProcess.ts"); /* harmony import */ var _effectLayer__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./effectLayer */ "./Layers/effectLayer.ts"); /* harmony import */ var _abstractScene__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../abstractScene */ "./abstractScene.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); /* harmony import */ var _Shaders_glowMapMerge_fragment__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Shaders/glowMapMerge.fragment */ "./Shaders/glowMapMerge.fragment.ts"); /* harmony import */ var _Shaders_glowMapMerge_vertex__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../Shaders/glowMapMerge.vertex */ "./Shaders/glowMapMerge.vertex.ts"); /* harmony import */ var _Layers_effectLayerSceneComponent__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../Layers/effectLayerSceneComponent */ "./Layers/effectLayerSceneComponent.ts"); _abstractScene__WEBPACK_IMPORTED_MODULE_10__["AbstractScene"].prototype.getGlowLayerByName = function (name) { for (var index = 0; index < this.effectLayers.length; index++) { if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) { return this.effectLayers[index]; } } return null; }; /** * The glow layer Helps adding a glow effect around the emissive parts of a mesh. * * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove * glowy meshes to your scene. * * Documentation: https://doc.babylonjs.com/how_to/glow_layer */ var GlowLayer = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GlowLayer, _super); /** * Instantiates a new glow Layer and references it to the scene. * @param name The name of the layer * @param scene The scene to use the layer in * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information) */ function GlowLayer(name, scene, options) { var _this = _super.call(this, name, scene) || this; _this._intensity = 1.0; _this._includedOnlyMeshes = []; _this._excludedMeshes = []; _this.neutralColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color4"](0, 0, 0, 1); // Adapt options _this._options = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options); // Initialize the layer _this._init({ alphaBlendingMode: _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ALPHA_ADD, camera: _this._options.camera, mainTextureFixedSize: _this._options.mainTextureFixedSize, mainTextureRatio: _this._options.mainTextureRatio, renderingGroupId: _this._options.renderingGroupId }); return _this; } Object.defineProperty(GlowLayer.prototype, "blurKernelSize", { /** * Gets the kernel size of the blur. */ get: function () { return this._horizontalBlurPostprocess1.kernel; }, /** * Sets the kernel size of the blur. */ set: function (value) { this._horizontalBlurPostprocess1.kernel = value; this._verticalBlurPostprocess1.kernel = value; this._horizontalBlurPostprocess2.kernel = value; this._verticalBlurPostprocess2.kernel = value; }, enumerable: true, configurable: true }); Object.defineProperty(GlowLayer.prototype, "intensity", { /** * Gets the glow intensity. */ get: function () { return this._intensity; }, /** * Sets the glow intensity. */ set: function (value) { this._intensity = value; }, enumerable: true, configurable: true }); /** * Get the effect name of the layer. * @return The effect name */ GlowLayer.prototype.getEffectName = function () { return GlowLayer.EffectName; }; /** * Create the merge effect. This is the shader use to blit the information back * to the main canvas at the end of the scene rendering. */ GlowLayer.prototype._createMergeEffect = function () { // Effect return this._engine.createEffect("glowMapMerge", [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n"); }; /** * Creates the render target textures and post processes used in the glow layer. */ GlowLayer.prototype._createTextureAndPostProcesses = function () { var _this = this; var blurTextureWidth = this._mainTextureDesiredSize.width; var blurTextureHeight = this._mainTextureDesiredSize.height; blurTextureWidth = this._engine.needPOTTextures ? _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth; blurTextureHeight = this._engine.needPOTTextures ? _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight; var textureType = 0; if (this._engine.getCaps().textureHalfFloatRender) { textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURETYPE_HALF_FLOAT; } else { textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURETYPE_UNSIGNED_INT; } this._blurTexture1 = new _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_6__["RenderTargetTexture"]("GlowLayerBlurRTT", { width: blurTextureWidth, height: blurTextureHeight }, this._scene, false, true, textureType); this._blurTexture1.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"].CLAMP_ADDRESSMODE; this._blurTexture1.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"].CLAMP_ADDRESSMODE; this._blurTexture1.updateSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"].BILINEAR_SAMPLINGMODE); this._blurTexture1.renderParticles = false; this._blurTexture1.ignoreCameraViewport = true; var blurTextureWidth2 = Math.floor(blurTextureWidth / 2); var blurTextureHeight2 = Math.floor(blurTextureHeight / 2); this._blurTexture2 = new _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_6__["RenderTargetTexture"]("GlowLayerBlurRTT2", { width: blurTextureWidth2, height: blurTextureHeight2 }, this._scene, false, true, textureType); this._blurTexture2.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"].CLAMP_ADDRESSMODE; this._blurTexture2.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"].CLAMP_ADDRESSMODE; this._blurTexture2.updateSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"].BILINEAR_SAMPLINGMODE); this._blurTexture2.renderParticles = false; this._blurTexture2.ignoreCameraViewport = true; this._textures = [this._blurTexture1, this._blurTexture2]; this._horizontalBlurPostprocess1 = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_8__["BlurPostProcess"]("GlowLayerHBP1", new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector2"](1.0, 0), this._options.blurKernelSize / 2, { width: blurTextureWidth, height: blurTextureHeight }, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType); this._horizontalBlurPostprocess1.width = blurTextureWidth; this._horizontalBlurPostprocess1.height = blurTextureHeight; this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) { effect.setTexture("textureSampler", _this._mainTexture); }); this._verticalBlurPostprocess1 = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_8__["BlurPostProcess"]("GlowLayerVBP1", new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector2"](0, 1.0), this._options.blurKernelSize / 2, { width: blurTextureWidth, height: blurTextureHeight }, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType); this._horizontalBlurPostprocess2 = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_8__["BlurPostProcess"]("GlowLayerHBP2", new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector2"](1.0, 0), this._options.blurKernelSize / 2, { width: blurTextureWidth2, height: blurTextureHeight2 }, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType); this._horizontalBlurPostprocess2.width = blurTextureWidth2; this._horizontalBlurPostprocess2.height = blurTextureHeight2; this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) { effect.setTexture("textureSampler", _this._blurTexture1); }); this._verticalBlurPostprocess2 = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_8__["BlurPostProcess"]("GlowLayerVBP2", new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector2"](0, 1.0), this._options.blurKernelSize / 2, { width: blurTextureWidth2, height: blurTextureHeight2 }, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType); this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2]; this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1]; this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2]; this._mainTexture.samples = this._options.mainTextureSamples; this._mainTexture.onAfterUnbindObservable.add(function () { var internalTexture = _this._blurTexture1.getInternalTexture(); if (internalTexture) { _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true); internalTexture = _this._blurTexture2.getInternalTexture(); if (internalTexture) { _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true); } } }); // Prevent autoClear. this._postProcesses.map(function (pp) { pp.autoClear = false; }); }; /** * Checks for the readiness of the element composing the layer. * @param subMesh the mesh to check for * @param useInstances specify wether or not to use instances to render the mesh * @param emissiveTexture the associated emissive texture used to generate the glow * @return true if ready otherwise, false */ GlowLayer.prototype.isReady = function (subMesh, useInstances) { var material = subMesh.getMaterial(); var mesh = subMesh.getRenderingMesh(); if (!material || !mesh) { return false; } var emissiveTexture = material.emissiveTexture; return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture); }; /** * Returns wether or nood the layer needs stencil enabled during the mesh rendering. */ GlowLayer.prototype.needStencil = function () { return false; }; /** * Returns true if the mesh can be rendered, otherwise false. * @param mesh The mesh to render * @param material The material used on the mesh * @returns true if it can be rendered otherwise false */ GlowLayer.prototype._canRenderMesh = function (mesh, material) { return true; }; /** * Implementation specific of rendering the generating effect on the main canvas. * @param effect The effect used to render through */ GlowLayer.prototype._internalRender = function (effect) { // Texture effect.setTexture("textureSampler", this._blurTexture1); effect.setTexture("textureSampler2", this._blurTexture2); effect.setFloat("offset", this._intensity); // Cache var engine = this._engine; var previousStencilBuffer = engine.getStencilBuffer(); // Draw order engine.setStencilBuffer(false); engine.drawElementsType(_Materials_material__WEBPACK_IMPORTED_MODULE_7__["Material"].TriangleFillMode, 0, 6); // Draw order engine.setStencilBuffer(previousStencilBuffer); }; /** * Sets the required values for both the emissive texture and and the main color. */ GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) { var textureLevel = 1.0; if (this.customEmissiveTextureSelector) { this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material); } else { if (material) { this._emissiveTextureAndColor.texture = material.emissiveTexture; if (this._emissiveTextureAndColor.texture) { textureLevel = this._emissiveTextureAndColor.texture.level; } } else { this._emissiveTextureAndColor.texture = null; } } if (this.customEmissiveColorSelector) { this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color); } else { if (material.emissiveColor) { this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, material.alpha); } else { this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a); } } }; /** * Returns true if the mesh should render, otherwise false. * @param mesh The mesh to render * @returns true if it should render otherwise false */ GlowLayer.prototype._shouldRenderMesh = function (mesh) { return this.hasMesh(mesh); }; /** * Adds specific effects defines. * @param defines The defines to add specifics to. */ GlowLayer.prototype._addCustomEffectDefines = function (defines) { defines.push("#define GLOW"); }; /** * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer. * @param mesh The mesh to exclude from the glow layer */ GlowLayer.prototype.addExcludedMesh = function (mesh) { if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) { this._excludedMeshes.push(mesh.uniqueId); } }; /** * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer. * @param mesh The mesh to remove */ GlowLayer.prototype.removeExcludedMesh = function (mesh) { var index = this._excludedMeshes.indexOf(mesh.uniqueId); if (index !== -1) { this._excludedMeshes.splice(index, 1); } }; /** * Add a mesh in the inclusion list to impact or being impacted by the glow layer. * @param mesh The mesh to include in the glow layer */ GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) { if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) { this._includedOnlyMeshes.push(mesh.uniqueId); } }; /** * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer. * @param mesh The mesh to remove */ GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) { var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId); if (index !== -1) { this._includedOnlyMeshes.splice(index, 1); } }; /** * Determine if a given mesh will be used in the glow layer * @param mesh The mesh to test * @returns true if the mesh will be highlighted by the current glow layer */ GlowLayer.prototype.hasMesh = function (mesh) { if (!_super.prototype.hasMesh.call(this, mesh)) { return false; } // Included Mesh if (this._includedOnlyMeshes.length) { return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1; } // Excluded Mesh if (this._excludedMeshes.length) { return this._excludedMeshes.indexOf(mesh.uniqueId) === -1; } return true; }; /** * Free any resources and references associated to a mesh. * Internal use * @param mesh The mesh to free. * @hidden */ GlowLayer.prototype._disposeMesh = function (mesh) { this.removeIncludedOnlyMesh(mesh); this.removeExcludedMesh(mesh); }; /** * Gets the class name of the effect layer * @returns the string with the class name of the effect layer */ GlowLayer.prototype.getClassName = function () { return "GlowLayer"; }; /** * Serializes this glow layer * @returns a serialized glow layer object */ GlowLayer.prototype.serialize = function () { var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); serializationObject.customType = "BABYLON.GlowLayer"; var index; // Included meshes serializationObject.includedMeshes = []; if (this._includedOnlyMeshes.length) { for (index = 0; index < this._includedOnlyMeshes.length; index++) { var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]); if (mesh) { serializationObject.includedMeshes.push(mesh.id); } } } // Excluded meshes serializationObject.excludedMeshes = []; if (this._excludedMeshes.length) { for (index = 0; index < this._excludedMeshes.length; index++) { var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]); if (mesh) { serializationObject.excludedMeshes.push(mesh.id); } } } return serializationObject; }; /** * Creates a Glow Layer from parsed glow layer data * @param parsedGlowLayer defines glow layer data * @param scene defines the current scene * @param rootUrl defines the root URL containing the glow layer information * @returns a parsed Glow Layer */ GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) { var gl = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl); var index; // Excluded meshes for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) { var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]); if (mesh) { gl.addExcludedMesh(mesh); } } // Included meshes for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) { var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]); if (mesh) { gl.addIncludedOnlyMesh(mesh); } } return gl; }; /** * Effect Name of the layer. */ GlowLayer.EffectName = "GlowLayer"; /** * The default blur kernel size used for the glow. */ GlowLayer.DefaultBlurKernelSize = 32; /** * The default texture size ratio used for the glow. */ GlowLayer.DefaultTextureRatio = 0.5; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], GlowLayer.prototype, "blurKernelSize", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], GlowLayer.prototype, "intensity", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("options") ], GlowLayer.prototype, "_options", void 0); return GlowLayer; }(_effectLayer__WEBPACK_IMPORTED_MODULE_9__["EffectLayer"])); _Misc_typeStore__WEBPACK_IMPORTED_MODULE_12__["_TypeStore"].RegisteredTypes["BABYLON.GlowLayer"] = GlowLayer; /***/ }), /***/ "./Layers/highlightLayer.ts": /*!**********************************!*\ !*** ./Layers/highlightLayer.ts ***! \**********************************/ /*! exports provided: HighlightLayer */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HighlightLayer", function() { return HighlightLayer; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Meshes/buffer */ "./Meshes/buffer.ts"); /* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Materials/material */ "./Materials/material.ts"); /* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); /* harmony import */ var _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Materials/Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts"); /* harmony import */ var _PostProcesses_postProcess__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../PostProcesses/postProcess */ "./PostProcesses/postProcess.ts"); /* harmony import */ var _PostProcesses_passPostProcess__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../PostProcesses/passPostProcess */ "./PostProcesses/passPostProcess.ts"); /* harmony import */ var _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../PostProcesses/blurPostProcess */ "./PostProcesses/blurPostProcess.ts"); /* harmony import */ var _effectLayer__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./effectLayer */ "./Layers/effectLayer.ts"); /* harmony import */ var _abstractScene__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../abstractScene */ "./abstractScene.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); /* harmony import */ var _Shaders_glowMapMerge_fragment__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../Shaders/glowMapMerge.fragment */ "./Shaders/glowMapMerge.fragment.ts"); /* harmony import */ var _Shaders_glowMapMerge_vertex__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../Shaders/glowMapMerge.vertex */ "./Shaders/glowMapMerge.vertex.ts"); /* harmony import */ var _Shaders_glowBlurPostProcess_fragment__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../Shaders/glowBlurPostProcess.fragment */ "./Shaders/glowBlurPostProcess.fragment.ts"); _abstractScene__WEBPACK_IMPORTED_MODULE_13__["AbstractScene"].prototype.getHighlightLayerByName = function (name) { for (var index = 0; index < this.effectLayers.length; index++) { if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) { return this.effectLayers[index]; } } return null; }; /** * Special Glow Blur post process only blurring the alpha channel * It enforces keeping the most luminous color in the color channel. */ var GlowBlurPostProcess = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](GlowBlurPostProcess, _super); function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) { if (samplingMode === void 0) { samplingMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].BILINEAR_SAMPLINGMODE; } var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this; _this.direction = direction; _this.kernel = kernel; _this.onApplyObservable.add(function (effect) { effect.setFloat2("screenSize", _this.width, _this.height); effect.setVector2("direction", _this.direction); effect.setFloat("blurWidth", _this.kernel); }); return _this; } return GlowBlurPostProcess; }(_PostProcesses_postProcess__WEBPACK_IMPORTED_MODULE_9__["PostProcess"])); /** * The highlight layer Helps adding a glow effect around a mesh. * * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove * glowy meshes to your scene. * * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!! */ var HighlightLayer = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](HighlightLayer, _super); /** * Instantiates a new highlight Layer and references it to the scene.. * @param name The name of the layer * @param scene The scene to use the layer in * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information) */ function HighlightLayer(name, scene, options) { var _this = _super.call(this, name, scene) || this; _this.name = name; /** * Specifies whether or not the inner glow is ACTIVE in the layer. */ _this.innerGlow = true; /** * Specifies whether or not the outer glow is ACTIVE in the layer. */ _this.outerGlow = true; /** * An event triggered when the highlight layer is being blurred. */ _this.onBeforeBlurObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * An event triggered when the highlight layer has been blurred. */ _this.onAfterBlurObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++; _this._meshes = {}; _this._excludedMeshes = {}; _this.neutralColor = HighlightLayer.NeutralColor; // Warn on stencil if (!_this._engine.isStencilEnable) { _Misc_logger__WEBPACK_IMPORTED_MODULE_15__["Logger"].Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"); } // Adapt options _this._options = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: _Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options); // Initialize the layer _this._init({ alphaBlendingMode: _this._options.alphaBlendingMode, camera: _this._options.camera, mainTextureFixedSize: _this._options.mainTextureFixedSize, mainTextureRatio: _this._options.mainTextureRatio, renderingGroupId: _this._options.renderingGroupId }); // Do not render as long as no meshes have been added _this._shouldRender = false; return _this; } Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", { /** * Gets the horizontal size of the blur. */ get: function () { return this._horizontalBlurPostprocess.kernel; }, /** * Specifies the horizontal size of the blur. */ set: function (value) { this._horizontalBlurPostprocess.kernel = value; }, enumerable: true, configurable: true }); Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", { /** * Gets the vertical size of the blur. */ get: function () { return this._verticalBlurPostprocess.kernel; }, /** * Specifies the vertical size of the blur. */ set: function (value) { this._verticalBlurPostprocess.kernel = value; }, enumerable: true, configurable: true }); /** * Get the effect name of the layer. * @return The effect name */ HighlightLayer.prototype.getEffectName = function () { return HighlightLayer.EffectName; }; /** * Create the merge effect. This is the shader use to blit the information back * to the main canvas at the end of the scene rendering. */ HighlightLayer.prototype._createMergeEffect = function () { // Effect return this._engine.createEffect("glowMapMerge", [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined); }; /** * Creates the render target textures and post processes used in the highlight layer. */ HighlightLayer.prototype._createTextureAndPostProcesses = function () { var _this = this; var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio; var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio; blurTextureWidth = this._engine.needPOTTextures ? _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth; blurTextureHeight = this._engine.needPOTTextures ? _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight; var textureType = 0; if (this._engine.getCaps().textureHalfFloatRender) { textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].TEXTURETYPE_HALF_FLOAT; } else { textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].TEXTURETYPE_UNSIGNED_INT; } this._blurTexture = new _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_8__["RenderTargetTexture"]("HighlightLayerBlurRTT", { width: blurTextureWidth, height: blurTextureHeight }, this._scene, false, true, textureType); this._blurTexture.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].CLAMP_ADDRESSMODE; this._blurTexture.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].CLAMP_ADDRESSMODE; this._blurTexture.anisotropicFilteringLevel = 16; this._blurTexture.updateSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].TRILINEAR_SAMPLINGMODE); this._blurTexture.renderParticles = false; this._blurTexture.ignoreCameraViewport = true; this._textures = [this._blurTexture]; if (this._options.alphaBlendingMode === _Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].ALPHA_COMBINE) { this._downSamplePostprocess = new _PostProcesses_passPostProcess__WEBPACK_IMPORTED_MODULE_10__["PassPostProcess"]("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine()); this._downSamplePostprocess.onApplyObservable.add(function (effect) { effect.setTexture("textureSampler", _this._mainTexture); }); this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector2"](1.0, 0), this._options.blurHorizontalSize, 1, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine()); this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) { effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight); }); this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector2"](0, 1.0), this._options.blurVerticalSize, 1, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine()); this._verticalBlurPostprocess.onApplyObservable.add(function (effect) { effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight); }); this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess]; } else { this._horizontalBlurPostprocess = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_11__["BlurPostProcess"]("HighlightLayerHBP", new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector2"](1.0, 0), this._options.blurHorizontalSize / 2, { width: blurTextureWidth, height: blurTextureHeight }, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType); this._horizontalBlurPostprocess.width = blurTextureWidth; this._horizontalBlurPostprocess.height = blurTextureHeight; this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) { effect.setTexture("textureSampler", _this._mainTexture); }); this._verticalBlurPostprocess = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_11__["BlurPostProcess"]("HighlightLayerVBP", new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector2"](0, 1.0), this._options.blurVerticalSize / 2, { width: blurTextureWidth, height: blurTextureHeight }, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType); this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess]; } this._mainTexture.onAfterUnbindObservable.add(function () { _this.onBeforeBlurObservable.notifyObservers(_this); var internalTexture = _this._blurTexture.getInternalTexture(); if (internalTexture) { _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true); } _this.onAfterBlurObservable.notifyObservers(_this); }); // Prevent autoClear. this._postProcesses.map(function (pp) { pp.autoClear = false; }); }; /** * Returns wether or nood the layer needs stencil enabled during the mesh rendering. */ HighlightLayer.prototype.needStencil = function () { return true; }; /** * Checks for the readiness of the element composing the layer. * @param subMesh the mesh to check for * @param useInstances specify wether or not to use instances to render the mesh * @param emissiveTexture the associated emissive texture used to generate the glow * @return true if ready otherwise, false */ HighlightLayer.prototype.isReady = function (subMesh, useInstances) { var material = subMesh.getMaterial(); var mesh = subMesh.getRenderingMesh(); if (!material || !mesh || !this._meshes) { return false; } var emissiveTexture = null; var highlightLayerMesh = this._meshes[mesh.uniqueId]; if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) { emissiveTexture = material.emissiveTexture; } return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture); }; /** * Implementation specific of rendering the generating effect on the main canvas. * @param effect The effect used to render through */ HighlightLayer.prototype._internalRender = function (effect) { // Texture effect.setTexture("textureSampler", this._blurTexture); // Cache var engine = this._engine; engine.cacheStencilState(); // Stencil operations engine.setStencilOperationPass(_Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].REPLACE); engine.setStencilOperationFail(_Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].KEEP); engine.setStencilOperationDepthFail(_Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].KEEP); // Draw order engine.setStencilMask(0x00); engine.setStencilBuffer(true); engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference); // 2 passes inner outer if (this.outerGlow) { effect.setFloat("offset", 0); engine.setStencilFunction(_Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].NOTEQUAL); engine.drawElementsType(_Materials_material__WEBPACK_IMPORTED_MODULE_6__["Material"].TriangleFillMode, 0, 6); } if (this.innerGlow) { effect.setFloat("offset", 1); engine.setStencilFunction(_Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].EQUAL); engine.drawElementsType(_Materials_material__WEBPACK_IMPORTED_MODULE_6__["Material"].TriangleFillMode, 0, 6); } // Restore Cache engine.restoreStencilState(); }; /** * Returns true if the layer contains information to display, otherwise false. */ HighlightLayer.prototype.shouldRender = function () { if (_super.prototype.shouldRender.call(this)) { return this._meshes ? true : false; } return false; }; /** * Returns true if the mesh should render, otherwise false. * @param mesh The mesh to render * @returns true if it should render otherwise false */ HighlightLayer.prototype._shouldRenderMesh = function (mesh) { // Excluded Mesh if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) { return false; } if (!_super.prototype.hasMesh.call(this, mesh)) { return false; } return true; }; /** * Sets the required values for both the emissive texture and and the main color. */ HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) { var highlightLayerMesh = this._meshes[mesh.uniqueId]; if (highlightLayerMesh) { this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0); } else { this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a); } if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) { this._emissiveTextureAndColor.texture = material.emissiveTexture; this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0); } else { this._emissiveTextureAndColor.texture = null; } }; /** * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer. * @param mesh The mesh to exclude from the highlight layer */ HighlightLayer.prototype.addExcludedMesh = function (mesh) { if (!this._excludedMeshes) { return; } var meshExcluded = this._excludedMeshes[mesh.uniqueId]; if (!meshExcluded) { this._excludedMeshes[mesh.uniqueId] = { mesh: mesh, beforeBind: mesh.onBeforeBindObservable.add(function (mesh) { mesh.getEngine().setStencilBuffer(false); }), afterRender: mesh.onAfterRenderObservable.add(function (mesh) { mesh.getEngine().setStencilBuffer(true); }), }; } }; /** * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer. * @param mesh The mesh to highlight */ HighlightLayer.prototype.removeExcludedMesh = function (mesh) { if (!this._excludedMeshes) { return; } var meshExcluded = this._excludedMeshes[mesh.uniqueId]; if (meshExcluded) { if (meshExcluded.beforeBind) { mesh.onBeforeBindObservable.remove(meshExcluded.beforeBind); } if (meshExcluded.afterRender) { mesh.onAfterRenderObservable.remove(meshExcluded.afterRender); } } this._excludedMeshes[mesh.uniqueId] = null; }; /** * Determine if a given mesh will be highlighted by the current HighlightLayer * @param mesh mesh to test * @returns true if the mesh will be highlighted by the current HighlightLayer */ HighlightLayer.prototype.hasMesh = function (mesh) { if (!this._meshes) { return false; } if (!_super.prototype.hasMesh.call(this, mesh)) { return false; } return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null; }; /** * Add a mesh in the highlight layer in order to make it glow with the chosen color. * @param mesh The mesh to highlight * @param color The color of the highlight * @param glowEmissiveOnly Extract the glow from the emissive texture */ HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) { var _this = this; if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; } if (!this._meshes) { return; } var meshHighlight = this._meshes[mesh.uniqueId]; if (meshHighlight) { meshHighlight.color = color; } else { this._meshes[mesh.uniqueId] = { mesh: mesh, color: color, // Lambda required for capture due to Observable this context observerHighlight: mesh.onBeforeBindObservable.add(function (mesh) { if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) { _this._defaultStencilReference(mesh); } else { mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference); } }), observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference), glowEmissiveOnly: glowEmissiveOnly }; mesh.onDisposeObservable.add(function () { _this._disposeMesh(mesh); }); } this._shouldRender = true; }; /** * Remove a mesh from the highlight layer in order to make it stop glowing. * @param mesh The mesh to highlight */ HighlightLayer.prototype.removeMesh = function (mesh) { if (!this._meshes) { return; } var meshHighlight = this._meshes[mesh.uniqueId]; if (meshHighlight) { if (meshHighlight.observerHighlight) { mesh.onBeforeBindObservable.remove(meshHighlight.observerHighlight); } if (meshHighlight.observerDefault) { mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault); } delete this._meshes[mesh.uniqueId]; } this._shouldRender = false; for (var meshHighlightToCheck in this._meshes) { if (this._meshes[meshHighlightToCheck]) { this._shouldRender = true; break; } } }; /** * Force the stencil to the normal expected value for none glowing parts */ HighlightLayer.prototype._defaultStencilReference = function (mesh) { mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference); }; /** * Free any resources and references associated to a mesh. * Internal use * @param mesh The mesh to free. * @hidden */ HighlightLayer.prototype._disposeMesh = function (mesh) { this.removeMesh(mesh); this.removeExcludedMesh(mesh); }; /** * Dispose the highlight layer and free resources. */ HighlightLayer.prototype.dispose = function () { if (this._meshes) { // Clean mesh references for (var id in this._meshes) { var meshHighlight = this._meshes[id]; if (meshHighlight && meshHighlight.mesh) { if (meshHighlight.observerHighlight) { meshHighlight.mesh.onBeforeBindObservable.remove(meshHighlight.observerHighlight); } if (meshHighlight.observerDefault) { meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault); } } } this._meshes = null; } if (this._excludedMeshes) { for (var id in this._excludedMeshes) { var meshHighlight = this._excludedMeshes[id]; if (meshHighlight) { if (meshHighlight.beforeBind) { meshHighlight.mesh.onBeforeBindObservable.remove(meshHighlight.beforeBind); } if (meshHighlight.afterRender) { meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender); } } } this._excludedMeshes = null; } _super.prototype.dispose.call(this); }; /** * Gets the class name of the effect layer * @returns the string with the class name of the effect layer */ HighlightLayer.prototype.getClassName = function () { return "HighlightLayer"; }; /** * Serializes this Highlight layer * @returns a serialized Highlight layer object */ HighlightLayer.prototype.serialize = function () { var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); serializationObject.customType = "BABYLON.HighlightLayer"; // Highlighted meshes serializationObject.meshes = []; if (this._meshes) { for (var m in this._meshes) { var mesh = this._meshes[m]; if (mesh) { serializationObject.meshes.push({ glowEmissiveOnly: mesh.glowEmissiveOnly, color: mesh.color.asArray(), meshId: mesh.mesh.id }); } } } // Excluded meshes serializationObject.excludedMeshes = []; if (this._excludedMeshes) { for (var e in this._excludedMeshes) { var excludedMesh = this._excludedMeshes[e]; if (excludedMesh) { serializationObject.excludedMeshes.push(excludedMesh.mesh.id); } } } return serializationObject; }; /** * Creates a Highlight layer from parsed Highlight layer data * @param parsedHightlightLayer defines the Highlight layer data * @param scene defines the current scene * @param rootUrl defines the root URL containing the Highlight layer information * @returns a parsed Highlight layer */ HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) { var hl = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl); var index; // Excluded meshes for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) { var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]); if (mesh) { hl.addExcludedMesh(mesh); } } // Included meshes for (index = 0; index < parsedHightlightLayer.meshes.length; index++) { var highlightedMesh = parsedHightlightLayer.meshes[index]; var mesh = scene.getMeshByID(highlightedMesh.meshId); if (mesh) { hl.addMesh(mesh, _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Color3"].FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly); } } return hl; }; /** * Effect Name of the highlight layer. */ HighlightLayer.EffectName = "HighlightLayer"; /** * The neutral color used during the preparation of the glow effect. * This is black by default as the blend operation is a blend operation. */ HighlightLayer.NeutralColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Color4"](0, 0, 0, 0); /** * Stencil value used for glowing meshes. */ HighlightLayer.GlowingMeshStencilReference = 0x02; /** * Stencil value used for the other meshes in the scene. */ HighlightLayer.NormalMeshStencilReference = 0x01; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], HighlightLayer.prototype, "innerGlow", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], HighlightLayer.prototype, "outerGlow", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], HighlightLayer.prototype, "blurHorizontalSize", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], HighlightLayer.prototype, "blurVerticalSize", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("options") ], HighlightLayer.prototype, "_options", void 0); return HighlightLayer; }(_effectLayer__WEBPACK_IMPORTED_MODULE_12__["EffectLayer"])); _Misc_typeStore__WEBPACK_IMPORTED_MODULE_16__["_TypeStore"].RegisteredTypes["BABYLON.HighlightLayer"] = HighlightLayer; /***/ }), /***/ "./Layers/index.ts": /*!*************************!*\ !*** ./Layers/index.ts ***! \*************************/ /*! exports provided: EffectLayer, EffectLayerSceneComponent, GlowLayer, HighlightLayer, Layer, LayerSceneComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _effectLayer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./effectLayer */ "./Layers/effectLayer.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EffectLayer", function() { return _effectLayer__WEBPACK_IMPORTED_MODULE_0__["EffectLayer"]; }); /* harmony import */ var _effectLayerSceneComponent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./effectLayerSceneComponent */ "./Layers/effectLayerSceneComponent.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EffectLayerSceneComponent", function() { return _effectLayerSceneComponent__WEBPACK_IMPORTED_MODULE_1__["EffectLayerSceneComponent"]; }); /* harmony import */ var _glowLayer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./glowLayer */ "./Layers/glowLayer.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GlowLayer", function() { return _glowLayer__WEBPACK_IMPORTED_MODULE_2__["GlowLayer"]; }); /* harmony import */ var _highlightLayer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./highlightLayer */ "./Layers/highlightLayer.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HighlightLayer", function() { return _highlightLayer__WEBPACK_IMPORTED_MODULE_3__["HighlightLayer"]; }); /* harmony import */ var _layer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./layer */ "./Layers/layer.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Layer", function() { return _layer__WEBPACK_IMPORTED_MODULE_4__["Layer"]; }); /* harmony import */ var _layerSceneComponent__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./layerSceneComponent */ "./Layers/layerSceneComponent.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LayerSceneComponent", function() { return _layerSceneComponent__WEBPACK_IMPORTED_MODULE_5__["LayerSceneComponent"]; }); /***/ }), /***/ "./Layers/layer.ts": /*!*************************!*\ !*** ./Layers/layer.ts ***! \*************************/ /*! exports provided: Layer */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Layer", function() { return Layer; }); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts"); /* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Meshes/buffer */ "./Meshes/buffer.ts"); /* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Materials/material */ "./Materials/material.ts"); /* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); /* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../sceneComponent */ "./sceneComponent.ts"); /* harmony import */ var _layerSceneComponent__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./layerSceneComponent */ "./Layers/layerSceneComponent.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); /* harmony import */ var _Shaders_layer_fragment__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Shaders/layer.fragment */ "./Shaders/layer.fragment.ts"); /* harmony import */ var _Shaders_layer_vertex__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Shaders/layer.vertex */ "./Shaders/layer.vertex.ts"); /** * This represents a full screen 2d layer. * This can be useful to display a picture in the background of your scene for instance. * @see https://www.babylonjs-playground.com/#08A2BS#1 */ var Layer = /** @class */ (function () { /** * Instantiates a new layer. * This represents a full screen 2d layer. * This can be useful to display a picture in the background of your scene for instance. * @see https://www.babylonjs-playground.com/#08A2BS#1 * @param name Define the name of the layer in the scene * @param imgUrl Define the url of the texture to display in the layer * @param scene Define the scene the layer belongs to * @param isBackground Defines whether the layer is displayed in front or behind the scene * @param color Defines a color for the layer */ function Layer( /** * Define the name of the layer. */ name, imgUrl, scene, isBackground, color) { this.name = name; /** * Define the scale of the layer in order to zoom in out of the texture. */ this.scale = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector2"](1, 1); /** * Define an offset for the layer in order to shift the texture. */ this.offset = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector2"](0, 0); /** * Define the alpha blending mode used in the layer in case the texture or color has an alpha. */ this.alphaBlendingMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].ALPHA_COMBINE; /** * Define a mask to restrict the layer to only some of the scene cameras. */ this.layerMask = 0x0FFFFFFF; /** * Define the list of render target the layer is visible into. */ this.renderTargetTextures = []; /** * Define if the layer is only used in renderTarget or if it also * renders in the main frame buffer of the canvas. */ this.renderOnlyInRenderTargetTextures = false; this._vertexBuffers = {}; /** * An event triggered when the layer is disposed. */ this.onDisposeObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); /** * An event triggered before rendering the scene */ this.onBeforeRenderObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); /** * An event triggered after rendering the scene */ this.onAfterRenderObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); this.texture = imgUrl ? new _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"](imgUrl, scene, true) : null; this.isBackground = isBackground === undefined ? true : isBackground; this.color = color === undefined ? new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color4"](1, 1, 1, 1) : color; this._scene = (scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_2__["EngineStore"].LastCreatedScene); var layerComponent = this._scene._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_6__["SceneComponentConstants"].NAME_LAYER); if (!layerComponent) { layerComponent = new _layerSceneComponent__WEBPACK_IMPORTED_MODULE_7__["LayerSceneComponent"](this._scene); this._scene._addComponent(layerComponent); } this._scene.layers.push(this); var engine = this._scene.getEngine(); // VBO var vertices = []; vertices.push(1, 1); vertices.push(-1, 1); vertices.push(-1, -1); vertices.push(1, -1); var vertexBuffer = new _Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"](engine, vertices, _Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind, false, false, 2); this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind] = vertexBuffer; this._createIndexBuffer(); // Effects this._effect = engine.createEffect("layer", [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], ""); this._alphaTestEffect = engine.createEffect("layer", [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST"); } Object.defineProperty(Layer.prototype, "onDispose", { /** * Back compatibility with callback before the onDisposeObservable existed. * The set callback will be triggered when the layer has been disposed. */ set: function (callback) { if (this._onDisposeObserver) { this.onDisposeObservable.remove(this._onDisposeObserver); } this._onDisposeObserver = this.onDisposeObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(Layer.prototype, "onBeforeRender", { /** * Back compatibility with callback before the onBeforeRenderObservable existed. * The set callback will be triggered just before rendering the layer. */ set: function (callback) { if (this._onBeforeRenderObserver) { this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver); } this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(Layer.prototype, "onAfterRender", { /** * Back compatibility with callback before the onAfterRenderObservable existed. * The set callback will be triggered just after rendering the layer. */ set: function (callback) { if (this._onAfterRenderObserver) { this.onAfterRenderObservable.remove(this._onAfterRenderObserver); } this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback); }, enumerable: true, configurable: true }); Layer.prototype._createIndexBuffer = function () { var engine = this._scene.getEngine(); // Indices var indices = []; indices.push(0); indices.push(1); indices.push(2); indices.push(0); indices.push(2); indices.push(3); this._indexBuffer = engine.createIndexBuffer(indices); }; /** @hidden */ Layer.prototype._rebuild = function () { var vb = this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind]; if (vb) { vb._rebuild(); } this._createIndexBuffer(); }; /** * Renders the layer in the scene. */ Layer.prototype.render = function () { var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect; // Check if (!currentEffect.isReady() || !this.texture || !this.texture.isReady()) { return; } var engine = this._scene.getEngine(); this.onBeforeRenderObservable.notifyObservers(this); // Render engine.enableEffect(currentEffect); engine.setState(false); // Texture currentEffect.setTexture("textureSampler", this.texture); currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix()); // Color currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a); // Scale / offset currentEffect.setVector2("offset", this.offset); currentEffect.setVector2("scale", this.scale); // VBOs engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect); // Draw order if (!this.alphaTest) { engine.setAlphaMode(this.alphaBlendingMode); engine.drawElementsType(_Materials_material__WEBPACK_IMPORTED_MODULE_4__["Material"].TriangleFillMode, 0, 6); engine.setAlphaMode(_Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].ALPHA_DISABLE); } else { engine.drawElementsType(_Materials_material__WEBPACK_IMPORTED_MODULE_4__["Material"].TriangleFillMode, 0, 6); } this.onAfterRenderObservable.notifyObservers(this); }; /** * Disposes and releases the associated ressources. */ Layer.prototype.dispose = function () { var vertexBuffer = this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind]; if (vertexBuffer) { vertexBuffer.dispose(); this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind] = null; } if (this._indexBuffer) { this._scene.getEngine()._releaseBuffer(this._indexBuffer); this._indexBuffer = null; } if (this.texture) { this.texture.dispose(); this.texture = null; } // Clean RTT list this.renderTargetTextures = []; // Remove from scene var index = this._scene.layers.indexOf(this); this._scene.layers.splice(index, 1); // Callback this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); this.onAfterRenderObservable.clear(); this.onBeforeRenderObservable.clear(); }; return Layer; }()); /***/ }), /***/ "./Layers/layerSceneComponent.ts": /*!***************************************!*\ !*** ./Layers/layerSceneComponent.ts ***! \***************************************/ /*! exports provided: LayerSceneComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LayerSceneComponent", function() { return LayerSceneComponent; }); /* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../sceneComponent */ "./sceneComponent.ts"); /** * Defines the layer scene component responsible to manage any layers * in a given scene. */ var LayerSceneComponent = /** @class */ (function () { /** * Creates a new instance of the component for the given scene * @param scene Defines the scene to register the component in */ function LayerSceneComponent(scene) { /** * The component name helpfull to identify the component in the list of scene components. */ this.name = _sceneComponent__WEBPACK_IMPORTED_MODULE_0__["SceneComponentConstants"].NAME_LAYER; this.scene = scene; this._engine = scene.getEngine(); scene.layers = new Array(); } /** * Registers the component in a given scene */ LayerSceneComponent.prototype.register = function () { this.scene._beforeCameraDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_0__["SceneComponentConstants"].STEP_BEFORECAMERADRAW_LAYER, this, this._drawCameraBackground); this.scene._afterCameraDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_0__["SceneComponentConstants"].STEP_AFTERCAMERADRAW_LAYER, this, this._drawCameraForeground); this.scene._beforeRenderTargetDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_0__["SceneComponentConstants"].STEP_BEFORERENDERTARGETDRAW_LAYER, this, this._drawRenderTargetBackground); this.scene._afterRenderTargetDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_0__["SceneComponentConstants"].STEP_AFTERRENDERTARGETDRAW_LAYER, this, this._drawRenderTargetForeground); }; /** * Rebuilds the elements related to this component in case of * context lost for instance. */ LayerSceneComponent.prototype.rebuild = function () { var layers = this.scene.layers; for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) { var layer = layers_1[_i]; layer._rebuild(); } }; /** * Disposes the component and the associated ressources. */ LayerSceneComponent.prototype.dispose = function () { var layers = this.scene.layers; while (layers.length) { layers[0].dispose(); } }; LayerSceneComponent.prototype._draw = function (predicate) { var layers = this.scene.layers; if (layers.length) { this._engine.setDepthBuffer(false); for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) { var layer = layers_2[_i]; if (predicate(layer)) { layer.render(); } } this._engine.setDepthBuffer(true); } }; LayerSceneComponent.prototype._drawCameraPredicate = function (layer, isBackground, cameraLayerMask) { return !layer.renderOnlyInRenderTargetTextures && layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0); }; LayerSceneComponent.prototype._drawCameraBackground = function (camera) { var _this = this; this._draw(function (layer) { return _this._drawCameraPredicate(layer, true, camera.layerMask); }); }; LayerSceneComponent.prototype._drawCameraForeground = function (camera) { var _this = this; this._draw(function (layer) { return _this._drawCameraPredicate(layer, false, camera.layerMask); }); }; LayerSceneComponent.prototype._drawRenderTargetPredicate = function (layer, isBackground, cameraLayerMask, renderTargetTexture) { return (layer.renderTargetTextures.length > 0) && layer.isBackground === isBackground && (layer.renderTargetTextures.indexOf(renderTargetTexture) > -1) && ((layer.layerMask & cameraLayerMask) !== 0); }; LayerSceneComponent.prototype._drawRenderTargetBackground = function (renderTarget) { var _this = this; this._draw(function (layer) { return _this._drawRenderTargetPredicate(layer, true, _this.scene.activeCamera.layerMask, renderTarget); }); }; LayerSceneComponent.prototype._drawRenderTargetForeground = function (renderTarget) { var _this = this; this._draw(function (layer) { return _this._drawRenderTargetPredicate(layer, false, _this.scene.activeCamera.layerMask, renderTarget); }); }; return LayerSceneComponent; }()); /***/ }), /***/ "./Legacy/legacy.ts": /*!**************************!*\ !*** ./Legacy/legacy.ts ***! \**************************/ /*! exports provided: Debug, AbstractScene, KeepAssets, AssetContainer, Node, Scene, SceneComponentConstants, Stage, Action, ActionEvent, ActionManager, Condition, ValueCondition, PredicateCondition, StateCondition, SwitchBooleanAction, SetStateAction, SetValueAction, IncrementValueAction, PlayAnimationAction, StopAnimationAction, DoNothingAction, CombineAction, ExecuteCodeAction, SetParentAction, PlaySoundAction, StopSoundAction, InterpolateValueAction, Animatable, Animation, TargetedAnimation, AnimationGroup, AnimationPropertiesOverride, EasingFunction, CircleEase, BackEase, BounceEase, CubicEase, ElasticEase, ExponentialEase, PowerEase, QuadraticEase, QuarticEase, QuinticEase, SineEase, BezierCurveEase, RuntimeAnimation, AnimationEvent, AnimationKeyInterpolation, AnimationRange, Analyser, AudioEngine, AudioSceneComponent, Sound, SoundTrack, WeightedSound, Bone, BoneIKController, BoneLookController, Skeleton, CameraInputTypes, CameraInputsManager, Camera, TargetCamera, FreeCamera, FreeCameraInputsManager, TouchCamera, ArcRotateCamera, ArcRotateCameraInputsManager, DeviceOrientationCamera, FlyCamera, FlyCameraInputsManager, FollowCamera, ArcFollowCamera, GamepadCamera, UniversalCamera, VirtualJoysticksCamera, Collider, DefaultCollisionCoordinator, PickingInfo, IntersectionInfo, BoundingBox, BoundingInfo, BoundingSphere, Ray, AxesViewer, BoneAxesViewer, DebugLayer, PhysicsViewer, RayHelper, SkeletonViewer, Constants, InstancingAttributeInfo, DepthTextureCreationOptions, EngineCapabilities, Engine, EngineStore, NullEngineOptions, NullEngine, KeyboardEventTypes, KeyboardInfo, KeyboardInfoPre, PointerEventTypes, PointerInfoBase, PointerInfoPre, PointerInfo, ClipboardEventTypes, ClipboardInfo, DaydreamController, GearVRController, GenericController, OculusTouchController, PoseEnabledControllerType, PoseEnabledControllerHelper, PoseEnabledController, ViveController, WebVRController, WindowsMotionController, StickValues, Gamepad, GenericPad, GamepadManager, GamepadSystemSceneComponent, Xbox360Button, Xbox360Dpad, Xbox360Pad, AxisDragGizmo, AxisScaleGizmo, BoundingBoxGizmo, Gizmo, GizmoManager, PlaneRotationGizmo, PositionGizmo, RotationGizmo, ScaleGizmo, LightGizmo, EnvironmentHelper, PhotoDome, _forceSceneHelpersToBundle, VideoDome, EngineInstrumentation, SceneInstrumentation, _TimeToken, EffectLayer, EffectLayerSceneComponent, GlowLayer, HighlightLayer, Layer, LayerSceneComponent, LensFlare, LensFlareSystem, LensFlareSystemSceneComponent, Light, ShadowLight, DirectionalLight, HemisphericLight, PointLight, SpotLight, DefaultLoadingScreen, SceneLoaderProgressEvent, SceneLoader, SceneLoaderFlags, ColorCurves, EffectFallbacks, EffectCreationOptions, Effect, FresnelParameters, ImageProcessingConfigurationDefines, ImageProcessingConfiguration, Material, MaterialDefines, MaterialHelper, MultiMaterial, PushMaterial, ShaderMaterial, StandardMaterialDefines, StandardMaterial, BaseTexture, CubeTexture, EquiRectangularCubeTexture, HDRCubeTexture, InternalTexture, MirrorTexture, MultiRenderTarget, RawTexture, RenderTargetTexture, Texture, UniformBuffer, MaterialFlags, Scalar, ToGammaSpace, ToLinearSpace, Epsilon, Color3, Color4, Vector2, Vector3, Vector4, Size, Quaternion, Matrix, Plane, Viewport, Frustum, Space, Axis, BezierCurve, Orientation, Angle, Arc2, Path2, Path3D, Curve3, PositionNormalVertex, PositionNormalTextureVertex, Tmp, SphericalPolynomial, SphericalHarmonics, AbstractMesh, Buffer, VertexBuffer, CSG, Geometry, GroundMesh, TrailMesh, InstancedMesh, LinesMesh, InstancedLinesMesh, MeshLODLevel, _CreationDataStorage, _InstancesBatch, Mesh, VertexData, MeshBuilder, SimplificationSettings, SimplificationQueue, SimplificationType, SimplicationQueueSceneComponent, Polygon, PolygonMeshBuilder, BaseSubMesh, SubMesh, TransformNode, BoxBuilder, SphereBuilder, CylinderBuilder, LinesBuilder, PlaneBuilder, MorphTarget, MorphTargetManager, Database, BaseParticleSystem, GPUParticleSystem, Particle, ParticleHelper, ParticleSystem, _IDoNeedToBeInTheBuild, ParticleSystemSet, SolidParticle, ModelShape, DepthSortedParticle, SolidParticleSystem, SubEmitterType, SubEmitter, PhysicsEngine, PhysicsEngineSceneComponent, PhysicsHelper, PhysicsRadialExplosionEventOptions, PhysicsUpdraftEventOptions, PhysicsVortexEventOptions, PhysicsRadialImpulseFalloff, PhysicsUpdraftMode, PhysicsImpostor, PhysicsJoint, DistanceJoint, MotorEnabledJoint, HingeJoint, Hinge2Joint, AnaglyphPostProcess, BlackAndWhitePostProcess, BloomEffect, BloomMergePostProcess, BlurPostProcess, ChromaticAberrationPostProcess, CircleOfConfusionPostProcess, ColorCorrectionPostProcess, ConvolutionPostProcess, DepthOfFieldBlurPostProcess, DepthOfFieldEffectBlurLevel, DepthOfFieldEffect, DepthOfFieldMergePostProcessOptions, DepthOfFieldMergePostProcess, DisplayPassPostProcess, ExtractHighlightsPostProcess, FilterPostProcess, FxaaPostProcess, GrainPostProcess, HighlightsPostProcess, ImageProcessingPostProcess, MotionBlurPostProcess, PassPostProcess, PassCubePostProcess, PostProcess, PostProcessManager, RefractionPostProcess, SharpenPostProcess, StereoscopicInterlacePostProcess, TonemappingOperator, TonemapPostProcess, VolumetricLightScatteringPostProcess, VRDistortionCorrectionPostProcess, VRMultiviewToSingleviewPostProcess, ReflectionProbe, BoundingBoxRenderer, DepthRenderer, DepthRendererSceneComponent, EdgesRenderer, LineEdgesRenderer, GeometryBufferRenderer, GeometryBufferRendererSceneComponent, OutlineRenderer, RenderingGroup, RenderingGroupInfo, RenderingManager, UtilityLayerRenderer, Sprite, SpriteManager, SpriteSceneComponent, _AlphaState, _DepthCullingState, _StencilState, AndOrNotEvaluator, AssetTaskState, AbstractAssetTask, AssetsProgressEvent, MeshAssetTask, TextFileAssetTask, BinaryFileAssetTask, ImageAssetTask, TextureAssetTask, CubeTextureAssetTask, HDRCubeTextureAssetTask, EquiRectangularCubeTextureAssetTask, AssetsManager, DDSTools, expandToProperty, serialize, serializeAsTexture, serializeAsColor3, serializeAsFresnelParameters, serializeAsVector2, serializeAsVector3, serializeAsMeshReference, serializeAsColorCurves, serializeAsColor4, serializeAsImageProcessingConfiguration, serializeAsQuaternion, serializeAsMatrix, serializeAsCameraReference, SerializationHelper, Deferred, EnvironmentTextureTools, MeshExploder, FilesInput, KhronosTextureContainer, EventState, Observer, MultiObserver, Observable, PerformanceMonitor, RollingAverage, PromisePolyfill, SceneOptimization, TextureOptimization, HardwareScalingOptimization, ShadowsOptimization, PostProcessesOptimization, LensFlaresOptimization, CustomOptimization, ParticlesOptimization, RenderTargetsOptimization, MergeMeshesOptimization, SceneOptimizerOptions, SceneOptimizer, SceneSerializer, SmartArray, SmartArrayNoDuplicate, StringDictionary, Tags, TextureTools, TGATools, ColorGradient, Color3Gradient, FactorGradient, LoadFileError, RetryStrategy, Tools, PerfCounter, className, AsyncLoop, VideoRecorder, JoystickAxis, VirtualJoystick, WorkerPool, Logger, _TypeStore, FilesInputStore, DeepCopier, PivotTools, PrecisionDate, ScreenshotTools, WebRequest, InspectableType, AutoRotationBehavior, BouncingBehavior, FramingBehavior, AttachToBoxBehavior, FadeInOutBehavior, MultiPointerScaleBehavior, PointerDragBehavior, SixDofDragBehavior, ArcRotateCameraGamepadInput, ArcRotateCameraKeyboardMoveInput, ArcRotateCameraMouseWheelInput, ArcRotateCameraPointersInput, ArcRotateCameraVRDeviceOrientationInput, FlyCameraKeyboardInput, FlyCameraMouseInput, FollowCameraKeyboardMoveInput, FollowCameraMouseWheelInput, FollowCameraPointersInput, FreeCameraDeviceOrientationInput, FreeCameraGamepadInput, FreeCameraKeyboardMoveInput, FreeCameraMouseInput, FreeCameraTouchInput, FreeCameraVirtualJoystickInput, AnaglyphArcRotateCamera, AnaglyphFreeCamera, AnaglyphGamepadCamera, AnaglyphUniversalCamera, StereoscopicArcRotateCamera, StereoscopicFreeCamera, StereoscopicGamepadCamera, StereoscopicUniversalCamera, VRCameraMetrics, VRDeviceOrientationArcRotateCamera, VRDeviceOrientationFreeCamera, VRDeviceOrientationGamepadCamera, OnAfterEnteringVRObservableEvent, VRExperienceHelper, WebVRFreeCamera, WebXRCamera, WebXREnterExitUIButton, WebXREnterExitUIOptions, WebXREnterExitUI, WebXRState, WebXRExperienceHelper, WebXRController, WebXRInput, WebXRManagedOutputCanvas, WebXRSessionManager, Octree, OctreeBlock, OctreeSceneComponent, _OcclusionDataStorage, _forceTransformFeedbackToBundle, ShadowGenerator, ShadowGeneratorSceneComponent, _BabylonLoaderRegistered, BackgroundMaterial, PBRMaterialDefines, PBRBaseMaterial, PBRBaseSimpleMaterial, PBRMaterial, PBRMetallicRoughnessMaterial, PBRSpecularGlossinessMaterial, ColorGradingTexture, DynamicTexture, ProceduralTexture, RawCubeTexture, RawTexture3D, RefractionTexture, VideoTexture, DracoCompression, DiscBuilder, RibbonBuilder, HemisphereBuilder, TorusBuilder, TorusKnotBuilder, PolygonBuilder, ShapeBuilder, LatheBuilder, GroundBuilder, TubeBuilder, PolyhedronBuilder, IcoSphereBuilder, DecalBuilder, BoxParticleEmitter, ConeParticleEmitter, CylinderParticleEmitter, CylinderDirectedParticleEmitter, HemisphericParticleEmitter, PointParticleEmitter, SphereParticleEmitter, SphereDirectedParticleEmitter, CannonJSPlugin, AmmoJSPlugin, OimoJSPlugin, PostProcessRenderEffect, PostProcessRenderPipeline, PostProcessRenderPipelineManager, PostProcessRenderPipelineManagerSceneComponent, CubeMapToSphericalPolynomialTools, HDRTools, PanoramaToCubeMapTools, _DDSTextureLoader, _ENVTextureLoader, _KTXTextureLoader, _TGATextureLoader, CustomProceduralTexture, NoiseProceduralTexture, ProceduralTextureSceneComponent, DefaultRenderingPipeline, LensRenderingPipeline, SSAO2RenderingPipeline, SSAORenderingPipeline, StandardRenderingPipeline */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Debug", function() { return Debug; }); /* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../index */ "./index.ts"); /* harmony import */ var _Debug_index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Debug/index */ "./Debug/index.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AbstractScene", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AbstractScene"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeepAssets", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["KeepAssets"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AssetContainer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AssetContainer"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Node", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Node"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Scene", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Scene"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneComponentConstants", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneComponentConstants"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Stage", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Stage"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Action", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Action"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ActionEvent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ActionEvent"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ActionManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ActionManager"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Condition", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Condition"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ValueCondition", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ValueCondition"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PredicateCondition", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PredicateCondition"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StateCondition", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StateCondition"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SwitchBooleanAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SwitchBooleanAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SetStateAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SetStateAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SetValueAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SetValueAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IncrementValueAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["IncrementValueAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlayAnimationAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PlayAnimationAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StopAnimationAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StopAnimationAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DoNothingAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DoNothingAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CombineAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CombineAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ExecuteCodeAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ExecuteCodeAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SetParentAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SetParentAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlaySoundAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PlaySoundAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StopSoundAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StopSoundAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InterpolateValueAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["InterpolateValueAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Animatable", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Animatable"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Animation", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Animation"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TargetedAnimation", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TargetedAnimation"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationGroup", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnimationGroup"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationPropertiesOverride", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnimationPropertiesOverride"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EasingFunction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EasingFunction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CircleEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CircleEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BackEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BackEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BounceEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BounceEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CubicEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CubicEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ElasticEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ElasticEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ExponentialEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ExponentialEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PowerEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PowerEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "QuadraticEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["QuadraticEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "QuarticEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["QuarticEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "QuinticEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["QuinticEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SineEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SineEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BezierCurveEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BezierCurveEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RuntimeAnimation", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RuntimeAnimation"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationEvent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnimationEvent"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationKeyInterpolation", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnimationKeyInterpolation"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationRange", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnimationRange"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Analyser", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Analyser"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AudioEngine", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AudioEngine"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AudioSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AudioSceneComponent"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Sound", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Sound"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SoundTrack", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SoundTrack"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WeightedSound", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WeightedSound"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Bone", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Bone"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoneIKController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoneIKController"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoneLookController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoneLookController"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Skeleton", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Skeleton"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CameraInputTypes", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CameraInputTypes"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CameraInputsManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CameraInputsManager"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Camera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Camera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TargetCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TargetCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FreeCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraInputsManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraInputsManager"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TouchCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TouchCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraInputsManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraInputsManager"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DeviceOrientationCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DeviceOrientationCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FlyCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCameraInputsManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FlyCameraInputsManager"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FollowCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcFollowCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcFollowCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GamepadCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GamepadCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UniversalCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["UniversalCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VirtualJoysticksCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VirtualJoysticksCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Collider", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Collider"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DefaultCollisionCoordinator", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DefaultCollisionCoordinator"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PickingInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PickingInfo"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IntersectionInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["IntersectionInfo"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingBox", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoundingBox"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoundingInfo"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingSphere", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoundingSphere"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Ray", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Ray"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AxesViewer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AxesViewer"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoneAxesViewer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoneAxesViewer"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DebugLayer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DebugLayer"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsViewer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsViewer"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RayHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RayHelper"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SkeletonViewer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SkeletonViewer"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Constants", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Constants"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InstancingAttributeInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["InstancingAttributeInfo"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthTextureCreationOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthTextureCreationOptions"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EngineCapabilities", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EngineCapabilities"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Engine", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Engine"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EngineStore", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EngineStore"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NullEngineOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NullEngineOptions"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NullEngine", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NullEngine"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyboardEventTypes", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["KeyboardEventTypes"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyboardInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["KeyboardInfo"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyboardInfoPre", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["KeyboardInfoPre"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerEventTypes", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerInfoBase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointerInfoBase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerInfoPre", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointerInfoPre"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointerInfo"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClipboardEventTypes", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ClipboardEventTypes"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClipboardInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ClipboardInfo"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DaydreamController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DaydreamController"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GearVRController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GearVRController"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GenericController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GenericController"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OculusTouchController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["OculusTouchController"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledControllerType", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PoseEnabledControllerType"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledControllerHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PoseEnabledControllerHelper"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PoseEnabledController"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ViveController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ViveController"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebVRController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebVRController"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WindowsMotionController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WindowsMotionController"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StickValues", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StickValues"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Gamepad", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Gamepad"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GenericPad", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GenericPad"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GamepadManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GamepadManager"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GamepadSystemSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GamepadSystemSceneComponent"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Xbox360Button", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Xbox360Button"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Xbox360Dpad", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Xbox360Dpad"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Xbox360Pad", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Xbox360Pad"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AxisDragGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AxisDragGizmo"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AxisScaleGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AxisScaleGizmo"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingBoxGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoundingBoxGizmo"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Gizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Gizmo"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GizmoManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GizmoManager"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlaneRotationGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PlaneRotationGizmo"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PositionGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PositionGizmo"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RotationGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RotationGizmo"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScaleGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ScaleGizmo"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LightGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LightGizmo"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EnvironmentHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EnvironmentHelper"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhotoDome", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhotoDome"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_forceSceneHelpersToBundle", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_forceSceneHelpersToBundle"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VideoDome", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VideoDome"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EngineInstrumentation", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EngineInstrumentation"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneInstrumentation", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneInstrumentation"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_TimeToken", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_TimeToken"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EffectLayer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EffectLayer"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EffectLayerSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EffectLayerSceneComponent"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GlowLayer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GlowLayer"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HighlightLayer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HighlightLayer"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Layer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Layer"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LayerSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LayerSceneComponent"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LensFlare", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LensFlare"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LensFlareSystem", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LensFlareSystem"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LensFlareSystemSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LensFlareSystemSceneComponent"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Light", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Light"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowLight", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ShadowLight"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DirectionalLight", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DirectionalLight"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HemisphericLight", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HemisphericLight"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointLight", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointLight"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SpotLight", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SpotLight"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DefaultLoadingScreen", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DefaultLoadingScreen"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneLoaderProgressEvent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneLoaderProgressEvent"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneLoader", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneLoader"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneLoaderFlags", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneLoaderFlags"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorCurves", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ColorCurves"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EffectFallbacks", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EffectFallbacks"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EffectCreationOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EffectCreationOptions"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Effect", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Effect"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FresnelParameters", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FresnelParameters"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingConfigurationDefines", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ImageProcessingConfigurationDefines"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingConfiguration", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ImageProcessingConfiguration"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Material", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Material"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MaterialDefines", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MaterialDefines"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MaterialHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MaterialHelper"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MultiMaterial"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PushMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PushMaterial"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShaderMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ShaderMaterial"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StandardMaterialDefines", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StandardMaterialDefines"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StandardMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StandardMaterial"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BaseTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BaseTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CubeTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CubeTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EquiRectangularCubeTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EquiRectangularCubeTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HDRCubeTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HDRCubeTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InternalTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["InternalTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MirrorTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MirrorTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiRenderTarget", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MultiRenderTarget"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RawTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RawTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RenderTargetTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RenderTargetTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Texture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Texture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UniformBuffer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["UniformBuffer"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MaterialFlags", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MaterialFlags"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Scalar", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Scalar"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ToGammaSpace", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ToGammaSpace"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ToLinearSpace", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ToLinearSpace"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Epsilon", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Epsilon"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Color3", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Color3"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Color4", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Color4"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector2", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Vector2"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector3", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Vector3"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector4", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Vector4"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Size", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Size"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Quaternion", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Quaternion"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Matrix", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Matrix"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Plane", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Plane"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Viewport", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Viewport"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Frustum", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Frustum"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Space", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Space"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Axis", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Axis"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BezierCurve", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BezierCurve"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Orientation", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Orientation"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Angle", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Angle"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Arc2", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Arc2"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Path2", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Path2"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Path3D", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Path3D"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Curve3", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Curve3"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PositionNormalVertex", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PositionNormalVertex"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PositionNormalTextureVertex", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PositionNormalTextureVertex"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Tmp", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Tmp"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SphericalPolynomial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SphericalPolynomial"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SphericalHarmonics", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SphericalHarmonics"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AbstractMesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AbstractMesh"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Buffer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Buffer"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VertexBuffer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CSG", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CSG"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Geometry", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Geometry"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GroundMesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GroundMesh"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TrailMesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TrailMesh"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InstancedMesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["InstancedMesh"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LinesMesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LinesMesh"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InstancedLinesMesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["InstancedLinesMesh"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MeshLODLevel", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MeshLODLevel"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_CreationDataStorage", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_CreationDataStorage"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_InstancesBatch", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_InstancesBatch"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Mesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Mesh"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VertexData", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VertexData"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MeshBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MeshBuilder"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SimplificationSettings", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SimplificationSettings"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SimplificationQueue", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SimplificationQueue"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SimplificationType", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SimplificationType"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SimplicationQueueSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SimplicationQueueSceneComponent"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Polygon", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Polygon"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PolygonMeshBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PolygonMeshBuilder"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BaseSubMesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BaseSubMesh"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubMesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SubMesh"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransformNode", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TransformNode"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoxBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoxBuilder"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SphereBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SphereBuilder"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CylinderBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CylinderBuilder"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LinesBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LinesBuilder"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlaneBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PlaneBuilder"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MorphTarget", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MorphTarget"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MorphTargetManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MorphTargetManager"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Database", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Database"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BaseParticleSystem", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BaseParticleSystem"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GPUParticleSystem", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GPUParticleSystem"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Particle", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Particle"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ParticleHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ParticleHelper"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ParticleSystem", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ParticleSystem"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_IDoNeedToBeInTheBuild", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_IDoNeedToBeInTheBuild"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ParticleSystemSet", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ParticleSystemSet"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SolidParticle", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SolidParticle"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ModelShape", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ModelShape"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthSortedParticle", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthSortedParticle"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SolidParticleSystem", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SolidParticleSystem"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubEmitterType", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SubEmitterType"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SubEmitter"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsEngine", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsEngine"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsEngineSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsEngineSceneComponent"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsHelper"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsRadialExplosionEventOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsRadialExplosionEventOptions"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsUpdraftEventOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsUpdraftEventOptions"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsVortexEventOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsVortexEventOptions"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsRadialImpulseFalloff", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsRadialImpulseFalloff"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsUpdraftMode", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsUpdraftMode"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsImpostor", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsImpostor"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsJoint", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsJoint"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DistanceJoint", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DistanceJoint"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MotorEnabledJoint", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MotorEnabledJoint"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HingeJoint", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HingeJoint"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Hinge2Joint", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Hinge2Joint"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnaglyphPostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BlackAndWhitePostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BlackAndWhitePostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BloomEffect", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BloomEffect"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BloomMergePostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BloomMergePostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BlurPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BlurPostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ChromaticAberrationPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ChromaticAberrationPostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CircleOfConfusionPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CircleOfConfusionPostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorCorrectionPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ColorCorrectionPostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ConvolutionPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ConvolutionPostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthOfFieldBlurPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthOfFieldBlurPostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthOfFieldEffectBlurLevel", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthOfFieldEffectBlurLevel"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthOfFieldEffect", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthOfFieldEffect"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthOfFieldMergePostProcessOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthOfFieldMergePostProcessOptions"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthOfFieldMergePostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthOfFieldMergePostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DisplayPassPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DisplayPassPostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ExtractHighlightsPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ExtractHighlightsPostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FilterPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FilterPostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FxaaPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FxaaPostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GrainPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GrainPostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HighlightsPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HighlightsPostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ImageProcessingPostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MotionBlurPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MotionBlurPostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PassPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PassPostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PassCubePostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PassCubePostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PostProcessManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PostProcessManager"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RefractionPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RefractionPostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SharpenPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SharpenPostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicInterlacePostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StereoscopicInterlacePostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TonemappingOperator", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TonemappingOperator"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TonemapPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TonemapPostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VolumetricLightScatteringPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VolumetricLightScatteringPostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDistortionCorrectionPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VRDistortionCorrectionPostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRMultiviewToSingleviewPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VRMultiviewToSingleviewPostProcess"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReflectionProbe", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ReflectionProbe"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingBoxRenderer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoundingBoxRenderer"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthRenderer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthRenderer"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthRendererSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthRendererSceneComponent"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EdgesRenderer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EdgesRenderer"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LineEdgesRenderer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LineEdgesRenderer"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GeometryBufferRenderer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GeometryBufferRenderer"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GeometryBufferRendererSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GeometryBufferRendererSceneComponent"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OutlineRenderer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["OutlineRenderer"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RenderingGroup", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RenderingGroup"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RenderingGroupInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RenderingGroupInfo"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RenderingManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RenderingManager"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UtilityLayerRenderer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["UtilityLayerRenderer"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Sprite", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Sprite"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SpriteManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SpriteManager"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SpriteSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SpriteSceneComponent"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_AlphaState", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_AlphaState"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_DepthCullingState", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_DepthCullingState"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_StencilState", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_StencilState"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AndOrNotEvaluator", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AndOrNotEvaluator"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AssetTaskState", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AssetTaskState"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AbstractAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AbstractAssetTask"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AssetsProgressEvent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AssetsProgressEvent"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MeshAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MeshAssetTask"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextFileAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TextFileAssetTask"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BinaryFileAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BinaryFileAssetTask"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ImageAssetTask"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextureAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TextureAssetTask"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CubeTextureAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CubeTextureAssetTask"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HDRCubeTextureAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HDRCubeTextureAssetTask"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EquiRectangularCubeTextureAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EquiRectangularCubeTextureAssetTask"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AssetsManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AssetsManager"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DDSTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DDSTools"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "expandToProperty", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["expandToProperty"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serialize", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serialize"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsColor3", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsColor3"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsFresnelParameters", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsFresnelParameters"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsVector2", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsVector2"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsVector3", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsVector3"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsMeshReference", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsMeshReference"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsColorCurves", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsColorCurves"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsColor4", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsColor4"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsImageProcessingConfiguration", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsImageProcessingConfiguration"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsQuaternion", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsQuaternion"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsMatrix", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsMatrix"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsCameraReference", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsCameraReference"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SerializationHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SerializationHelper"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Deferred", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Deferred"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EnvironmentTextureTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EnvironmentTextureTools"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MeshExploder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MeshExploder"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FilesInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FilesInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KhronosTextureContainer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["KhronosTextureContainer"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EventState", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EventState"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Observer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Observer"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiObserver", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MultiObserver"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Observable", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Observable"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PerformanceMonitor", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PerformanceMonitor"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RollingAverage", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RollingAverage"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PromisePolyfill", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PromisePolyfill"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneOptimization"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextureOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TextureOptimization"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HardwareScalingOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HardwareScalingOptimization"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowsOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ShadowsOptimization"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PostProcessesOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PostProcessesOptimization"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LensFlaresOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LensFlaresOptimization"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CustomOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CustomOptimization"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ParticlesOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ParticlesOptimization"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RenderTargetsOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RenderTargetsOptimization"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MergeMeshesOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MergeMeshesOptimization"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneOptimizerOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneOptimizerOptions"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneOptimizer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneOptimizer"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneSerializer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneSerializer"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SmartArray", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SmartArray"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SmartArrayNoDuplicate", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SmartArrayNoDuplicate"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StringDictionary", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StringDictionary"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Tags", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Tags"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextureTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TextureTools"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TGATools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TGATools"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorGradient", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ColorGradient"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Color3Gradient", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Color3Gradient"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FactorGradient", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FactorGradient"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LoadFileError", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LoadFileError"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RetryStrategy", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RetryStrategy"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Tools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Tools"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PerfCounter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "className", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["className"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AsyncLoop", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AsyncLoop"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VideoRecorder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VideoRecorder"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "JoystickAxis", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["JoystickAxis"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VirtualJoystick", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VirtualJoystick"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WorkerPool", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WorkerPool"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Logger", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Logger"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_TypeStore", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_TypeStore"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FilesInputStore", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FilesInputStore"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DeepCopier", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DeepCopier"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PivotTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PivotTools"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrecisionDate", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PrecisionDate"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScreenshotTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ScreenshotTools"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebRequest", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebRequest"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InspectableType", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["InspectableType"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AutoRotationBehavior", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AutoRotationBehavior"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BouncingBehavior", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BouncingBehavior"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FramingBehavior", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FramingBehavior"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AttachToBoxBehavior", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AttachToBoxBehavior"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FadeInOutBehavior", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FadeInOutBehavior"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiPointerScaleBehavior", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MultiPointerScaleBehavior"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerDragBehavior", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointerDragBehavior"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SixDofDragBehavior", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SixDofDragBehavior"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraGamepadInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraGamepadInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraKeyboardMoveInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraKeyboardMoveInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraMouseWheelInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraMouseWheelInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraPointersInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraPointersInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraVRDeviceOrientationInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraVRDeviceOrientationInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCameraKeyboardInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FlyCameraKeyboardInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCameraMouseInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FlyCameraMouseInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraKeyboardMoveInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FollowCameraKeyboardMoveInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraMouseWheelInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FollowCameraMouseWheelInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraPointersInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FollowCameraPointersInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraDeviceOrientationInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraDeviceOrientationInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraGamepadInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraGamepadInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraKeyboardMoveInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraKeyboardMoveInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraMouseInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraMouseInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraTouchInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraTouchInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraVirtualJoystickInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraVirtualJoystickInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphArcRotateCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnaglyphArcRotateCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphFreeCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnaglyphFreeCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphGamepadCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnaglyphGamepadCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphUniversalCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnaglyphUniversalCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicArcRotateCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StereoscopicArcRotateCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicFreeCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StereoscopicFreeCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicGamepadCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StereoscopicGamepadCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicUniversalCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StereoscopicUniversalCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRCameraMetrics", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VRCameraMetrics"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationArcRotateCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VRDeviceOrientationArcRotateCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationFreeCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VRDeviceOrientationFreeCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationGamepadCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VRDeviceOrientationGamepadCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OnAfterEnteringVRObservableEvent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["OnAfterEnteringVRObservableEvent"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRExperienceHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VRExperienceHelper"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebVRFreeCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebVRFreeCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRCamera"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUIButton", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXREnterExitUIButton"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUIOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXREnterExitUIOptions"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUI", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXREnterExitUI"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRState", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRState"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRExperienceHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRExperienceHelper"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRController"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRInput"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRManagedOutputCanvas", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRManagedOutputCanvas"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRSessionManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRSessionManager"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Octree", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Octree"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OctreeBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["OctreeBlock"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OctreeSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["OctreeSceneComponent"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_OcclusionDataStorage", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_OcclusionDataStorage"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_forceTransformFeedbackToBundle", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_forceTransformFeedbackToBundle"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowGenerator", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ShadowGenerator"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowGeneratorSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ShadowGeneratorSceneComponent"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_BabylonLoaderRegistered", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_BabylonLoaderRegistered"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BackgroundMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BackgroundMaterial"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMaterialDefines", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PBRMaterialDefines"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRBaseMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PBRBaseMaterial"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRBaseSimpleMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PBRBaseSimpleMaterial"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PBRMaterial"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMetallicRoughnessMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PBRMetallicRoughnessMaterial"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRSpecularGlossinessMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PBRSpecularGlossinessMaterial"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorGradingTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ColorGradingTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DynamicTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DynamicTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ProceduralTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ProceduralTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RawCubeTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RawCubeTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RawTexture3D", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RawTexture3D"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RefractionTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RefractionTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VideoTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VideoTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DracoCompression", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DracoCompression"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DiscBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DiscBuilder"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RibbonBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RibbonBuilder"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HemisphereBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HemisphereBuilder"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TorusBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TorusBuilder"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TorusKnotBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TorusKnotBuilder"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PolygonBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PolygonBuilder"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShapeBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ShapeBuilder"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LatheBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LatheBuilder"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GroundBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GroundBuilder"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TubeBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TubeBuilder"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PolyhedronBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PolyhedronBuilder"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IcoSphereBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["IcoSphereBuilder"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DecalBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DecalBuilder"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoxParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoxParticleEmitter"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ConeParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ConeParticleEmitter"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CylinderParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CylinderParticleEmitter"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CylinderDirectedParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CylinderDirectedParticleEmitter"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HemisphericParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HemisphericParticleEmitter"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointParticleEmitter"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SphereParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SphereParticleEmitter"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SphereDirectedParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SphereDirectedParticleEmitter"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CannonJSPlugin", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CannonJSPlugin"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AmmoJSPlugin", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AmmoJSPlugin"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OimoJSPlugin", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["OimoJSPlugin"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PostProcessRenderEffect", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PostProcessRenderEffect"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PostProcessRenderPipeline", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PostProcessRenderPipeline"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PostProcessRenderPipelineManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PostProcessRenderPipelineManager"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PostProcessRenderPipelineManagerSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PostProcessRenderPipelineManagerSceneComponent"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CubeMapToSphericalPolynomialTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CubeMapToSphericalPolynomialTools"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HDRTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HDRTools"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PanoramaToCubeMapTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PanoramaToCubeMapTools"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_DDSTextureLoader", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_DDSTextureLoader"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_ENVTextureLoader", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_ENVTextureLoader"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_KTXTextureLoader", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_KTXTextureLoader"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_TGATextureLoader", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_TGATextureLoader"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CustomProceduralTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CustomProceduralTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NoiseProceduralTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NoiseProceduralTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ProceduralTextureSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ProceduralTextureSceneComponent"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DefaultRenderingPipeline", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DefaultRenderingPipeline"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LensRenderingPipeline", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LensRenderingPipeline"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SSAO2RenderingPipeline", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SSAO2RenderingPipeline"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SSAORenderingPipeline", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SSAORenderingPipeline"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StandardRenderingPipeline", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StandardRenderingPipeline"]; }); /** * Legacy support, defining window.BABYLON (global variable). * * This is the entry point for the UMD module. * The entry point for a future ESM package should be index.ts */ var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined); if (typeof globalObject !== "undefined") { globalObject.BABYLON = BABYLON; globalObject.BABYLON = globalObject.BABYLON || {}; var BABYLON = globalObject.BABYLON; BABYLON.Debug = BABYLON.Debug || {}; var keys = []; for (var key in _Debug_index__WEBPACK_IMPORTED_MODULE_1__) { BABYLON.Debug[key] = _Debug_index__WEBPACK_IMPORTED_MODULE_1__[key]; keys.push(key); } for (var key in _index__WEBPACK_IMPORTED_MODULE_0__) { BABYLON[key] = _index__WEBPACK_IMPORTED_MODULE_0__[key]; } } var Debug = { AxesViewer: _Debug_index__WEBPACK_IMPORTED_MODULE_1__["AxesViewer"], BoneAxesViewer: _Debug_index__WEBPACK_IMPORTED_MODULE_1__["BoneAxesViewer"], PhysicsViewer: _Debug_index__WEBPACK_IMPORTED_MODULE_1__["PhysicsViewer"], SkeletonViewer: _Debug_index__WEBPACK_IMPORTED_MODULE_1__["SkeletonViewer"], }; /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/webpack/buildin/global.js */ "../node_modules/webpack/buildin/global.js"))) /***/ }), /***/ "./LensFlares/index.ts": /*!*****************************!*\ !*** ./LensFlares/index.ts ***! \*****************************/ /*! exports provided: LensFlare, LensFlareSystem, LensFlareSystemSceneComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _lensFlare__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./lensFlare */ "./LensFlares/lensFlare.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LensFlare", function() { return _lensFlare__WEBPACK_IMPORTED_MODULE_0__["LensFlare"]; }); /* harmony import */ var _lensFlareSystem__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./lensFlareSystem */ "./LensFlares/lensFlareSystem.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LensFlareSystem", function() { return _lensFlareSystem__WEBPACK_IMPORTED_MODULE_1__["LensFlareSystem"]; }); /* harmony import */ var _lensFlareSystemSceneComponent__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./lensFlareSystemSceneComponent */ "./LensFlares/lensFlareSystemSceneComponent.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LensFlareSystemSceneComponent", function() { return _lensFlareSystemSceneComponent__WEBPACK_IMPORTED_MODULE_2__["LensFlareSystemSceneComponent"]; }); /***/ }), /***/ "./LensFlares/lensFlare.ts": /*!*********************************!*\ !*** ./LensFlares/lensFlare.ts ***! \*********************************/ /*! exports provided: LensFlare */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LensFlare", function() { return LensFlare; }); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); /** * This represents one of the lens effect in a `lensFlareSystem`. * It controls one of the indiviual texture used in the effect. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares */ var LensFlare = /** @class */ (function () { /** * Instantiates a new Lens Flare. * This represents one of the lens effect in a `lensFlareSystem`. * It controls one of the indiviual texture used in the effect. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares * @param size Define the size of the lens flare in the system (a floating value between 0 and 1) * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind. * @param color Define the lens color * @param imgUrl Define the lens texture url * @param system Define the `lensFlareSystem` this flare is part of */ function LensFlare( /** * Define the size of the lens flare in the system (a floating value between 0 and 1) */ size, /** * Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind. */ position, color, imgUrl, system) { this.size = size; this.position = position; /** * Define the alpha mode to render this particular lens. */ this.alphaMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].ALPHA_ONEONE; this.color = color || new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"](1, 1, 1); this.texture = imgUrl ? new _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_1__["Texture"](imgUrl, system.getScene(), true) : null; this._system = system; system.lensFlares.push(this); } /** * Creates a new Lens Flare. * This represents one of the lens effect in a `lensFlareSystem`. * It controls one of the indiviual texture used in the effect. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares * @param size Define the size of the lens flare (a floating value between 0 and 1) * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind. * @param color Define the lens color * @param imgUrl Define the lens texture url * @param system Define the `lensFlareSystem` this flare is part of * @returns The newly created Lens Flare */ LensFlare.AddFlare = function (size, position, color, imgUrl, system) { return new LensFlare(size, position, color, imgUrl, system); }; /** * Dispose and release the lens flare with its associated resources. */ LensFlare.prototype.dispose = function () { if (this.texture) { this.texture.dispose(); } // Remove from scene var index = this._system.lensFlares.indexOf(this); this._system.lensFlares.splice(index, 1); }; return LensFlare; }()); /***/ }), /***/ "./LensFlares/lensFlareSystem.ts": /*!***************************************!*\ !*** ./LensFlares/lensFlareSystem.ts ***! \***************************************/ /*! exports provided: LensFlareSystem */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LensFlareSystem", function() { return LensFlareSystem; }); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.scalar */ "./Maths/math.scalar.ts"); /* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts"); /* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/buffer */ "./Meshes/buffer.ts"); /* harmony import */ var _Culling_ray__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Culling/ray */ "./Culling/ray.ts"); /* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Materials/material */ "./Materials/material.ts"); /* harmony import */ var _lensFlare__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./lensFlare */ "./LensFlares/lensFlare.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); /* harmony import */ var _Shaders_lensFlare_fragment__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Shaders/lensFlare.fragment */ "./Shaders/lensFlare.fragment.ts"); /* harmony import */ var _Shaders_lensFlare_vertex__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Shaders/lensFlare.vertex */ "./Shaders/lensFlare.vertex.ts"); /* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Misc/devTools */ "./Misc/devTools.ts"); /** * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses. * It is usually composed of several `lensFlare`. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares */ var LensFlareSystem = /** @class */ (function () { /** * Instantiates a lens flare system. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses. * It is usually composed of several `lensFlare`. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares * @param name Define the name of the lens flare system in the scene * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh). * @param scene Define the scene the lens flare system belongs to */ function LensFlareSystem( /** * Define the name of the lens flare system */ name, emitter, scene) { this.name = name; /** * List of lens flares used in this system. */ this.lensFlares = new Array(); /** * Define a limit from the border the lens flare can be visible. */ this.borderLimit = 300; /** * Define a viewport border we do not want to see the lens flare in. */ this.viewportBorder = 0; /** * Restricts the rendering of the effect to only the camera rendering this layer mask. */ this.layerMask = 0x0FFFFFFF; this._vertexBuffers = {}; this._isEnabled = true; this._scene = scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_3__["EngineStore"].LastCreatedScene; LensFlareSystem._SceneComponentInitialization(this._scene); this._emitter = emitter; this.id = name; scene.lensFlareSystems.push(this); this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); }; var engine = scene.getEngine(); // VBO var vertices = []; vertices.push(1, 1); vertices.push(-1, 1); vertices.push(-1, -1); vertices.push(1, -1); this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind] = new _Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"](engine, vertices, _Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind, false, false, 2); // Indices var indices = []; indices.push(0); indices.push(1); indices.push(2); indices.push(0); indices.push(2); indices.push(3); this._indexBuffer = engine.createIndexBuffer(indices); // Effects this._effect = engine.createEffect("lensFlare", [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind], ["color", "viewportMatrix"], ["textureSampler"], ""); } Object.defineProperty(LensFlareSystem.prototype, "isEnabled", { /** * Define if the lens flare system is enabled. */ get: function () { return this._isEnabled; }, set: function (value) { this._isEnabled = value; }, enumerable: true, configurable: true }); /** * Get the scene the effects belongs to. * @returns the scene holding the lens flare system */ LensFlareSystem.prototype.getScene = function () { return this._scene; }; /** * Get the emitter of the lens flare system. * It defines the source of the lens flares (it can be a camera, a light or a mesh). * @returns the emitter of the lens flare system */ LensFlareSystem.prototype.getEmitter = function () { return this._emitter; }; /** * Set the emitter of the lens flare system. * It defines the source of the lens flares (it can be a camera, a light or a mesh). * @param newEmitter Define the new emitter of the system */ LensFlareSystem.prototype.setEmitter = function (newEmitter) { this._emitter = newEmitter; }; /** * Get the lens flare system emitter position. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh). * @returns the position */ LensFlareSystem.prototype.getEmitterPosition = function () { return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position; }; /** * @hidden */ LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) { var position = this.getEmitterPosition(); position = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Project(position, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(), this._scene.getTransformMatrix(), globalViewport); this._positionX = position.x; this._positionY = position.y; position = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix()); if (this.viewportBorder > 0) { globalViewport.x -= this.viewportBorder; globalViewport.y -= this.viewportBorder; globalViewport.width += this.viewportBorder * 2; globalViewport.height += this.viewportBorder * 2; position.x += this.viewportBorder; position.y += this.viewportBorder; this._positionX += this.viewportBorder; this._positionY += this.viewportBorder; } if (position.z > 0) { if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) { if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height)) { return true; } } return true; } return false; }; /** @hidden */ LensFlareSystem.prototype._isVisible = function () { if (!this._isEnabled || !this._scene.activeCamera) { return false; } var emitterPosition = this.getEmitterPosition(); var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition); var distance = direction.length(); direction.normalize(); var ray = new _Culling_ray__WEBPACK_IMPORTED_MODULE_5__["Ray"](this._scene.activeCamera.globalPosition, direction); var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true); return !pickInfo || !pickInfo.hit || pickInfo.distance > distance; }; /** * @hidden */ LensFlareSystem.prototype.render = function () { if (!this._effect.isReady() || !this._scene.activeCamera) { return false; } var engine = this._scene.getEngine(); var viewport = this._scene.activeCamera.viewport; var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true)); // Position if (!this.computeEffectivePosition(globalViewport)) { return false; } // Visibility if (!this._isVisible()) { return false; } // Intensity var awayX; var awayY; if (this._positionX < this.borderLimit + globalViewport.x) { awayX = this.borderLimit + globalViewport.x - this._positionX; } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) { awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit; } else { awayX = 0; } if (this._positionY < this.borderLimit + globalViewport.y) { awayY = this.borderLimit + globalViewport.y - this._positionY; } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) { awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit; } else { awayY = 0; } var away = (awayX > awayY) ? awayX : awayY; away -= this.viewportBorder; if (away > this.borderLimit) { away = this.borderLimit; } var intensity = 1.0 - _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_2__["Scalar"].Clamp(away / this.borderLimit, 0, 1); if (intensity < 0) { return false; } if (intensity > 1.0) { intensity = 1.0; } if (this.viewportBorder > 0) { globalViewport.x += this.viewportBorder; globalViewport.y += this.viewportBorder; globalViewport.width -= this.viewportBorder * 2; globalViewport.height -= this.viewportBorder * 2; this._positionX -= this.viewportBorder; this._positionY -= this.viewportBorder; } // Position var centerX = globalViewport.x + globalViewport.width / 2; var centerY = globalViewport.y + globalViewport.height / 2; var distX = centerX - this._positionX; var distY = centerY - this._positionY; // Effects engine.enableEffect(this._effect); engine.setState(false); engine.setDepthBuffer(false); // VBOs engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect); // Flares for (var index = 0; index < this.lensFlares.length; index++) { var flare = this.lensFlares[index]; engine.setAlphaMode(flare.alphaMode); var x = centerX - (distX * flare.position); var y = centerY - (distY * flare.position); var cw = flare.size; var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true); var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0; var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2)); var viewportMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1); this._effect.setMatrix("viewportMatrix", viewportMatrix); // Texture this._effect.setTexture("textureSampler", flare.texture); // Color this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0); // Draw order engine.drawElementsType(_Materials_material__WEBPACK_IMPORTED_MODULE_6__["Material"].TriangleFillMode, 0, 6); } engine.setDepthBuffer(true); engine.setAlphaMode(_Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].ALPHA_DISABLE); return true; }; /** * Dispose and release the lens flare with its associated resources. */ LensFlareSystem.prototype.dispose = function () { var vertexBuffer = this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind]; if (vertexBuffer) { vertexBuffer.dispose(); this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind] = null; } if (this._indexBuffer) { this._scene.getEngine()._releaseBuffer(this._indexBuffer); this._indexBuffer = null; } while (this.lensFlares.length) { this.lensFlares[0].dispose(); } // Remove from scene var index = this._scene.lensFlareSystems.indexOf(this); this._scene.lensFlareSystems.splice(index, 1); }; /** * Parse a lens flare system from a JSON repressentation * @param parsedLensFlareSystem Define the JSON to parse * @param scene Define the scene the parsed system should be instantiated in * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures * @returns the parsed system */ LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) { var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId); var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId; var lensFlareSystem = new LensFlareSystem(name, emitter, scene); lensFlareSystem.id = parsedLensFlareSystem.id || name; lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit; for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) { var parsedFlare = parsedLensFlareSystem.flares[index]; _lensFlare__WEBPACK_IMPORTED_MODULE_7__["LensFlare"].AddFlare(parsedFlare.size, parsedFlare.position, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color3"].FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem); } return lensFlareSystem; }; /** * Serialize the current Lens Flare System into a JSON representation. * @returns the serialized JSON */ LensFlareSystem.prototype.serialize = function () { var serializationObject = {}; serializationObject.id = this.id; serializationObject.name = this.name; serializationObject.emitterId = this.getEmitter().id; serializationObject.borderLimit = this.borderLimit; serializationObject.flares = []; for (var index = 0; index < this.lensFlares.length; index++) { var flare = this.lensFlares[index]; serializationObject.flares.push({ size: flare.size, position: flare.position, color: flare.color.asArray(), textureName: _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].GetFilename(flare.texture ? flare.texture.name : "") }); } return serializationObject; }; /** @hidden */ LensFlareSystem._SceneComponentInitialization = function (_) { throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_11__["_DevTools"].WarnImport("LensFlareSystemSceneComponent"); }; return LensFlareSystem; }()); /***/ }), /***/ "./LensFlares/lensFlareSystemSceneComponent.ts": /*!*****************************************************!*\ !*** ./LensFlares/lensFlareSystemSceneComponent.ts ***! \*****************************************************/ /*! exports provided: LensFlareSystemSceneComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LensFlareSystemSceneComponent", function() { return LensFlareSystemSceneComponent; }); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../sceneComponent */ "./sceneComponent.ts"); /* harmony import */ var _abstractScene__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../abstractScene */ "./abstractScene.ts"); /* harmony import */ var _lensFlareSystem__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./lensFlareSystem */ "./LensFlares/lensFlareSystem.ts"); // Adds the parser to the scene parsers. _abstractScene__WEBPACK_IMPORTED_MODULE_2__["AbstractScene"].AddParser(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) { // Lens flares if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) { if (!container.lensFlareSystems) { container.lensFlareSystems = new Array(); } for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) { var parsedLensFlareSystem = parsedData.lensFlareSystems[index]; var lf = _lensFlareSystem__WEBPACK_IMPORTED_MODULE_3__["LensFlareSystem"].Parse(parsedLensFlareSystem, scene, rootUrl); container.lensFlareSystems.push(lf); } } }); _abstractScene__WEBPACK_IMPORTED_MODULE_2__["AbstractScene"].prototype.getLensFlareSystemByName = function (name) { for (var index = 0; index < this.lensFlareSystems.length; index++) { if (this.lensFlareSystems[index].name === name) { return this.lensFlareSystems[index]; } } return null; }; _abstractScene__WEBPACK_IMPORTED_MODULE_2__["AbstractScene"].prototype.getLensFlareSystemByID = function (id) { for (var index = 0; index < this.lensFlareSystems.length; index++) { if (this.lensFlareSystems[index].id === id) { return this.lensFlareSystems[index]; } } return null; }; _abstractScene__WEBPACK_IMPORTED_MODULE_2__["AbstractScene"].prototype.removeLensFlareSystem = function (toRemove) { var index = this.lensFlareSystems.indexOf(toRemove); if (index !== -1) { this.lensFlareSystems.splice(index, 1); } return index; }; _abstractScene__WEBPACK_IMPORTED_MODULE_2__["AbstractScene"].prototype.addLensFlareSystem = function (newLensFlareSystem) { this.lensFlareSystems.push(newLensFlareSystem); }; /** * Defines the lens flare scene component responsible to manage any lens flares * in a given scene. */ var LensFlareSystemSceneComponent = /** @class */ (function () { /** * Creates a new instance of the component for the given scene * @param scene Defines the scene to register the component in */ function LensFlareSystemSceneComponent(scene) { /** * The component name helpfull to identify the component in the list of scene components. */ this.name = _sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_LENSFLARESYSTEM; this.scene = scene; scene.lensFlareSystems = new Array(); } /** * Registers the component in a given scene */ LensFlareSystemSceneComponent.prototype.register = function () { this.scene._afterCameraDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw); }; /** * Rebuilds the elements related to this component in case of * context lost for instance. */ LensFlareSystemSceneComponent.prototype.rebuild = function () { // Nothing to do for lens flare }; /** * Adds all the element from the container to the scene * @param container the container holding the elements */ LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) { var _this = this; if (!container.lensFlareSystems) { return; } container.lensFlareSystems.forEach(function (o) { _this.scene.addLensFlareSystem(o); }); }; /** * Removes all the elements in the container from the scene * @param container contains the elements to remove * @param dispose if the removed element should be disposed (default: false) */ LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container, dispose) { var _this = this; if (!container.lensFlareSystems) { return; } container.lensFlareSystems.forEach(function (o) { _this.scene.removeLensFlareSystem(o); if (dispose) { o.dispose(); } }); }; /** * Serializes the component data to the specified json object * @param serializationObject The object to serialize to */ LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) { // Lens flares serializationObject.lensFlareSystems = []; var lensFlareSystems = this.scene.lensFlareSystems; for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) { var lensFlareSystem = lensFlareSystems_1[_i]; serializationObject.lensFlareSystems.push(lensFlareSystem.serialize()); } }; /** * Disposes the component and the associated ressources. */ LensFlareSystemSceneComponent.prototype.dispose = function () { var lensFlareSystems = this.scene.lensFlareSystems; while (lensFlareSystems.length) { lensFlareSystems[0].dispose(); } }; LensFlareSystemSceneComponent.prototype._draw = function (camera) { // Lens flares if (this.scene.lensFlaresEnabled) { var lensFlareSystems = this.scene.lensFlareSystems; _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0); for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) { var lensFlareSystem = lensFlareSystems_2[_i]; if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) { lensFlareSystem.render(); } } _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0); } }; return LensFlareSystemSceneComponent; }()); _lensFlareSystem__WEBPACK_IMPORTED_MODULE_3__["LensFlareSystem"]._SceneComponentInitialization = function (scene) { var component = scene._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_LENSFLARESYSTEM); if (!component) { component = new LensFlareSystemSceneComponent(scene); scene._addComponent(component); } }; /***/ }), /***/ "./Lights/Shadows/index.ts": /*!*********************************!*\ !*** ./Lights/Shadows/index.ts ***! \*********************************/ /*! exports provided: ShadowGenerator, ShadowGeneratorSceneComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _shadowGenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./shadowGenerator */ "./Lights/Shadows/shadowGenerator.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowGenerator", function() { return _shadowGenerator__WEBPACK_IMPORTED_MODULE_0__["ShadowGenerator"]; }); /* harmony import */ var _shadowGeneratorSceneComponent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./shadowGeneratorSceneComponent */ "./Lights/Shadows/shadowGeneratorSceneComponent.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowGeneratorSceneComponent", function() { return _shadowGeneratorSceneComponent__WEBPACK_IMPORTED_MODULE_1__["ShadowGeneratorSceneComponent"]; }); /***/ }), /***/ "./Lights/Shadows/shadowGenerator.ts": /*!*******************************************!*\ !*** ./Lights/Shadows/shadowGenerator.ts ***! \*******************************************/ /*! exports provided: ShadowGenerator */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShadowGenerator", function() { return ShadowGenerator; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Meshes/buffer */ "./Meshes/buffer.ts"); /* harmony import */ var _Lights_light__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Lights/light */ "./Lights/light.ts"); /* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/material */ "./Materials/material.ts"); /* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Materials/materialHelper */ "./Materials/materialHelper.ts"); /* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); /* harmony import */ var _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Materials/Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts"); /* harmony import */ var _PostProcesses_postProcess__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../PostProcesses/postProcess */ "./PostProcesses/postProcess.ts"); /* harmony import */ var _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../PostProcesses/blurPostProcess */ "./PostProcesses/blurPostProcess.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); /* harmony import */ var _Shaders_shadowMap_fragment__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../Shaders/shadowMap.fragment */ "./Shaders/shadowMap.fragment.ts"); /* harmony import */ var _Shaders_shadowMap_vertex__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../../Shaders/shadowMap.vertex */ "./Shaders/shadowMap.vertex.ts"); /* harmony import */ var _Shaders_depthBoxBlur_fragment__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../../Shaders/depthBoxBlur.fragment */ "./Shaders/depthBoxBlur.fragment.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../../Misc/devTools */ "./Misc/devTools.ts"); /** * Default implementation IShadowGenerator. * This is the main object responsible of generating shadows in the framework. * Documentation: https://doc.babylonjs.com/babylon101/shadows */ var ShadowGenerator = /** @class */ (function () { /** * 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/babylon101/shadows * @param mapSize The size of the texture what stores the shadows. Example : 1024. * @param light The 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. */ function ShadowGenerator(mapSize, light, usefulFloatFirst) { /** * Observable triggered before the shadow is rendered. Can be used to update internal effect state */ this.onBeforeShadowMapRenderObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_14__["Observable"](); /** * Observable triggered before a mesh is rendered in the shadow map. * Can be used to update internal effect state (that you can get from the onBeforeShadowMapRenderObservable) */ this.onBeforeShadowMapRenderMeshObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_14__["Observable"](); this._bias = 0.00005; this._normalBias = 0; this._blurBoxOffset = 1; this._blurScale = 2; this._blurKernel = 1; this._useKernelBlur = false; this._filter = ShadowGenerator.FILTER_NONE; this._filteringQuality = ShadowGenerator.QUALITY_HIGH; this._contactHardeningLightSizeUVRatio = 0.1; this._darkness = 0; this._transparencyShadow = false; /** * Controls the extent to which the shadows fade out at the edge of the frustum * Used only by directionals and spots */ this.frustumEdgeFalloff = 0; /** * If true the shadow map is generated by rendering the back face of the mesh instead of the front face. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset. * It might on the other hand introduce peter panning. */ this.forceBackFacesOnly = false; this._lightDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); this._viewMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Zero(); this._projectionMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Zero(); this._transformMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Zero(); this._cachedPosition = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); this._cachedDirection = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); this._currentFaceIndex = 0; this._currentFaceIndexCache = 0; this._defaultTextureMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(); this._mapSize = mapSize; this._light = light; this._scene = light.getScene(); light._shadowGenerator = this; ShadowGenerator._SceneComponentInitialization(this._scene); // Texture type fallback from float to int if not supported. var caps = this._scene.getEngine().getCaps(); if (!usefulFloatFirst) { if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) { this._textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_HALF_FLOAT; } else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) { this._textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_FLOAT; } else { this._textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_UNSIGNED_INT; } } else { if (caps.textureFloatRender && caps.textureFloatLinearFiltering) { this._textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_FLOAT; } else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) { this._textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_HALF_FLOAT; } else { this._textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_UNSIGNED_INT; } } this._initializeGenerator(); this._applyFilterValues(); } Object.defineProperty(ShadowGenerator.prototype, "bias", { /** * Gets the bias: offset applied on the depth preventing acnea (in light direction). */ get: function () { return this._bias; }, /** * Sets the bias: offset applied on the depth preventing acnea (in light direction). */ set: function (bias) { this._bias = bias; }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "normalBias", { /** * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle). */ get: function () { return this._normalBias; }, /** * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle). */ set: function (normalBias) { this._normalBias = normalBias; }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", { /** * Gets the blur box offset: offset applied during the blur pass. * Only useful if useKernelBlur = false */ get: function () { return this._blurBoxOffset; }, /** * Sets the blur box offset: offset applied during the blur pass. * Only useful if useKernelBlur = false */ set: function (value) { if (this._blurBoxOffset === value) { return; } this._blurBoxOffset = value; this._disposeBlurPostProcesses(); }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "blurScale", { /** * Gets the blur scale: scale of the blurred texture compared to the main shadow map. * 2 means half of the size. */ get: function () { 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: function (value) { if (this._blurScale === value) { return; } this._blurScale = value; this._disposeBlurPostProcesses(); }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "blurKernel", { /** * Gets the blur kernel: kernel size of the blur pass. * Only useful if useKernelBlur = true */ get: function () { return this._blurKernel; }, /** * Sets the blur kernel: kernel size of the blur pass. * Only useful if useKernelBlur = true */ set: function (value) { if (this._blurKernel === value) { return; } this._blurKernel = value; this._disposeBlurPostProcesses(); }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", { /** * Gets whether the blur pass is a kernel blur (if true) or box blur. * Only useful in filtered mode (useBlurExponentialShadowMap...) */ get: function () { return this._useKernelBlur; }, /** * Sets whether the blur pass is a kernel blur (if true) or box blur. * Only useful in filtered mode (useBlurExponentialShadowMap...) */ set: function (value) { if (this._useKernelBlur === value) { return; } this._useKernelBlur = value; this._disposeBlurPostProcesses(); }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "depthScale", { /** * Gets the depth scale used in ESM mode. */ get: function () { return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale(); }, /** * Sets the depth scale used in ESM mode. * This can override the scale stored on the light. */ set: function (value) { this._depthScale = value; }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "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: function () { 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: function (value) { // Blurring the cubemap is going to be too expensive. Reverting to unblurred version if (this._light.needCube()) { if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) { this.useExponentialShadowMap = true; return; } else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) { this.useCloseExponentialShadowMap = true; return; } // PCF on cubemap would also be expensive else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) { this.usePoissonSampling = true; return; } } // Weblg1 fallback for PCF. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) { if (this._scene.getEngine().webGLVersion === 1) { this.usePoissonSampling = true; return; } } if (this._filter === value) { return; } this._filter = value; this._disposeBlurPostProcesses(); this._applyFilterValues(); this._light._markMeshesAsLightDirty(); }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", { /** * Gets if the current filter is set to Poisson Sampling. */ get: function () { return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING; }, /** * Sets the current filter to Poisson Sampling. */ set: function (value) { if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) { return; } this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE); }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", { /** * Gets if the current filter is set to ESM. */ get: function () { return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP; }, /** * Sets the current filter is to ESM. */ set: function (value) { if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) { return; } this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE); }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", { /** * Gets if the current filter is set to filtered ESM. */ get: function () { return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP; }, /** * Gets if the current filter is set to filtered ESM. */ set: function (value) { if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) { return; } this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE); }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", { /** * Gets if the current filter is set to "close ESM" (using the inverse of the * exponential to prevent steep falloff artifacts). */ get: function () { 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: function (value) { if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) { return; } this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE); }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", { /** * Gets if the current filter is set to filtered "close ESM" (using the inverse of the * exponential to prevent steep falloff artifacts). */ get: function () { 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: function (value) { if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) { return; } this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE); }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", { /** * Gets if the current filter is set to "PCF" (percentage closer filtering). */ get: function () { return this.filter === ShadowGenerator.FILTER_PCF; }, /** * Sets the current filter to "PCF" (percentage closer filtering). */ set: function (value) { if (!value && this.filter !== ShadowGenerator.FILTER_PCF) { return; } this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE); }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", { /** * Gets the PCF or PCSS Quality. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true. */ get: function () { return this._filteringQuality; }, /** * Sets the PCF or PCSS Quality. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true. */ set: function (filteringQuality) { this._filteringQuality = filteringQuality; }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", { /** * Gets if the current filter is set to "PCSS" (contact hardening). */ get: function () { return this.filter === ShadowGenerator.FILTER_PCSS; }, /** * Sets the current filter to "PCSS" (contact hardening). */ set: function (value) { if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) { return; } this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE); }, enumerable: true, configurable: true }); Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", { /** * 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: function () { 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: function (contactHardeningLightSizeUVRatio) { this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio; }, enumerable: true, configurable: true }); /** * 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. */ ShadowGenerator.prototype.getDarkness = function () { 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. */ ShadowGenerator.prototype.setDarkness = function (darkness) { if (darkness >= 1.0) { this._darkness = 1.0; } else if (darkness <= 0.0) { this._darkness = 0.0; } else { this._darkness = darkness; } return this; }; /** * Sets the ability to have transparent shadow (boolean). * @param transparent True if transparent else False * @returns the shadow generator allowing fluent coding */ ShadowGenerator.prototype.setTransparencyShadow = function (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 */ ShadowGenerator.prototype.getShadowMap = function () { 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 */ ShadowGenerator.prototype.getShadowMapForRendering = function () { if (this._shadowMap2) { return this._shadowMap2; } return this._shadowMap; }; /** * 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 */ ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) { if (includeDescendants === void 0) { includeDescendants = true; } var _a; if (!this._shadowMap) { return this; } if (!this._shadowMap.renderList) { this._shadowMap.renderList = []; } this._shadowMap.renderList.push(mesh); if (includeDescendants) { (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes()); } 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 */ ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) { if (includeDescendants === void 0) { includeDescendants = true; } if (!this._shadowMap || !this._shadowMap.renderList) { return this; } var index = this._shadowMap.renderList.indexOf(mesh); if (index !== -1) { this._shadowMap.renderList.splice(index, 1); } if (includeDescendants) { for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) { var child = _a[_i]; this.removeShadowCaster(child); } } return this; }; /** * Returns the associated light object. * @returns the light generating the shadow */ ShadowGenerator.prototype.getLight = function () { return this._light; }; ShadowGenerator.prototype._initializeGenerator = function () { this._light._markMeshesAsLightDirty(); this._initializeShadowMap(); }; ShadowGenerator.prototype._initializeShadowMap = function () { var _this = this; // Render target var engine = this._scene.getEngine(); if (engine.webGLVersion > 1) { this._shadowMap = new _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_7__["RenderTargetTexture"](this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false); this._shadowMap.createDepthStencilTexture(_Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].LESS, true); } else { this._shadowMap = new _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_7__["RenderTargetTexture"](this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube()); } this._shadowMap.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].CLAMP_ADDRESSMODE; this._shadowMap.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].CLAMP_ADDRESSMODE; this._shadowMap.anisotropicFilteringLevel = 1; this._shadowMap.updateSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].BILINEAR_SAMPLINGMODE); this._shadowMap.renderParticles = false; this._shadowMap.ignoreCameraViewport = true; // Record Face Index before render. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) { _this._currentFaceIndex = faceIndex; if (_this._filter === ShadowGenerator.FILTER_PCF) { engine.setColorWrite(false); } }); // Custom render function. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this); // Blur if required afer render. this._shadowMap.onAfterUnbindObservable.add(function () { if (_this._filter === ShadowGenerator.FILTER_PCF) { engine.setColorWrite(true); } if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) { return; } var shadowMap = _this.getShadowMapForRendering(); if (shadowMap) { _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true); } }); // Clear according to the chosen filter. var clearZero = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color4"](0, 0, 0, 0); var clearOne = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color4"](1.0, 1.0, 1.0, 1.0); this._shadowMap.onClearObservable.add(function (engine) { if (_this._filter === ShadowGenerator.FILTER_PCF) { engine.clear(clearOne, false, true, false); } else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) { engine.clear(clearZero, true, true, false); } else { engine.clear(clearOne, true, true, false); } }); }; ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () { var _this = this; var engine = this._scene.getEngine(); var targetSize = this._mapSize / this.blurScale; if (!this.useKernelBlur || this.blurScale !== 1.0) { this._shadowMap2 = new _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_7__["RenderTargetTexture"](this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType); this._shadowMap2.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].CLAMP_ADDRESSMODE; this._shadowMap2.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].CLAMP_ADDRESSMODE; this._shadowMap2.updateSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].BILINEAR_SAMPLINGMODE); } if (this.useKernelBlur) { this._kernelBlurXPostprocess = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_9__["BlurPostProcess"](this._light.name + "KernelBlurX", new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector2"](1, 0), this.blurKernel, 1.0, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].BILINEAR_SAMPLINGMODE, engine, false, this._textureType); this._kernelBlurXPostprocess.width = targetSize; this._kernelBlurXPostprocess.height = targetSize; this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) { effect.setTexture("textureSampler", _this._shadowMap); }); this._kernelBlurYPostprocess = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_9__["BlurPostProcess"](this._light.name + "KernelBlurY", new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector2"](0, 1), this.blurKernel, 1.0, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].BILINEAR_SAMPLINGMODE, engine, false, this._textureType); this._kernelBlurXPostprocess.autoClear = false; this._kernelBlurYPostprocess.autoClear = false; if (this._textureType === _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_UNSIGNED_INT) { this._kernelBlurXPostprocess.packedFloat = true; this._kernelBlurYPostprocess.packedFloat = true; } this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess]; } else { this._boxBlurPostprocess = new _PostProcesses_postProcess__WEBPACK_IMPORTED_MODULE_8__["PostProcess"](this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType); this._boxBlurPostprocess.onApplyObservable.add(function (effect) { effect.setFloat2("screenSize", targetSize, targetSize); effect.setTexture("textureSampler", _this._shadowMap); }); this._boxBlurPostprocess.autoClear = false; this._blurPostProcesses = [this._boxBlurPostprocess]; } }; ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) { var index; var engine = this._scene.getEngine(); if (depthOnlySubMeshes.length) { engine.setColorWrite(false); for (index = 0; index < depthOnlySubMeshes.length; index++) { this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]); } engine.setColorWrite(true); } 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]); } } }; ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) { var _this = this; var mesh = subMesh.getRenderingMesh(); var scene = this._scene; var engine = scene.getEngine(); var material = subMesh.getMaterial(); if (!material || subMesh.verticesCount === 0) { return; } // Culling engine.setState(material.backFaceCulling); // Managing instances var batch = mesh._getInstancesRenderList(subMesh._id); if (batch.mustReturn) { return; } var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined); if (this.isReady(subMesh, hardwareInstancedRendering)) { engine.enableEffect(this._effect); mesh._bind(subMesh, this._effect, _Materials_material__WEBPACK_IMPORTED_MODULE_4__["Material"].TriangleFillMode); this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale); this._effect.setMatrix("viewProjection", this.getTransformMatrix()); if (this.getLight().getTypeID() === _Lights_light__WEBPACK_IMPORTED_MODULE_3__["Light"].LIGHTTYPEID_DIRECTIONALLIGHT) { this._effect.setVector3("lightData", this._cachedDirection); } else { this._effect.setVector3("lightData", this._cachedPosition); } if (scene.activeCamera) { this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera)); } // Alpha test if (material && material.needAlphaTesting()) { var alphaTexture = material.getAlphaTestTexture(); if (alphaTexture) { this._effect.setTexture("diffuseSampler", alphaTexture); this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix); } } // Bones if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { var skeleton = mesh.skeleton; if (skeleton.isUsingTextureForMatrices) { var boneTexture = skeleton.getTransformMatrixTexture(); if (!boneTexture) { return; } this._effect.setTexture("boneSampler", boneTexture); this._effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1)); } else { this._effect.setMatrices("mBones", skeleton.getTransformMatrices((mesh))); } } // Morph targets _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_5__["MaterialHelper"].BindMorphTargetParameters(mesh, this._effect); if (this.forceBackFacesOnly) { engine.setState(true, 0, false, true); } // Observables this.onBeforeShadowMapRenderMeshObservable.notifyObservers(mesh); this.onBeforeShadowMapRenderObservable.notifyObservers(this._effect); // Draw mesh._processRendering(subMesh, this._effect, _Materials_material__WEBPACK_IMPORTED_MODULE_4__["Material"].TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); }); if (this.forceBackFacesOnly) { engine.setState(true, 0, false, false); } } else { // Need to reset refresh rate of the shadowMap if (this._shadowMap) { this._shadowMap.resetRefreshCounter(); } } }; ShadowGenerator.prototype._applyFilterValues = function () { if (!this._shadowMap) { return; } if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) { this._shadowMap.updateSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].NEAREST_SAMPLINGMODE); } else { this._shadowMap.updateSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].BILINEAR_SAMPLINGMODE); } }; /** * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly 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 */ ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) { var _this = this; var localOptions = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ useInstances: false }, options); var shadowMap = this.getShadowMap(); if (!shadowMap) { if (onCompiled) { onCompiled(this); } return; } var renderList = shadowMap.renderList; if (!renderList) { if (onCompiled) { onCompiled(this); } return; } var subMeshes = new Array(); for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) { var mesh = renderList_1[_i]; subMeshes.push.apply(subMeshes, mesh.subMeshes); } if (subMeshes.length === 0) { if (onCompiled) { onCompiled(this); } return; } var currentIndex = 0; var checkReady = function () { if (!_this._scene || !_this._scene.getEngine()) { return; } while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) { currentIndex++; if (currentIndex >= subMeshes.length) { if (onCompiled) { onCompiled(_this); } return; } } setTimeout(checkReady, 16); }; checkReady(); }; /** * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects. * @param options Sets of optional options forcing the compilation with different modes * @returns A promise that resolves when the compilation completes */ ShadowGenerator.prototype.forceCompilationAsync = function (options) { var _this = this; return new Promise(function (resolve) { _this.forceCompilation(function () { resolve(); }, options); }); }; /** * Determine wheter 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 wether will draw in the map using instances * @returns true if ready otherwise, false */ ShadowGenerator.prototype.isReady = function (subMesh, useInstances) { var defines = []; if (this._textureType !== _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_UNSIGNED_INT) { defines.push("#define FLOAT"); } if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) { defines.push("#define ESM"); } else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) { defines.push("#define DEPTHTEXTURE"); } var attribs = [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].PositionKind]; var mesh = subMesh.getMesh(); var material = subMesh.getMaterial(); // Normal bias. if (this.normalBias && mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].NormalKind)) { attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].NormalKind); defines.push("#define NORMAL"); if (mesh.nonUniformScaling) { defines.push("#define NONUNIFORMSCALING"); } if (this.getLight().getTypeID() === _Lights_light__WEBPACK_IMPORTED_MODULE_3__["Light"].LIGHTTYPEID_DIRECTIONALLIGHT) { defines.push("#define DIRECTIONINLIGHTDATA"); } } // Alpha test if (material && material.needAlphaTesting()) { var alphaTexture = material.getAlphaTestTexture(); if (alphaTexture) { defines.push("#define ALPHATEST"); if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].UVKind)) { attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].UVKind); defines.push("#define UV1"); } if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].UV2Kind)) { if (alphaTexture.coordinatesIndex === 1) { attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].UV2Kind); defines.push("#define UV2"); } } } } // Bones if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].MatricesIndicesKind); attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].MatricesWeightsKind); if (mesh.numBoneInfluencers > 4) { attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].MatricesIndicesExtraKind); attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].MatricesWeightsExtraKind); } var skeleton = mesh.skeleton; defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); if (skeleton.isUsingTextureForMatrices) { defines.push("#define BONETEXTURE"); } else { defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1)); } } else { defines.push("#define NUM_BONE_INFLUENCERS 0"); } // Morph targets var manager = mesh.morphTargetManager; var morphInfluencers = 0; if (manager) { if (manager.numInfluencers > 0) { defines.push("#define MORPHTARGETS"); morphInfluencers = manager.numInfluencers; defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers); _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_5__["MaterialHelper"].PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers }); } } // Instances if (useInstances) { defines.push("#define INSTANCES"); attribs.push("world0"); attribs.push("world1"); attribs.push("world2"); attribs.push("world3"); } if (this.customShaderOptions) { if (this.customShaderOptions.defines) { for (var _i = 0, _a = this.customShaderOptions.defines; _i < _a.length; _i++) { var define = _a[_i]; if (defines.indexOf(define) === -1) { defines.push(define); } } } } // Get correct effect var join = defines.join("\n"); if (this._cachedDefines !== join) { this._cachedDefines = join; var shaderName = "shadowMap"; var uniforms = ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences", "boneTextureWidth"]; var samplers = ["diffuseSampler", "boneSampler"]; // Custom shader? if (this.customShaderOptions) { shaderName = this.customShaderOptions.shaderName; if (this.customShaderOptions.attributes) { for (var _b = 0, _c = this.customShaderOptions.attributes; _b < _c.length; _b++) { var attrib = _c[_b]; if (attribs.indexOf(attrib) === -1) { attribs.push(attrib); } } } if (this.customShaderOptions.uniforms) { for (var _d = 0, _e = this.customShaderOptions.uniforms; _d < _e.length; _d++) { var uniform = _e[_d]; if (uniforms.indexOf(uniform) === -1) { uniforms.push(uniform); } } } if (this.customShaderOptions.samplers) { for (var _f = 0, _g = this.customShaderOptions.samplers; _f < _g.length; _f++) { var sampler = _g[_f]; if (samplers.indexOf(sampler) === -1) { samplers.push(sampler); } } } } this._effect = this._scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers }); } if (!this._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 */ ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) { var scene = this._scene; var light = this._light; if (!scene.shadowsEnabled || !light.shadowEnabled) { return; } defines["SHADOW" + lightIndex] = true; if (this.useContactHardeningShadow) { defines["SHADOWPCSS" + lightIndex] = true; if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) { defines["SHADOWLOWQUALITY" + lightIndex] = true; } else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) { defines["SHADOWMEDIUMQUALITY" + lightIndex] = true; } // else default to high. } if (this.usePercentageCloserFiltering) { defines["SHADOWPCF" + lightIndex] = true; if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) { defines["SHADOWLOWQUALITY" + lightIndex] = true; } else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) { defines["SHADOWMEDIUMQUALITY" + lightIndex] = true; } // else default to high. } else if (this.usePoissonSampling) { defines["SHADOWPOISSON" + lightIndex] = true; } else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) { defines["SHADOWESM" + lightIndex] = true; } else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) { defines["SHADOWCLOSEESM" + lightIndex] = true; } if (light.needCube()) { defines["SHADOWCUBE" + lightIndex] = true; } }; /** * Binds the shadow related information inside of an effect (information like near, far, darkness... * defined in the generator but impacting the effect). * @param lightIndex Index of the light in the enabled light list of the material owning the effect * @param effect The effect we are binfing the information for */ ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) { var light = this._light; var scene = this._scene; if (!scene.shadowsEnabled || !light.shadowEnabled) { return; } var camera = scene.activeCamera; if (!camera) { return; } var shadowMap = this.getShadowMap(); if (!shadowMap) { return; } if (!light.needCube()) { effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix()); } // Only PCF uses depth stencil texture. if (this._filter === ShadowGenerator.FILTER_PCF) { effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering()); 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("shadowSampler" + lightIndex, this.getShadowMapForRendering()); effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering()); light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex); } else { effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering()); 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 transformation matrix used to project the meshes into the map from the light point of view. * (eq to shadow prjection matrix * light transform matrix) * @returns The transform matrix used to create the shadow map */ ShadowGenerator.prototype.getTransformMatrix = function () { var scene = this._scene; if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) { return this._transformMatrix; } this._currentRenderID = scene.getRenderId(); this._currentFaceIndexCache = this._currentFaceIndex; var lightPosition = this._light.position; if (this._light.computeTransformedInformation()) { lightPosition = this._light.transformedPosition; } _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection); if (Math.abs(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(this._lightDirection, _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Up())) === 1.0) { this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light } if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) { this._cachedPosition.copyFrom(lightPosition); this._cachedDirection.copyFrom(this._lightDirection); _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Up(), this._viewMatrix); var shadowMap = this.getShadowMap(); if (shadowMap) { var 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. */ ShadowGenerator.prototype.recreateShadowMap = function () { var shadowMap = this._shadowMap; if (!shadowMap) { return; } // Track render list. var renderList = shadowMap.renderList; // Clean up existing data. this._disposeRTTandPostProcesses(); // Reinitializes. this._initializeGenerator(); // Reaffect the filter to ensure a correct fallback if necessary. this.filter = this.filter; // Reaffect the filter. this._applyFilterValues(); // Reaffect Render List. this._shadowMap.renderList = renderList; }; ShadowGenerator.prototype._disposeBlurPostProcesses = function () { 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 = []; }; ShadowGenerator.prototype._disposeRTTandPostProcesses = function () { if (this._shadowMap) { this._shadowMap.dispose(); this._shadowMap = null; } this._disposeBlurPostProcesses(); }; /** * Disposes the ShadowGenerator. * Returns nothing. */ ShadowGenerator.prototype.dispose = function () { this._disposeRTTandPostProcesses(); if (this._light) { this._light._shadowGenerator = null; this._light._markMeshesAsLightDirty(); } }; /** * Serializes the shadow generator setup to a json object. * @returns The serialized JSON object */ ShadowGenerator.prototype.serialize = function () { var serializationObject = {}; var shadowMap = this.getShadowMap(); if (!shadowMap) { return serializationObject; } serializationObject.lightId = this._light.id; serializationObject.mapSize = shadowMap.getRenderSize(); serializationObject.useExponentialShadowMap = this.useExponentialShadowMap; serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap; serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap; serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap; serializationObject.usePoissonSampling = this.usePoissonSampling; serializationObject.forceBackFacesOnly = this.forceBackFacesOnly; serializationObject.depthScale = this.depthScale; serializationObject.darkness = this.getDarkness(); serializationObject.blurBoxOffset = this.blurBoxOffset; serializationObject.blurKernel = this.blurKernel; serializationObject.blurScale = this.blurScale; serializationObject.useKernelBlur = this.useKernelBlur; 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.filteringQuality = this.filteringQuality; serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio; serializationObject.renderList = []; if (shadowMap.renderList) { for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) { var 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 */ ShadowGenerator.Parse = function (parsedShadowGenerator, scene) { var light = scene.getLightByID(parsedShadowGenerator.lightId); var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light); var shadowMap = shadowGenerator.getShadowMap(); for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) { var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]); meshes.forEach(function (mesh) { if (!shadowMap) { return; } if (!shadowMap.renderList) { shadowMap.renderList = []; } shadowMap.renderList.push(mesh); }); } 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.usePercentageCloserFiltering) { shadowGenerator.usePercentageCloserFiltering = true; } else if (parsedShadowGenerator.useContactHardeningShadow) { shadowGenerator.useContactHardeningShadow = true; } if (parsedShadowGenerator.filteringQuality) { shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality; } if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) { shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio; } // Backward compat else if (parsedShadowGenerator.useVarianceShadowMap) { shadowGenerator.useExponentialShadowMap = true; } else if (parsedShadowGenerator.useBlurVarianceShadowMap) { shadowGenerator.useBlurExponentialShadowMap = true; } 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; } if (parsedShadowGenerator.bias !== undefined) { shadowGenerator.bias = parsedShadowGenerator.bias; } if (parsedShadowGenerator.normalBias !== undefined) { shadowGenerator.normalBias = parsedShadowGenerator.normalBias; } if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) { shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff; } if (parsedShadowGenerator.darkness) { shadowGenerator.setDarkness(parsedShadowGenerator.darkness); } if (parsedShadowGenerator.transparencyShadow) { shadowGenerator.setTransparencyShadow(true); } shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly; return shadowGenerator; }; /** * Shadow generator mode None: no filtering applied. */ ShadowGenerator.FILTER_NONE = 0; /** * Shadow generator mode ESM: Exponential Shadow Mapping. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf) */ ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1; /** * Shadow generator mode Poisson Sampling: Percentage Closer Filtering. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength) */ ShadowGenerator.FILTER_POISSONSAMPLING = 2; /** * Shadow generator mode ESM: Blurred Exponential Shadow Mapping. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf) */ ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3; /** * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing * edge artifacts on steep falloff. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf) */ ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4; /** * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing * edge artifacts on steep falloff. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf) */ ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5; /** * Shadow generator mode PCF: Percentage Closer Filtering * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1 * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html) */ ShadowGenerator.FILTER_PCF = 6; /** * Shadow generator mode PCSS: Percentage Closering Soft Shadow. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1 * Contact Hardening */ ShadowGenerator.FILTER_PCSS = 7; /** * Reserved for PCF and PCSS * Highest Quality. * * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts. * * Execute PCSS with 32 taps blocker search and 64 taps PCF. */ ShadowGenerator.QUALITY_HIGH = 0; /** * Reserved for PCF and PCSS * Good tradeoff for quality/perf cross devices * * Execute PCF on a 3*3 kernel. * * Execute PCSS with 16 taps blocker search and 32 taps PCF. */ ShadowGenerator.QUALITY_MEDIUM = 1; /** * Reserved for PCF and PCSS * The lowest quality but the fastest. * * Execute PCF on a 1*1 kernel. * * Execute PCSS with 16 taps blocker search and 16 taps PCF. */ ShadowGenerator.QUALITY_LOW = 2; /** @hidden */ ShadowGenerator._SceneComponentInitialization = function (_) { throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_15__["_DevTools"].WarnImport("ShadowGeneratorSceneComponent"); }; return ShadowGenerator; }()); /***/ }), /***/ "./Lights/Shadows/shadowGeneratorSceneComponent.ts": /*!*********************************************************!*\ !*** ./Lights/Shadows/shadowGeneratorSceneComponent.ts ***! \*********************************************************/ /*! exports provided: ShadowGeneratorSceneComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShadowGeneratorSceneComponent", function() { return ShadowGeneratorSceneComponent; }); /* harmony import */ var _shadowGenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./shadowGenerator */ "./Lights/Shadows/shadowGenerator.ts"); /* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../sceneComponent */ "./sceneComponent.ts"); /* harmony import */ var _abstractScene__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../abstractScene */ "./abstractScene.ts"); // Adds the parser to the scene parsers. _abstractScene__WEBPACK_IMPORTED_MODULE_2__["AbstractScene"].AddParser(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_SHADOWGENERATOR, function (parsedData, scene) { // Shadows if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) { for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) { var parsedShadowGenerator = parsedData.shadowGenerators[index]; _shadowGenerator__WEBPACK_IMPORTED_MODULE_0__["ShadowGenerator"].Parse(parsedShadowGenerator, scene); // SG would be available on their associated lights } } }); /** * Defines the shadow generator component responsible to manage any shadow generators * in a given scene. */ var ShadowGeneratorSceneComponent = /** @class */ (function () { /** * Creates a new instance of the component for the given scene * @param scene Defines the scene to register the component in */ function ShadowGeneratorSceneComponent(scene) { /** * The component name helpfull to identify the component in the list of scene components. */ this.name = _sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_SHADOWGENERATOR; this.scene = scene; } /** * Registers the component in a given scene */ ShadowGeneratorSceneComponent.prototype.register = function () { this.scene._gatherRenderTargetsStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets); }; /** * Rebuilds the elements related to this component in case of * context lost for instance. */ ShadowGeneratorSceneComponent.prototype.rebuild = function () { // Nothing To Do Here. }; /** * Serializes the component data to the specified json object * @param serializationObject The object to serialize to */ ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) { // Shadows serializationObject.shadowGenerators = []; var lights = this.scene.lights; for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) { var light = lights_1[_i]; var shadowGenerator = light.getShadowGenerator(); if (shadowGenerator) { serializationObject.shadowGenerators.push(shadowGenerator.serialize()); } } }; /** * Adds all the element from the container to the scene * @param container the container holding the elements */ ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) { // Nothing To Do Here. (directly attached to a light) }; /** * Removes all the elements in the container from the scene * @param container contains the elements to remove * @param dispose if the removed element should be disposed (default: false) */ ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container, dispose) { // Nothing To Do Here. (directly attached to a light) }; /** * Rebuilds the elements related to this component in case of * context lost for instance. */ ShadowGeneratorSceneComponent.prototype.dispose = function () { // Nothing To Do Here. }; ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) { // Shadows var scene = this.scene; if (this.scene.shadowsEnabled) { for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) { var light = scene.lights[lightIndex]; var shadowGenerator = light.getShadowGenerator(); if (light.isEnabled() && light.shadowEnabled && shadowGenerator) { var shadowMap = (shadowGenerator.getShadowMap()); if (scene.textures.indexOf(shadowMap) !== -1) { renderTargets.push(shadowMap); } } } } }; return ShadowGeneratorSceneComponent; }()); _shadowGenerator__WEBPACK_IMPORTED_MODULE_0__["ShadowGenerator"]._SceneComponentInitialization = function (scene) { var component = scene._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_SHADOWGENERATOR); if (!component) { component = new ShadowGeneratorSceneComponent(scene); scene._addComponent(component); } }; /***/ }), /***/ "./Lights/directionalLight.ts": /*!************************************!*\ !*** ./Lights/directionalLight.ts ***! \************************************/ /*! exports provided: DirectionalLight */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DirectionalLight", function() { return DirectionalLight; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts"); /* harmony import */ var _light__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./light */ "./Lights/light.ts"); /* harmony import */ var _shadowLight__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./shadowLight */ "./Lights/shadowLight.ts"); _node__WEBPACK_IMPORTED_MODULE_3__["Node"].AddNodeConstructor("Light_Type_1", function (name, scene) { return function () { return new DirectionalLight(name, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), scene); }; }); /** * A directional light is defined by a direction (what a surprise!). * The light is emitted from everywhere in the specified direction, and has an infinite range. * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object. * Documentation: https://doc.babylonjs.com/babylon101/lights */ var DirectionalLight = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DirectionalLight, _super); /** * 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/babylon101/lights * @param name The friendly name of the light * @param direction The direction of the light * @param scene The scene the light belongs to */ function DirectionalLight(name, direction, scene) { var _this = _super.call(this, name, scene) || this; _this._shadowFrustumSize = 0; _this._shadowOrthoScale = 0.1; /** * Automatically compute the projection matrix to best fit (including all the casters) * on each frame. */ _this.autoUpdateExtends = true; // Cache _this._orthoLeft = Number.MAX_VALUE; _this._orthoRight = Number.MIN_VALUE; _this._orthoTop = Number.MIN_VALUE; _this._orthoBottom = Number.MAX_VALUE; _this.position = direction.scale(-1.0); _this.direction = direction; return _this; } Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", { /** * Fix frustum size for the shadow generation. This is disabled if the value is 0. */ get: function () { return this._shadowFrustumSize; }, /** * Specifies a fix frustum size for the shadow generation. */ set: function (value) { this._shadowFrustumSize = value; this.forceProjectionMatrixCompute(); }, enumerable: true, configurable: true }); Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", { /** * 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: function () { 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: function (value) { this._shadowOrthoScale = value; this.forceProjectionMatrixCompute(); }, enumerable: true, configurable: true }); /** * Returns the string "DirectionalLight". * @return The class name */ DirectionalLight.prototype.getClassName = function () { return "DirectionalLight"; }; /** * Returns the integer 1. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x */ DirectionalLight.prototype.getTypeID = function () { return _light__WEBPACK_IMPORTED_MODULE_4__["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. */ DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (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. */ DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix) { var activeCamera = this.getScene().activeCamera; if (!activeCamera) { return; } _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix); }; /** * 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. */ DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) { var activeCamera = this.getScene().activeCamera; if (!activeCamera) { return; } // Check extends if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) { var tempVector3 = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); this._orthoLeft = Number.MAX_VALUE; this._orthoRight = Number.MIN_VALUE; this._orthoTop = Number.MIN_VALUE; this._orthoBottom = Number.MAX_VALUE; for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) { var mesh = renderList[meshIndex]; if (!mesh) { continue; } var boundingInfo = mesh.getBoundingInfo(); var boundingBox = boundingInfo.boundingBox; for (var index = 0; index < boundingBox.vectorsWorld.length; index++) { _Maths_math__WEBPACK_IMPORTED_MODULE_2__["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; } } } } var xOffset = this._orthoRight - this._orthoLeft; var yOffset = this._orthoTop - this._orthoBottom; _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix); }; DirectionalLight.prototype._buildUniformLayout = function () { this._uniformBuffer.addUniform("vLightData", 4); this._uniformBuffer.addUniform("vLightDiffuse", 4); this._uniformBuffer.addUniform("vLightSpecular", 3); 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 */ DirectionalLight.prototype.transferToEffect = function (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; }; /** * 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. * @param activeCamera The camera we are returning the min for * @returns the depth min z */ DirectionalLight.prototype.getDepthMinZ = function (activeCamera) { return 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. * @param activeCamera The camera we are returning the max for * @returns the depth max z */ DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) { return 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 */ DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) { defines["DIRLIGHT" + lightIndex] = true; }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], DirectionalLight.prototype, "shadowFrustumSize", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], DirectionalLight.prototype, "shadowOrthoScale", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], DirectionalLight.prototype, "autoUpdateExtends", void 0); return DirectionalLight; }(_shadowLight__WEBPACK_IMPORTED_MODULE_5__["ShadowLight"])); /***/ }), /***/ "./Lights/hemisphericLight.ts": /*!************************************!*\ !*** ./Lights/hemisphericLight.ts ***! \************************************/ /*! exports provided: HemisphericLight */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HemisphericLight", function() { return HemisphericLight; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts"); /* harmony import */ var _light__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./light */ "./Lights/light.ts"); _node__WEBPACK_IMPORTED_MODULE_3__["Node"].AddNodeConstructor("Light_Type_3", function (name, scene) { return function () { return new HemisphericLight(name, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), scene); }; }); /** * The HemisphericLight simulates the ambient environment light, * so the passed direction is the light reflection direction, not the incoming direction. */ var HemisphericLight = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](HemisphericLight, _super); /** * Creates a HemisphericLight object in the scene according to the passed direction (Vector3). * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction. * The HemisphericLight can't cast shadows. * Documentation : https://doc.babylonjs.com/babylon101/lights * @param name The friendly name of the light * @param direction The direction of the light reflection * @param scene The scene the light belongs to */ function HemisphericLight(name, direction, scene) { var _this = _super.call(this, name, scene) || this; /** * The groundColor is the light in the opposite direction to the one specified during creation. * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction. */ _this.groundColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"](0.0, 0.0, 0.0); _this.direction = direction || _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Up(); return _this; } HemisphericLight.prototype._buildUniformLayout = function () { this._uniformBuffer.addUniform("vLightData", 4); this._uniformBuffer.addUniform("vLightDiffuse", 4); this._uniformBuffer.addUniform("vLightSpecular", 3); this._uniformBuffer.addUniform("vLightGround", 3); this._uniformBuffer.addUniform("shadowsInfo", 3); this._uniformBuffer.addUniform("depthValues", 2); this._uniformBuffer.create(); }; /** * Returns the string "HemisphericLight". * @return The class name */ HemisphericLight.prototype.getClassName = function () { return "HemisphericLight"; }; /** * Sets the HemisphericLight direction towards the passed target (Vector3). * Returns the updated direction. * @param target The target the direction should point to * @return The computed direction */ HemisphericLight.prototype.setDirectionToTarget = function (target) { this.direction = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Normalize(target.subtract(_Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero())); return this.direction; }; /** * Returns the shadow generator associated to the light. * @returns Always null for hemispheric lights because it does not support shadows. */ HemisphericLight.prototype.getShadowGenerator = function () { return null; }; /** * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string). * @param effect The effect to update * @param lightIndex The index of the light in the effect to update * @returns The hemispheric light */ HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) { var normalizeDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Normalize(this.direction); this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex); this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex); return this; }; /** * Computes the world matrix of the node * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch * @param useWasUpdatedFlag defines a reserved property * @returns the world matrix */ HemisphericLight.prototype.computeWorldMatrix = function () { if (!this._worldMatrix) { this._worldMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Identity(); } return this._worldMatrix; }; /** * Returns the integer 3. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x */ HemisphericLight.prototype.getTypeID = function () { return _light__WEBPACK_IMPORTED_MODULE_4__["Light"].LIGHTTYPEID_HEMISPHERICLIGHT; }; /** * Prepares the list of defines specific to the light type. * @param defines the list of defines * @param lightIndex defines the index of the light for the effect */ HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) { defines["HEMILIGHT" + lightIndex] = true; }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])() ], HemisphericLight.prototype, "groundColor", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])() ], HemisphericLight.prototype, "direction", void 0); return HemisphericLight; }(_light__WEBPACK_IMPORTED_MODULE_4__["Light"])); /***/ }), /***/ "./Lights/index.ts": /*!*************************!*\ !*** ./Lights/index.ts ***! \*************************/ /*! exports provided: Light, ShadowLight, DirectionalLight, HemisphericLight, PointLight, SpotLight, ShadowGenerator, ShadowGeneratorSceneComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _light__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./light */ "./Lights/light.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Light", function() { return _light__WEBPACK_IMPORTED_MODULE_0__["Light"]; }); /* harmony import */ var _shadowLight__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./shadowLight */ "./Lights/shadowLight.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowLight", function() { return _shadowLight__WEBPACK_IMPORTED_MODULE_1__["ShadowLight"]; }); /* harmony import */ var _Shadows_index__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Shadows/index */ "./Lights/Shadows/index.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowGenerator", function() { return _Shadows_index__WEBPACK_IMPORTED_MODULE_2__["ShadowGenerator"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowGeneratorSceneComponent", function() { return _Shadows_index__WEBPACK_IMPORTED_MODULE_2__["ShadowGeneratorSceneComponent"]; }); /* harmony import */ var _directionalLight__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./directionalLight */ "./Lights/directionalLight.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DirectionalLight", function() { return _directionalLight__WEBPACK_IMPORTED_MODULE_3__["DirectionalLight"]; }); /* harmony import */ var _hemisphericLight__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./hemisphericLight */ "./Lights/hemisphericLight.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HemisphericLight", function() { return _hemisphericLight__WEBPACK_IMPORTED_MODULE_4__["HemisphericLight"]; }); /* harmony import */ var _pointLight__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./pointLight */ "./Lights/pointLight.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointLight", function() { return _pointLight__WEBPACK_IMPORTED_MODULE_5__["PointLight"]; }); /* harmony import */ var _spotLight__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./spotLight */ "./Lights/spotLight.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SpotLight", function() { return _spotLight__WEBPACK_IMPORTED_MODULE_6__["SpotLight"]; }); /***/ }), /***/ "./Lights/light.ts": /*!*************************!*\ !*** ./Lights/light.ts ***! \*************************/ /*! exports provided: Light */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Light", function() { return Light; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts"); /* harmony import */ var _Materials_uniformBuffer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Materials/uniformBuffer */ "./Materials/uniformBuffer.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); /** * Base class of all the lights in Babylon. It groups all the generic information about lights. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour. * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased. */ var Light = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Light, _super); /** * Creates a Light object in the scene. * Documentation : https://doc.babylonjs.com/babylon101/lights * @param name The firendly name of the light * @param scene The scene the light belongs too */ function Light(name, scene) { var _this = _super.call(this, name, scene) || this; /** * Diffuse gives the basic color to an object. */ _this.diffuse = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"](1.0, 1.0, 1.0); /** * Specular produces a highlight color on an object. * Note: This is note affecting PBR materials. */ _this.specular = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"](1.0, 1.0, 1.0); /** * Defines the falloff type for this light. This lets overrriding how punctual light are * falling off base on range or angle. * This can be set to any values in Light.FALLOFF_x. * * Note: This is only useful for PBR Materials at the moment. This could be extended if required to * other types of materials. */ _this.falloffType = Light.FALLOFF_DEFAULT; /** * Strength of the light. * Note: By default it is define in the framework own unit. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in. */ _this.intensity = 1.0; _this._range = Number.MAX_VALUE; _this._inverseSquaredRange = 0; /** * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type * of light. */ _this._photometricScale = 1.0; _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC; _this._radius = 0.00001; /** * Defines the rendering priority of the lights. It can help in case of fallback or number of lights * exceeding the number allowed of the materials. */ _this.renderPriority = 0; _this._shadowEnabled = true; _this._excludeWithLayerMask = 0; _this._includeOnlyWithLayerMask = 0; _this._lightmapMode = 0; /** * @hidden Internal use only. */ _this._excludedMeshesIds = new Array(); /** * @hidden Internal use only. */ _this._includedOnlyMeshesIds = new Array(); /** @hidden */ _this._isLight = true; _this.getScene().addLight(_this); _this._uniformBuffer = new _Materials_uniformBuffer__WEBPACK_IMPORTED_MODULE_4__["UniformBuffer"](_this.getScene().getEngine()); _this._buildUniformLayout(); _this.includedOnlyMeshes = new Array(); _this.excludedMeshes = new Array(); _this._resyncMeshes(); return _this; } Object.defineProperty(Light.prototype, "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. */ get: function () { 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: function (value) { this._range = value; this._inverseSquaredRange = 1.0 / (this.range * this.range); }, enumerable: true, configurable: true }); Object.defineProperty(Light.prototype, "intensityMode", { /** * 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: function () { 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: function (value) { this._intensityMode = value; this._computePhotometricScale(); }, enumerable: true, configurable: true }); Object.defineProperty(Light.prototype, "radius", { /** * Gets the light radius used by PBR Materials to simulate soft area lights. */ get: function () { return this._radius; }, /** * sets the light radius used by PBR Materials to simulate soft area lights. */ set: function (value) { this._radius = value; this._computePhotometricScale(); }, enumerable: true, configurable: true }); Object.defineProperty(Light.prototype, "shadowEnabled", { /** * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching * the current shadow generator. */ get: function () { return this._shadowEnabled; }, /** * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching * the current shadow generator. */ set: function (value) { if (this._shadowEnabled === value) { return; } this._shadowEnabled = value; this._markMeshesAsLightDirty(); }, enumerable: true, configurable: true }); Object.defineProperty(Light.prototype, "includedOnlyMeshes", { /** * Gets the only meshes impacted by this light. */ get: function () { return this._includedOnlyMeshes; }, /** * Sets the only meshes impacted by this light. */ set: function (value) { this._includedOnlyMeshes = value; this._hookArrayForIncludedOnly(value); }, enumerable: true, configurable: true }); Object.defineProperty(Light.prototype, "excludedMeshes", { /** * Gets the meshes not impacted by this light. */ get: function () { return this._excludedMeshes; }, /** * Sets the meshes not impacted by this light. */ set: function (value) { this._excludedMeshes = value; this._hookArrayForExcluded(value); }, enumerable: true, configurable: true }); Object.defineProperty(Light.prototype, "excludeWithLayerMask", { /** * Gets the layer id use to find what meshes are not impacted by the light. * Inactive if 0 */ get: function () { return this._excludeWithLayerMask; }, /** * Sets the layer id use to find what meshes are not impacted by the light. * Inactive if 0 */ set: function (value) { this._excludeWithLayerMask = value; this._resyncMeshes(); }, enumerable: true, configurable: true }); Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", { /** * Gets the layer id use to find what meshes are impacted by the light. * Inactive if 0 */ get: function () { return this._includeOnlyWithLayerMask; }, /** * Sets the layer id use to find what meshes are impacted by the light. * Inactive if 0 */ set: function (value) { this._includeOnlyWithLayerMask = value; this._resyncMeshes(); }, enumerable: true, configurable: true }); Object.defineProperty(Light.prototype, "lightmapMode", { /** * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x) */ get: function () { return this._lightmapMode; }, /** * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x) */ set: function (value) { if (this._lightmapMode === value) { return; } this._lightmapMode = value; this._markMeshesAsLightDirty(); }, enumerable: true, configurable: true }); /** * Returns the string "Light". * @returns the class name */ Light.prototype.getClassName = function () { 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 */ Light.prototype.toString = function (fullDetails) { var ret = "Name: " + this.name; ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()]; if (this.animations) { for (var i = 0; i < this.animations.length; i++) { ret += ", animation[0]: " + this.animations[i].toString(fullDetails); } } if (fullDetails) { } return ret; }; /** @hidden */ Light.prototype._syncParentEnabledState = function () { _super.prototype._syncParentEnabledState.call(this); this._resyncMeshes(); }; /** * Set the enabled state of this node. * @param value - the new enabled state */ Light.prototype.setEnabled = function (value) { _super.prototype.setEnabled.call(this, value); this._resyncMeshes(); }; /** * Returns the Light associated shadow generator if any. * @return the associated shadow generator. */ Light.prototype.getShadowGenerator = function () { return this._shadowGenerator; }; /** * Returns a Vector3, the absolute light position in the World. * @returns the world space position of the light */ Light.prototype.getAbsolutePosition = function () { return _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); }; /** * Specifies if the light will affect the passed mesh. * @param mesh The mesh to test against the light * @return true the mesh is affected otherwise, false. */ Light.prototype.canAffectMesh = function (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; }; /** * Sort function to order lights for rendering. * @param a First Light object to compare to second. * @param b Second Light object to compare first. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b. */ Light.CompareLightsPriority = function (a, b) { //shadow-casting lights have priority over non-shadow-casting lights //the renderPrioirty is a secondary sort criterion if (a.shadowEnabled !== b.shadowEnabled) { return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0); } return b.renderPriority - a.renderPriority; }; /** * 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) */ Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) { if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; } if (this._shadowGenerator) { this._shadowGenerator.dispose(); this._shadowGenerator = null; } // Animations this.getScene().stopAnimation(this); // Remove from meshes for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) { var mesh = _a[_i]; mesh._removeLightSource(this); } this._uniformBuffer.dispose(); // Remove from scene this.getScene().removeLight(this); _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures); }; /** * Returns the light type ID (integer). * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x */ Light.prototype.getTypeID = function () { 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 */ Light.prototype.getScaledIntensity = function () { return this._photometricScale * this.intensity; }; /** * Returns a new Light object, named "name", from the current one. * @param name The name of the cloned light * @returns the new created light */ Light.prototype.clone = function (name) { var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()); if (!constructor) { return null; } return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(constructor, this); }; /** * Serializes the current light into a Serialization object. * @returns the serialized object. */ Light.prototype.serialize = function () { var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); // Type serializationObject.type = this.getTypeID(); // Parent if (this.parent) { serializationObject.parentId = this.parent.id; } // Inclusion / exclusions if (this.excludedMeshes.length > 0) { serializationObject.excludedMeshesIds = []; this.excludedMeshes.forEach(function (mesh) { serializationObject.excludedMeshesIds.push(mesh.id); }); } if (this.includedOnlyMeshes.length > 0) { serializationObject.includedOnlyMeshesIds = []; this.includedOnlyMeshes.forEach(function (mesh) { serializationObject.includedOnlyMeshesIds.push(mesh.id); }); } // Animations _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].AppendSerializedAnimations(this, serializationObject); serializationObject.ranges = this.serializeAnimationRanges(); 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 */ Light.GetConstructorFromName = function (type, name, scene) { var constructorFunc = _node__WEBPACK_IMPORTED_MODULE_3__["Node"].Construct("Light_Type_" + type, name, scene); if (constructorFunc) { return constructorFunc; } // Default to no light for none present once. return null; }; /** * Parses the passed "parsedLight" and returns a new instanced Light from this parsing. * @param parsedLight The JSON representation of the light * @param scene The scene to create the parsed light in * @returns the created light after parsing */ Light.Parse = function (parsedLight, scene) { var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene); if (!constructor) { return null; } var light = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(constructor, parsedLight, scene); // Inclusion / exclusions if (parsedLight.excludedMeshesIds) { light._excludedMeshesIds = parsedLight.excludedMeshesIds; } if (parsedLight.includedOnlyMeshesIds) { light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds; } // Parent if (parsedLight.parentId) { light._waitingParentId = parsedLight.parentId; } // Animations if (parsedLight.animations) { for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) { var parsedAnimation = parsedLight.animations[animationIndex]; var internalClass = _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].GetClass("BABYLON.Animation"); if (internalClass) { light.animations.push(internalClass.Parse(parsedAnimation)); } } _node__WEBPACK_IMPORTED_MODULE_3__["Node"].ParseAnimationRanges(light, parsedLight, scene); } if (parsedLight.autoAnimate) { scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0); } return light; }; Light.prototype._hookArrayForExcluded = function (array) { var _this = this; var oldPush = array.push; array.push = function () { var items = []; for (var _i = 0; _i < arguments.length; _i++) { items[_i] = arguments[_i]; } var result = oldPush.apply(array, items); for (var _a = 0, items_1 = items; _a < items_1.length; _a++) { var item = items_1[_a]; item._resyncLighSource(_this); } return result; }; var oldSplice = array.splice; array.splice = function (index, deleteCount) { var deleted = oldSplice.apply(array, [index, deleteCount]); for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) { var item = deleted_1[_i]; item._resyncLighSource(_this); } return deleted; }; for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { var item = array_1[_i]; item._resyncLighSource(this); } }; Light.prototype._hookArrayForIncludedOnly = function (array) { var _this = this; var oldPush = array.push; array.push = function () { var items = []; for (var _i = 0; _i < arguments.length; _i++) { items[_i] = arguments[_i]; } var result = oldPush.apply(array, items); _this._resyncMeshes(); return result; }; var oldSplice = array.splice; array.splice = function (index, deleteCount) { var deleted = oldSplice.apply(array, [index, deleteCount]); _this._resyncMeshes(); return deleted; }; this._resyncMeshes(); }; Light.prototype._resyncMeshes = function () { for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) { var mesh = _a[_i]; mesh._resyncLighSource(this); } }; /** * Forces the meshes to update their light related information in their rendering used effects * @hidden Internal Use Only */ Light.prototype._markMeshesAsLightDirty = function () { for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) { var mesh = _a[_i]; if (mesh._lightSources.indexOf(this) !== -1) { mesh._markSubMeshesAsLightDirty(); } } }; /** * Recomputes the cached photometric scale if needed. */ Light.prototype._computePhotometricScale = function () { this._photometricScale = this._getPhotometricScale(); this.getScene().resetCachedMaterial(); }; /** * Returns the Photometric Scale according to the light type and intensity mode. */ Light.prototype._getPhotometricScale = function () { var photometricScale = 0.0; var lightTypeID = this.getTypeID(); //get photometric mode var photometricMode = this.intensityMode; if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) { if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) { photometricMode = Light.INTENSITYMODE_ILLUMINANCE; } else { photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY; } } //compute photometric scale switch (lightTypeID) { case Light.LIGHTTYPEID_POINTLIGHT: case Light.LIGHTTYPEID_SPOTLIGHT: switch (photometricMode) { case Light.INTENSITYMODE_LUMINOUSPOWER: photometricScale = 1.0 / (4.0 * Math.PI); break; case Light.INTENSITYMODE_LUMINOUSINTENSITY: photometricScale = 1.0; break; case Light.INTENSITYMODE_LUMINANCE: photometricScale = this.radius * this.radius; break; } break; case Light.LIGHTTYPEID_DIRECTIONALLIGHT: switch (photometricMode) { case Light.INTENSITYMODE_ILLUMINANCE: photometricScale = 1.0; break; case Light.INTENSITYMODE_LUMINANCE: // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres). var apexAngleRadians = this.radius; // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function). apexAngleRadians = Math.max(apexAngleRadians, 0.001); var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians)); photometricScale = solidAngle; break; } break; case Light.LIGHTTYPEID_HEMISPHERICLIGHT: // No fall off in hemisperic light. photometricScale = 1.0; break; } return photometricScale; }; /** * Reorder the light in the scene according to their defined priority. * @hidden Internal Use Only */ Light.prototype._reorderLightsInScene = function () { var scene = this.getScene(); if (this._renderPriority != 0) { scene.requireLightSorting = true; } this.getScene().sortLightsByPriority(); }; /** * Falloff Default: light is falling off following the material specification: * standard material is using standard falloff whereas pbr material can request special falloff per materials. */ Light.FALLOFF_DEFAULT = 0; /** * Falloff Physical: light is falling off following the inverse squared distance law. */ Light.FALLOFF_PHYSICAL = 1; /** * Falloff gltf: light is falling off as described in the gltf moving to PBR document * to enhance interoperability with other engines. */ Light.FALLOFF_GLTF = 2; /** * Falloff Standard: light is falling off like in the standard material * to enhance interoperability with other materials. */ Light.FALLOFF_STANDARD = 3; //lightmapMode Consts /** * If every light affecting the material is in this lightmapMode, * material.lightmapTexture adds or multiplies * (depends on material.useLightmapAsShadowmap) * after every other light calculations. */ Light.LIGHTMAP_DEFAULT = 0; /** * material.lightmapTexture as only diffuse lighting from this light * adds only specular lighting from this light * adds dynamic shadows */ Light.LIGHTMAP_SPECULAR = 1; /** * material.lightmapTexture as only lighting * no light calculation from this light * only adds dynamic shadows from this light */ Light.LIGHTMAP_SHADOWSONLY = 2; // Intensity Mode Consts /** * Each light type uses the default quantity according to its type: * point/spot lights use luminous intensity * directional lights use illuminance */ Light.INTENSITYMODE_AUTOMATIC = 0; /** * lumen (lm) */ Light.INTENSITYMODE_LUMINOUSPOWER = 1; /** * candela (lm/sr) */ Light.INTENSITYMODE_LUMINOUSINTENSITY = 2; /** * lux (lm/m^2) */ Light.INTENSITYMODE_ILLUMINANCE = 3; /** * nit (cd/m^2) */ Light.INTENSITYMODE_LUMINANCE = 4; // Light types ids const. /** * Light type const id of the point light. */ Light.LIGHTTYPEID_POINTLIGHT = 0; /** * Light type const id of the directional light. */ Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1; /** * Light type const id of the spot light. */ Light.LIGHTTYPEID_SPOTLIGHT = 2; /** * Light type const id of the hemispheric light. */ Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])() ], Light.prototype, "diffuse", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])() ], Light.prototype, "specular", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Light.prototype, "falloffType", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Light.prototype, "intensity", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Light.prototype, "range", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Light.prototype, "intensityMode", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Light.prototype, "radius", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Light.prototype, "_renderPriority", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_reorderLightsInScene") ], Light.prototype, "renderPriority", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("shadowEnabled") ], Light.prototype, "_shadowEnabled", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("excludeWithLayerMask") ], Light.prototype, "_excludeWithLayerMask", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("includeOnlyWithLayerMask") ], Light.prototype, "_includeOnlyWithLayerMask", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("lightmapMode") ], Light.prototype, "_lightmapMode", void 0); return Light; }(_node__WEBPACK_IMPORTED_MODULE_3__["Node"])); /***/ }), /***/ "./Lights/pointLight.ts": /*!******************************!*\ !*** ./Lights/pointLight.ts ***! \******************************/ /*! exports provided: PointLight */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointLight", function() { return PointLight; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts"); /* harmony import */ var _light__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./light */ "./Lights/light.ts"); /* harmony import */ var _shadowLight__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./shadowLight */ "./Lights/shadowLight.ts"); _node__WEBPACK_IMPORTED_MODULE_3__["Node"].AddNodeConstructor("Light_Type_0", function (name, scene) { return function () { return new PointLight(name, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), scene); }; }); /** * A point light is a light defined by an unique point in world space. * The light is emitted in every direction from this point. * A good example of a point light is a standard light bulb. * Documentation: https://doc.babylonjs.com/babylon101/lights */ var PointLight = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PointLight, _super); /** * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene. * A PointLight emits the light in every direction. * It can cast shadows. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it : * ```javascript * var pointLight = new PointLight("pl", camera.position, scene); * ``` * Documentation : https://doc.babylonjs.com/babylon101/lights * @param name The light friendly name * @param position The position of the point light in the scene * @param scene The scene the lights belongs to */ function PointLight(name, position, scene) { var _this = _super.call(this, name, scene) || this; _this._shadowAngle = Math.PI / 2; _this.position = position; return _this; } Object.defineProperty(PointLight.prototype, "shadowAngle", { /** * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback * This specifies what angle the shadow will use to be created. * * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps. */ get: function () { return this._shadowAngle; }, /** * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback * This specifies what angle the shadow will use to be created. * * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps. */ set: function (value) { this._shadowAngle = value; this.forceProjectionMatrixCompute(); }, enumerable: true, configurable: true }); Object.defineProperty(PointLight.prototype, "direction", { /** * Gets the direction if it has been set. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback */ get: function () { return this._direction; }, /** * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback */ set: function (value) { var previousNeedCube = this.needCube(); this._direction = value; if (this.needCube() !== previousNeedCube && this._shadowGenerator) { this._shadowGenerator.recreateShadowMap(); } }, enumerable: true, configurable: true }); /** * Returns the string "PointLight" * @returns the class name */ PointLight.prototype.getClassName = function () { return "PointLight"; }; /** * Returns the integer 0. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x */ PointLight.prototype.getTypeID = function () { return _light__WEBPACK_IMPORTED_MODULE_4__["Light"].LIGHTTYPEID_POINTLIGHT; }; /** * Specifies wether or not the shadowmap should be a cube texture. * @returns true if the shadowmap needs to be a cube texture. */ PointLight.prototype.needCube = function () { return !this.direction; }; /** * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer). * @param faceIndex The index of the face we are computed the direction to generate shadow * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true */ PointLight.prototype.getShadowDirection = function (faceIndex) { if (this.direction) { return _super.prototype.getShadowDirection.call(this, faceIndex); } else { switch (faceIndex) { case 0: return new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](1.0, 0.0, 0.0); case 1: return new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](-1.0, 0.0, 0.0); case 2: return new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0.0, -1.0, 0.0); case 3: return new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0.0, 1.0, 0.0); case 4: return new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0.0, 0.0, 1.0); case 5: return new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0.0, 0.0, -1.0); } } return _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); }; /** * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings : * - fov = PI / 2 * - aspect ratio : 1.0 * - z-near and far equal to the active camera minZ and maxZ. * Returns the PointLight. */ PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) { var activeCamera = this.getScene().activeCamera; if (!activeCamera) { return; } _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix); }; PointLight.prototype._buildUniformLayout = function () { this._uniformBuffer.addUniform("vLightData", 4); this._uniformBuffer.addUniform("vLightDiffuse", 4); this._uniformBuffer.addUniform("vLightSpecular", 3); this._uniformBuffer.addUniform("vLightFalloff", 4); this._uniformBuffer.addUniform("shadowsInfo", 3); this._uniformBuffer.addUniform("depthValues", 2); this._uniformBuffer.create(); }; /** * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string). * @param effect The effect to update * @param lightIndex The index of the light in the effect to update * @returns The point light */ PointLight.prototype.transferToEffect = function (effect, lightIndex) { if (this.computeTransformedInformation()) { this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex); } else { this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex); } this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex); return this; }; /** * 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 */ PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) { defines["POINTLIGHT" + lightIndex] = true; }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PointLight.prototype, "shadowAngle", null); return PointLight; }(_shadowLight__WEBPACK_IMPORTED_MODULE_5__["ShadowLight"])); /***/ }), /***/ "./Lights/shadowLight.ts": /*!*******************************!*\ !*** ./Lights/shadowLight.ts ***! \*******************************/ /*! exports provided: ShadowLight */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShadowLight", function() { return ShadowLight; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _light__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./light */ "./Lights/light.ts"); /** * Base implementation IShadowLight * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern. */ var ShadowLight = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ShadowLight, _super); function ShadowLight() { var _this = _super !== null && _super.apply(this, arguments) || this; _this._needProjectionMatrixCompute = true; return _this; } ShadowLight.prototype._setPosition = function (value) { this._position = value; }; Object.defineProperty(ShadowLight.prototype, "position", { /** * Sets the position the shadow will be casted from. Also use as the light position for both * point and spot lights. */ get: function () { 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: function (value) { this._setPosition(value); }, enumerable: true, configurable: true }); ShadowLight.prototype._setDirection = function (value) { this._direction = value; }; Object.defineProperty(ShadowLight.prototype, "direction", { /** * 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: function () { 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: function (value) { this._setDirection(value); }, enumerable: true, configurable: true }); Object.defineProperty(ShadowLight.prototype, "shadowMinZ", { /** * Gets the shadow projection clipping minimum z value. */ get: function () { return this._shadowMinZ; }, /** * Sets the shadow projection clipping minimum z value. */ set: function (value) { this._shadowMinZ = value; this.forceProjectionMatrixCompute(); }, enumerable: true, configurable: true }); Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", { /** * Sets the shadow projection clipping maximum z value. */ get: function () { return this._shadowMaxZ; }, /** * Gets the shadow projection clipping maximum z value. */ set: function (value) { this._shadowMaxZ = value; this.forceProjectionMatrixCompute(); }, enumerable: true, configurable: true }); /** * 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) */ ShadowLight.prototype.computeTransformedInformation = function () { if (this.parent && this.parent.getWorldMatrix) { if (!this.transformedPosition) { this.transformedPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); } _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition); // In case the direction is present. if (this.direction) { if (!this.transformedDirection) { this.transformedDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); } _Maths_math__WEBPACK_IMPORTED_MODULE_2__["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. */ ShadowLight.prototype.getDepthScale = function () { return 50.0; }; /** * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed. * @param faceIndex The index of the face we are computed the direction to generate shadow * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true */ ShadowLight.prototype.getShadowDirection = function (faceIndex) { return this.transformedDirection ? this.transformedDirection : this.direction; }; /** * Returns the ShadowLight absolute position in the World. * @returns the position vector in world space */ ShadowLight.prototype.getAbsolutePosition = function () { 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 */ ShadowLight.prototype.setDirectionToTarget = function (target) { this.direction = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["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. */ ShadowLight.prototype.getRotation = function () { this.direction.normalize(); var xaxis = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Cross(this.direction, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Axis"].Y); var yaxis = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Cross(xaxis, this.direction); return _Maths_math__WEBPACK_IMPORTED_MODULE_2__["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 */ ShadowLight.prototype.needCube = function () { return false; }; /** * Detects if the projection matrix requires to be recomputed this frame. * @returns true if it requires to be recomputed otherwise, false. */ ShadowLight.prototype.needProjectionMatrixCompute = function () { return this._needProjectionMatrixCompute; }; /** * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed. */ ShadowLight.prototype.forceProjectionMatrixCompute = function () { this._needProjectionMatrixCompute = true; }; /** @hidden */ ShadowLight.prototype._initCache = function () { _super.prototype._initCache.call(this); this._cache.position = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); }; /** @hidden */ ShadowLight.prototype._isSynchronized = function () { 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 */ ShadowLight.prototype.computeWorldMatrix = function (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 = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Identity(); } _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix); if (this.parent && this.parent.getWorldMatrix) { this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix); this._markSyncedWithParent(); } // Cache the determinant this._worldMatrixDeterminant = this._worldMatrix.determinant(); 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 */ ShadowLight.prototype.getDepthMinZ = function (activeCamera) { return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ; }; /** * Gets the maxZ used for shadow according to both the scene and the light. * @param activeCamera The camera we are returning the max for * @returns the depth max z */ ShadowLight.prototype.getDepthMaxZ = function (activeCamera) { return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ; }; /** * Sets the shadow projection matrix in parameter to the generated projection matrix. * @param matrix The materix 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 */ ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) { if (this.customProjectionMatrixBuilder) { this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix); } else { this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList); } return this; }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])() ], ShadowLight.prototype, "position", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])() ], ShadowLight.prototype, "direction", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ShadowLight.prototype, "shadowMinZ", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ShadowLight.prototype, "shadowMaxZ", null); return ShadowLight; }(_light__WEBPACK_IMPORTED_MODULE_3__["Light"])); /***/ }), /***/ "./Lights/spotLight.ts": /*!*****************************!*\ !*** ./Lights/spotLight.ts ***! \*****************************/ /*! exports provided: SpotLight */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpotLight", function() { return SpotLight; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts"); /* harmony import */ var _light__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./light */ "./Lights/light.ts"); /* harmony import */ var _shadowLight__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./shadowLight */ "./Lights/shadowLight.ts"); _node__WEBPACK_IMPORTED_MODULE_3__["Node"].AddNodeConstructor("Light_Type_2", function (name, scene) { return function () { return new SpotLight(name, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), 0, 0, scene); }; }); /** * A spot light is defined by a position, a direction, an angle, and an exponent. * These values define a cone of light starting from the position, emitting toward the direction. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam, * and the exponent defines the speed of the decay of the light with distance (reach). * Documentation: https://doc.babylonjs.com/babylon101/lights */ var SpotLight = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](SpotLight, _super); /** * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone. * It can cast shadows. * Documentation : https://doc.babylonjs.com/babylon101/lights * @param name The light friendly name * @param position The position of the spot light in the scene * @param direction The direction of the light in the scene * @param angle The cone angle of the light in Radians * @param exponent The light decay speed with the distance from the emission spot * @param scene The scene the lights belongs to */ function SpotLight(name, position, direction, angle, exponent, scene) { var _this = _super.call(this, name, scene) || this; _this._innerAngle = 0; _this._projectionTextureMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Zero(); _this._projectionTextureLightNear = 1e-6; _this._projectionTextureLightFar = 1000.0; _this._projectionTextureUpDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Up(); _this._projectionTextureViewLightDirty = true; _this._projectionTextureProjectionLightDirty = true; _this._projectionTextureDirty = true; _this._projectionTextureViewTargetVector = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); _this._projectionTextureViewLightMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Zero(); _this._projectionTextureProjectionLightMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Zero(); _this._projectionTextureScalingMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0); _this.position = position; _this.direction = direction; _this.angle = angle; _this.exponent = exponent; return _this; } Object.defineProperty(SpotLight.prototype, "angle", { /** * Gets the cone angle of the spot light in Radians. */ get: function () { return this._angle; }, /** * Sets the cone angle of the spot light in Radians. */ set: function (value) { this._angle = value; this._cosHalfAngle = Math.cos(value * 0.5); this._projectionTextureProjectionLightDirty = true; this.forceProjectionMatrixCompute(); this._computeAngleValues(); }, enumerable: true, configurable: true }); Object.defineProperty(SpotLight.prototype, "innerAngle", { /** * Only used in gltf falloff mode, this defines the angle where * the directional falloff will start before cutting at angle which could be seen * as outer angle. */ get: function () { return this._innerAngle; }, /** * Only used in gltf falloff mode, this defines the angle where * the directional falloff will start before cutting at angle which could be seen * as outer angle. */ set: function (value) { this._innerAngle = value; this._computeAngleValues(); }, enumerable: true, configurable: true }); Object.defineProperty(SpotLight.prototype, "shadowAngleScale", { /** * Allows scaling the angle of the light for shadow generation only. */ get: function () { return this._shadowAngleScale; }, /** * Allows scaling the angle of the light for shadow generation only. */ set: function (value) { this._shadowAngleScale = value; this.forceProjectionMatrixCompute(); }, enumerable: true, configurable: true }); Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", { /** * Allows reading the projecton texture */ get: function () { return this._projectionTextureMatrix; }, enumerable: true, configurable: true }); Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", { /** * Gets the near clip of the Spotlight for texture projection. */ get: function () { return this._projectionTextureLightNear; }, /** * Sets the near clip of the Spotlight for texture projection. */ set: function (value) { this._projectionTextureLightNear = value; this._projectionTextureProjectionLightDirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", { /** * Gets the far clip of the Spotlight for texture projection. */ get: function () { return this._projectionTextureLightFar; }, /** * Sets the far clip of the Spotlight for texture projection. */ set: function (value) { this._projectionTextureLightFar = value; this._projectionTextureProjectionLightDirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", { /** * Gets the Up vector of the Spotlight for texture projection. */ get: function () { return this._projectionTextureUpDirection; }, /** * Sets the Up vector of the Spotlight for texture projection. */ set: function (value) { this._projectionTextureUpDirection = value; this._projectionTextureProjectionLightDirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(SpotLight.prototype, "projectionTexture", { /** * Gets the projection texture of the light. */ get: function () { return this._projectionTexture; }, /** * Sets the projection texture of the light. */ set: function (value) { this._projectionTexture = value; this._projectionTextureDirty = true; }, enumerable: true, configurable: true }); /** * Returns the string "SpotLight". * @returns the class name */ SpotLight.prototype.getClassName = function () { return "SpotLight"; }; /** * Returns the integer 2. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x */ SpotLight.prototype.getTypeID = function () { return _light__WEBPACK_IMPORTED_MODULE_4__["Light"].LIGHTTYPEID_SPOTLIGHT; }; /** * Overrides the direction setter to recompute the projection texture view light Matrix. */ SpotLight.prototype._setDirection = function (value) { _super.prototype._setDirection.call(this, value); this._projectionTextureViewLightDirty = true; }; /** * Overrides the position setter to recompute the projection texture view light Matrix. */ SpotLight.prototype._setPosition = function (value) { _super.prototype._setPosition.call(this, value); this._projectionTextureViewLightDirty = true; }; /** * Sets the passed matrix "matrix" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0. * Returns the SpotLight. */ SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) { var activeCamera = this.getScene().activeCamera; if (!activeCamera) { return; } this._shadowAngleScale = this._shadowAngleScale || 1; var angle = this._shadowAngleScale * this._angle; _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix); }; SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () { this._projectionTextureViewLightDirty = false; this._projectionTextureDirty = true; this.position.addToRef(this.direction, this._projectionTextureViewTargetVector); _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix); }; SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () { this._projectionTextureProjectionLightDirty = false; this._projectionTextureDirty = true; var light_far = this.projectionTextureLightFar; var light_near = this.projectionTextureLightNear; var P = light_far / (light_far - light_near); var Q = -P * light_near; var S = 1.0 / Math.tan(this._angle / 2.0); var A = 1.0; _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Matrix"].FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix); }; /** * Main function for light texture projection matrix computing. */ SpotLight.prototype._computeProjectionTextureMatrix = function () { this._projectionTextureDirty = false; this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix); this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix); }; SpotLight.prototype._buildUniformLayout = function () { this._uniformBuffer.addUniform("vLightData", 4); this._uniformBuffer.addUniform("vLightDiffuse", 4); this._uniformBuffer.addUniform("vLightSpecular", 3); this._uniformBuffer.addUniform("vLightDirection", 3); this._uniformBuffer.addUniform("vLightFalloff", 4); this._uniformBuffer.addUniform("shadowsInfo", 3); this._uniformBuffer.addUniform("depthValues", 2); this._uniformBuffer.create(); }; SpotLight.prototype._computeAngleValues = function () { this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle)); this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale; }; /** * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction. * @param effect The effect to update * @param lightIndex The index of the light in the effect to update * @returns The spot light */ SpotLight.prototype.transferToEffect = function (effect, lightIndex) { var normalizeDirection; if (this.computeTransformedInformation()) { this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex); normalizeDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Normalize(this.transformedDirection); } else { this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex); normalizeDirection = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Normalize(this.direction); } this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex); this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex); if (this.projectionTexture && this.projectionTexture.isReady()) { if (this._projectionTextureViewLightDirty) { this._computeProjectionTextureViewLightMatrix(); } if (this._projectionTextureProjectionLightDirty) { this._computeProjectionTextureProjectionLightMatrix(); } if (this._projectionTextureDirty) { this._computeProjectionTextureMatrix(); } effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix); effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture); } return this; }; /** * Disposes the light and the associated resources. */ SpotLight.prototype.dispose = function () { _super.prototype.dispose.call(this); if (this._projectionTexture) { this._projectionTexture.dispose(); } }; /** * 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 */ SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) { defines["SPOTLIGHT" + lightIndex] = true; defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false; }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], SpotLight.prototype, "angle", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], SpotLight.prototype, "innerAngle", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], SpotLight.prototype, "shadowAngleScale", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], SpotLight.prototype, "exponent", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], SpotLight.prototype, "projectionTextureLightNear", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], SpotLight.prototype, "projectionTextureLightFar", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], SpotLight.prototype, "projectionTextureUpDirection", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])("projectedLightTexture") ], SpotLight.prototype, "_projectionTexture", void 0); return SpotLight; }(_shadowLight__WEBPACK_IMPORTED_MODULE_5__["ShadowLight"])); /***/ }), /***/ "./Loading/Plugins/babylonFileLoader.ts": /*!**********************************************!*\ !*** ./Loading/Plugins/babylonFileLoader.ts ***! \**********************************************/ /*! exports provided: _BabylonLoaderRegistered */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_BabylonLoaderRegistered", function() { return _BabylonLoaderRegistered; }); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Meshes/mesh */ "./Meshes/mesh.ts"); /* harmony import */ var _Meshes_geometry__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Meshes/geometry */ "./Meshes/geometry.ts"); /* harmony import */ var _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Meshes/transformNode */ "./Meshes/transformNode.ts"); /* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Materials/material */ "./Materials/material.ts"); /* harmony import */ var _Materials_multiMaterial__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Materials/multiMaterial */ "./Materials/multiMaterial.ts"); /* harmony import */ var _Materials_Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../Materials/Textures/cubeTexture */ "./Materials/Textures/cubeTexture.ts"); /* harmony import */ var _Materials_Textures_hdrCubeTexture__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../Materials/Textures/hdrCubeTexture */ "./Materials/Textures/hdrCubeTexture.ts"); /* harmony import */ var _Animations_animationGroup__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../Animations/animationGroup */ "./Animations/animationGroup.ts"); /* harmony import */ var _Lights_light__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../Lights/light */ "./Lights/light.ts"); /* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../../sceneComponent */ "./sceneComponent.ts"); /* harmony import */ var _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../../Loading/sceneLoader */ "./Loading/sceneLoader.ts"); /* harmony import */ var _abstractScene__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../../abstractScene */ "./abstractScene.ts"); /* harmony import */ var _assetContainer__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../../assetContainer */ "./assetContainer.ts"); /* harmony import */ var _Actions_actionManager__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../../Actions/actionManager */ "./Actions/actionManager.ts"); /* harmony import */ var _Bones_skeleton__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../../Bones/skeleton */ "./Bones/skeleton.ts"); /* harmony import */ var _Morph_morphTargetManager__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../../Morph/morphTargetManager */ "./Morph/morphTargetManager.ts"); /* harmony import */ var _Physics_Plugins_cannonJSPlugin__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../../Physics/Plugins/cannonJSPlugin */ "./Physics/Plugins/cannonJSPlugin.ts"); /* harmony import */ var _Physics_Plugins_oimoJSPlugin__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../../Physics/Plugins/oimoJSPlugin */ "./Physics/Plugins/oimoJSPlugin.ts"); /* harmony import */ var _Physics_Plugins_ammoJSPlugin__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../../Physics/Plugins/ammoJSPlugin */ "./Physics/Plugins/ammoJSPlugin.ts"); /* harmony import */ var _Probes_reflectionProbe__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../../Probes/reflectionProbe */ "./Probes/reflectionProbe.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts"); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); /** @hidden */ var _BabylonLoaderRegistered = true; var parseMaterialById = function (id, parsedData, scene, rootUrl) { for (var index = 0, cache = parsedData.materials.length; index < cache; index++) { var parsedMaterial = parsedData.materials[index]; if (parsedMaterial.id === id) { return _Materials_material__WEBPACK_IMPORTED_MODULE_6__["Material"].Parse(parsedMaterial, scene, rootUrl); } } return null; }; var isDescendantOf = function (mesh, names, hierarchyIds) { for (var i in names) { if (mesh.name === names[i]) { hierarchyIds.push(mesh.id); return true; } } if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) { hierarchyIds.push(mesh.id); return true; } return false; }; var logOperation = function (operation, producer) { return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown"); }; var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) { if (addToScene === void 0) { addToScene = false; } var container = new _assetContainer__WEBPACK_IMPORTED_MODULE_15__["AssetContainer"](scene); // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details // when SceneLoader.debugLogging = true (default), or exception encountered. // Everything stored in var log instead of writing separate lines to support only writing in exception, // and avoid problems with multiple concurrent .babylon loads. var log = "importScene has failed JSON parse"; try { var parsedData = JSON.parse(data); log = ""; var fullDetails = _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].loggingLevel === _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].DETAILED_LOGGING; var index; var cache; // Environment texture if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) { // PBR needed for both HDR texture (gamma space) & a sky box var isPBR = parsedData.isPBR !== undefined ? parsedData.isPBR : true; if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") { var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128; var hdrTexture = new _Materials_Textures_hdrCubeTexture__WEBPACK_IMPORTED_MODULE_9__["HDRCubeTexture"]((parsedData.environmentTexture.match(/https?:\/\//g) ? "" : rootUrl) + parsedData.environmentTexture, scene, hdrSize, true, !isPBR); if (parsedData.environmentTextureRotationY) { hdrTexture.rotationY = parsedData.environmentTextureRotationY; } scene.environmentTexture = hdrTexture; } else { if (_Misc_tools__WEBPACK_IMPORTED_MODULE_24__["Tools"].EndsWith(parsedData.environmentTexture, ".env")) { var compressedTexture = new _Materials_Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_8__["CubeTexture"]((parsedData.environmentTexture.match(/https?:\/\//g) ? "" : rootUrl) + parsedData.environmentTexture, scene); if (parsedData.environmentTextureRotationY) { compressedTexture.rotationY = parsedData.environmentTextureRotationY; } scene.environmentTexture = compressedTexture; } else { var cubeTexture = _Materials_Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_8__["CubeTexture"].CreateFromPrefilteredData((parsedData.environmentTexture.match(/https?:\/\//g) ? "" : rootUrl) + parsedData.environmentTexture, scene); if (parsedData.environmentTextureRotationY) { cubeTexture.rotationY = parsedData.environmentTextureRotationY; } scene.environmentTexture = cubeTexture; } } if (parsedData.createDefaultSkybox === true) { var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000; var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0; scene.createDefaultSkybox(scene.environmentTexture, isPBR, skyboxScale, skyboxBlurLevel); } container.environmentTexture = scene.environmentTexture; } // Lights if (parsedData.lights !== undefined && parsedData.lights !== null) { for (index = 0, cache = parsedData.lights.length; index < cache; index++) { var parsedLight = parsedData.lights[index]; var light = _Lights_light__WEBPACK_IMPORTED_MODULE_11__["Light"].Parse(parsedLight, scene); if (light) { container.lights.push(light); log += (index === 0 ? "\n\tLights:" : ""); log += "\n\t\t" + light.toString(fullDetails); } } } // Reflection probes if (parsedData.reflectionProbes !== undefined && parsedData.reflectionProbes !== null) { for (index = 0, cache = parsedData.reflectionProbes.length; index < cache; index++) { var parsedReflectionProbe = parsedData.reflectionProbes[index]; var reflectionProbe = _Probes_reflectionProbe__WEBPACK_IMPORTED_MODULE_22__["ReflectionProbe"].Parse(parsedReflectionProbe, scene, rootUrl); if (reflectionProbe) { container.reflectionProbes.push(reflectionProbe); log += (index === 0 ? "\n\tReflection Probes:" : ""); log += "\n\t\t" + reflectionProbe.toString(fullDetails); } } } // Animations if (parsedData.animations !== undefined && parsedData.animations !== null) { for (index = 0, cache = parsedData.animations.length; index < cache; index++) { var parsedAnimation = parsedData.animations[index]; var internalClass = _Misc_typeStore__WEBPACK_IMPORTED_MODULE_23__["_TypeStore"].GetClass("BABYLON.Animation"); if (internalClass) { var animation = internalClass.Parse(parsedAnimation); scene.animations.push(animation); container.animations.push(animation); log += (index === 0 ? "\n\tAnimations:" : ""); log += "\n\t\t" + animation.toString(fullDetails); } } } // Materials if (parsedData.materials !== undefined && parsedData.materials !== null) { for (index = 0, cache = parsedData.materials.length; index < cache; index++) { var parsedMaterial = parsedData.materials[index]; var mat = _Materials_material__WEBPACK_IMPORTED_MODULE_6__["Material"].Parse(parsedMaterial, scene, rootUrl); if (mat) { container.materials.push(mat); log += (index === 0 ? "\n\tMaterials:" : ""); log += "\n\t\t" + mat.toString(fullDetails); // Textures var textures = mat.getActiveTextures(); textures.forEach(function (t) { if (container.textures.indexOf(t) == -1) { container.textures.push(t); } }); } } } if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) { for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) { var parsedMultiMaterial = parsedData.multiMaterials[index]; var mmat = _Materials_multiMaterial__WEBPACK_IMPORTED_MODULE_7__["MultiMaterial"].ParseMultiMaterial(parsedMultiMaterial, scene); container.multiMaterials.push(mmat); log += (index === 0 ? "\n\tMultiMaterials:" : ""); log += "\n\t\t" + mmat.toString(fullDetails); // Textures var textures = mmat.getActiveTextures(); textures.forEach(function (t) { if (container.textures.indexOf(t) == -1) { container.textures.push(t); } }); } } // Morph targets if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) { for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) { var managerData = _a[_i]; container.morphTargetManagers.push(_Morph_morphTargetManager__WEBPACK_IMPORTED_MODULE_18__["MorphTargetManager"].Parse(managerData, scene)); } } // Skeletons if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) { for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) { var parsedSkeleton = parsedData.skeletons[index]; var skeleton = _Bones_skeleton__WEBPACK_IMPORTED_MODULE_17__["Skeleton"].Parse(parsedSkeleton, scene); container.skeletons.push(skeleton); log += (index === 0 ? "\n\tSkeletons:" : ""); log += "\n\t\t" + skeleton.toString(fullDetails); } } // Geometries var geometries = parsedData.geometries; if (geometries !== undefined && geometries !== null) { var addedGeometry = new Array(); // VertexData var vertexData = geometries.vertexData; if (vertexData !== undefined && vertexData !== null) { for (index = 0, cache = vertexData.length; index < cache; index++) { var parsedVertexData = vertexData[index]; addedGeometry.push(_Meshes_geometry__WEBPACK_IMPORTED_MODULE_4__["Geometry"].Parse(parsedVertexData, scene, rootUrl)); } } addedGeometry.forEach(function (g) { if (g) { container.geometries.push(g); } }); } // Transform nodes if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) { for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) { var parsedTransformNode = parsedData.transformNodes[index]; var node = _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_5__["TransformNode"].Parse(parsedTransformNode, scene, rootUrl); container.transformNodes.push(node); } } // Meshes if (parsedData.meshes !== undefined && parsedData.meshes !== null) { for (index = 0, cache = parsedData.meshes.length; index < cache; index++) { var parsedMesh = parsedData.meshes[index]; var mesh = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"].Parse(parsedMesh, scene, rootUrl); container.meshes.push(mesh); log += (index === 0 ? "\n\tMeshes:" : ""); log += "\n\t\t" + mesh.toString(fullDetails); } } // Cameras if (parsedData.cameras !== undefined && parsedData.cameras !== null) { for (index = 0, cache = parsedData.cameras.length; index < cache; index++) { var parsedCamera = parsedData.cameras[index]; var camera = _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].Parse(parsedCamera, scene); container.cameras.push(camera); log += (index === 0 ? "\n\tCameras:" : ""); log += "\n\t\t" + camera.toString(fullDetails); } } // Animation Groups if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) { for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) { var parsedAnimationGroup = parsedData.animationGroups[index]; var animationGroup = _Animations_animationGroup__WEBPACK_IMPORTED_MODULE_10__["AnimationGroup"].Parse(parsedAnimationGroup, scene); container.animationGroups.push(animationGroup); log += (index === 0 ? "\n\tAnimationGroups:" : ""); log += "\n\t\t" + animationGroup.toString(fullDetails); } } // Browsing all the graph to connect the dots for (index = 0, cache = scene.cameras.length; index < cache; index++) { var camera = scene.cameras[index]; if (camera._waitingParentId) { camera.parent = scene.getLastEntryByID(camera._waitingParentId); camera._waitingParentId = null; } } for (index = 0, cache = scene.lights.length; index < cache; index++) { var light_1 = scene.lights[index]; if (light_1 && light_1._waitingParentId) { light_1.parent = scene.getLastEntryByID(light_1._waitingParentId); light_1._waitingParentId = null; } } // Connect parents & children and parse actions for (index = 0, cache = scene.transformNodes.length; index < cache; index++) { var transformNode = scene.transformNodes[index]; if (transformNode._waitingParentId) { transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId); transformNode._waitingParentId = null; } } for (index = 0, cache = scene.meshes.length; index < cache; index++) { var mesh = scene.meshes[index]; if (mesh._waitingParentId) { mesh.parent = scene.getLastEntryByID(mesh._waitingParentId); mesh._waitingParentId = null; } } // freeze world matrix application for (index = 0, cache = scene.meshes.length; index < cache; index++) { var currentMesh = scene.meshes[index]; if (currentMesh._waitingFreezeWorldMatrix) { currentMesh.freezeWorldMatrix(); currentMesh._waitingFreezeWorldMatrix = null; } else { currentMesh.computeWorldMatrix(true); } } // Lights exclusions / inclusions for (index = 0, cache = scene.lights.length; index < cache; index++) { var light_2 = scene.lights[index]; // Excluded check if (light_2._excludedMeshesIds.length > 0) { for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) { var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]); if (excludedMesh) { light_2.excludedMeshes.push(excludedMesh); } } light_2._excludedMeshesIds = []; } // Included check if (light_2._includedOnlyMeshesIds.length > 0) { for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) { var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]); if (includedOnlyMesh) { light_2.includedOnlyMeshes.push(includedOnlyMesh); } } light_2._includedOnlyMeshesIds = []; } } _abstractScene__WEBPACK_IMPORTED_MODULE_14__["AbstractScene"].Parse(parsedData, scene, container, rootUrl); // Actions (scene) Done last as it can access other objects. for (index = 0, cache = scene.meshes.length; index < cache; index++) { var mesh = scene.meshes[index]; if (mesh._waitingActions) { _Actions_actionManager__WEBPACK_IMPORTED_MODULE_16__["ActionManager"].Parse(mesh._waitingActions, mesh, scene); mesh._waitingActions = null; } } if (parsedData.actions !== undefined && parsedData.actions !== null) { _Actions_actionManager__WEBPACK_IMPORTED_MODULE_16__["ActionManager"].Parse(parsedData.actions, null, scene); } if (!addToScene) { container.removeAllFromScene(); } } catch (err) { var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log; if (onError) { onError(msg, err); } else { _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Log(msg); throw err; } } finally { if (log !== null && _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].loggingLevel !== _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].NO_LOGGING) { _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (_Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].loggingLevel !== _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].MINIMAL_LOGGING ? log : "")); } } return container; }; _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].RegisterPlugin({ name: "babylon.js", extensions: ".babylon", canDirectLoad: function (data) { if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled return true; } return false; }, importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) { // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details // when SceneLoader.debugLogging = true (default), or exception encountered. // Everything stored in var log instead of writing separate lines to support only writing in exception, // and avoid problems with multiple concurrent .babylon loads. var log = "importMesh has failed JSON parse"; try { var parsedData = JSON.parse(data); log = ""; var fullDetails = _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].loggingLevel === _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].DETAILED_LOGGING; if (!meshesNames) { meshesNames = null; } else if (!Array.isArray(meshesNames)) { meshesNames = [meshesNames]; } var hierarchyIds = new Array(); if (parsedData.meshes !== undefined && parsedData.meshes !== null) { var loadedSkeletonsIds = []; var loadedMaterialsIds = []; var index; var cache; for (index = 0, cache = parsedData.meshes.length; index < cache; index++) { var parsedMesh = parsedData.meshes[index]; if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) { if (meshesNames !== null) { // Remove found mesh name from list. delete meshesNames[meshesNames.indexOf(parsedMesh.name)]; } //Geometry? if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) { //does the file contain geometries? if (parsedData.geometries !== undefined && parsedData.geometries !== null) { //find the correct geometry and add it to the scene var found = false; ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) { if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) { return; } else { parsedData.geometries[geometryType].forEach(function (parsedGeometryData) { if (parsedGeometryData.id === parsedMesh.geometryId) { switch (geometryType) { case "vertexData": _Meshes_geometry__WEBPACK_IMPORTED_MODULE_4__["Geometry"].Parse(parsedGeometryData, scene, rootUrl); break; } found = true; } }); } }); if (found === false) { _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Warn("Geometry not found for mesh " + parsedMesh.id); } } } // Material ? if (parsedMesh.materialId) { var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1); if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) { for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) { var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex]; if (parsedMultiMaterial.id === parsedMesh.materialId) { for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) { var subMatId = parsedMultiMaterial.materials[matIndex]; loadedMaterialsIds.push(subMatId); var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl); if (mat) { log += "\n\tMaterial " + mat.toString(fullDetails); } } loadedMaterialsIds.push(parsedMultiMaterial.id); var mmat = _Materials_multiMaterial__WEBPACK_IMPORTED_MODULE_7__["MultiMaterial"].ParseMultiMaterial(parsedMultiMaterial, scene); if (mmat) { materialFound = true; log += "\n\tMulti-Material " + mmat.toString(fullDetails); } break; } } } if (materialFound === false) { loadedMaterialsIds.push(parsedMesh.materialId); var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl); if (!mat) { _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Warn("Material not found for mesh " + parsedMesh.id); } else { log += "\n\tMaterial " + mat.toString(fullDetails); } } } // Skeleton ? if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) { var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1); if (skeletonAlreadyLoaded === false) { for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) { var parsedSkeleton = parsedData.skeletons[skeletonIndex]; if (parsedSkeleton.id === parsedMesh.skeletonId) { var skeleton = _Bones_skeleton__WEBPACK_IMPORTED_MODULE_17__["Skeleton"].Parse(parsedSkeleton, scene); skeletons.push(skeleton); loadedSkeletonsIds.push(parsedSkeleton.id); log += "\n\tSkeleton " + skeleton.toString(fullDetails); } } } } // Morph targets ? if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) { for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) { var managerData = _a[_i]; _Morph_morphTargetManager__WEBPACK_IMPORTED_MODULE_18__["MorphTargetManager"].Parse(managerData, scene); } } var mesh = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"].Parse(parsedMesh, scene, rootUrl); meshes.push(mesh); log += "\n\tMesh " + mesh.toString(fullDetails); } } // Connecting parents var currentMesh; for (index = 0, cache = scene.meshes.length; index < cache; index++) { currentMesh = scene.meshes[index]; if (currentMesh._waitingParentId) { currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId); currentMesh._waitingParentId = null; } } // freeze and compute world matrix application for (index = 0, cache = scene.meshes.length; index < cache; index++) { currentMesh = scene.meshes[index]; if (currentMesh._waitingFreezeWorldMatrix) { currentMesh.freezeWorldMatrix(); currentMesh._waitingFreezeWorldMatrix = null; } else { currentMesh.computeWorldMatrix(true); } } } // Particles if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) { var parser = _abstractScene__WEBPACK_IMPORTED_MODULE_14__["AbstractScene"].GetIndividualParser(_sceneComponent__WEBPACK_IMPORTED_MODULE_12__["SceneComponentConstants"].NAME_PARTICLESYSTEM); if (parser) { for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) { var parsedParticleSystem = parsedData.particleSystems[index]; if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) { particleSystems.push(parser(parsedParticleSystem, scene, rootUrl)); } } } } return true; } catch (err) { var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log; if (onError) { onError(msg, err); } else { _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Log(msg); throw err; } } finally { if (log !== null && _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].loggingLevel !== _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].NO_LOGGING) { _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (_Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].loggingLevel !== _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].MINIMAL_LOGGING ? log : "")); } } return false; }, load: function (scene, data, rootUrl, onError) { // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details // when SceneLoader.debugLogging = true (default), or exception encountered. // Everything stored in var log instead of writing separate lines to support only writing in exception, // and avoid problems with multiple concurrent .babylon loads. var log = "importScene has failed JSON parse"; try { var parsedData = JSON.parse(data); log = ""; // Scene if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) { scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !_Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].ForceFullSceneLoadingForIncremental; } if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) { scene.autoClear = parsedData.autoClear; } if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) { scene.clearColor = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color4"].FromArray(parsedData.clearColor); } if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) { scene.ambientColor = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"].FromArray(parsedData.ambientColor); } if (parsedData.gravity !== undefined && parsedData.gravity !== null) { scene.gravity = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].FromArray(parsedData.gravity); } // Fog if (parsedData.fogMode && parsedData.fogMode !== 0) { scene.fogMode = parsedData.fogMode; scene.fogColor = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"].FromArray(parsedData.fogColor); scene.fogStart = parsedData.fogStart; scene.fogEnd = parsedData.fogEnd; scene.fogDensity = parsedData.fogDensity; log += "\tFog mode for scene: "; switch (scene.fogMode) { // getters not compiling, so using hardcoded case 1: log += "exp\n"; break; case 2: log += "exp2\n"; break; case 3: log += "linear\n"; break; } } //Physics if (parsedData.physicsEnabled) { var physicsPlugin; if (parsedData.physicsEngine === "cannon") { physicsPlugin = new _Physics_Plugins_cannonJSPlugin__WEBPACK_IMPORTED_MODULE_19__["CannonJSPlugin"](); } else if (parsedData.physicsEngine === "oimo") { physicsPlugin = new _Physics_Plugins_oimoJSPlugin__WEBPACK_IMPORTED_MODULE_20__["OimoJSPlugin"](); } else if (parsedData.physicsEngine === "ammo") { physicsPlugin = new _Physics_Plugins_ammoJSPlugin__WEBPACK_IMPORTED_MODULE_21__["AmmoJSPlugin"](); } log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n"; //else - default engine, which is currently oimo var physicsGravity = parsedData.physicsGravity ? _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"].FromArray(parsedData.physicsGravity) : null; scene.enablePhysics(physicsGravity, physicsPlugin); } // Metadata if (parsedData.metadata !== undefined && parsedData.metadata !== null) { scene.metadata = parsedData.metadata; } //collisions, if defined. otherwise, default is true if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) { scene.collisionsEnabled = parsedData.collisionsEnabled; } var container = loadAssetContainer(scene, data, rootUrl, onError, true); if (!container) { return false; } if (parsedData.autoAnimate) { scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0); } if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) { scene.setActiveCameraByID(parsedData.activeCameraID); } // Environment texture if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) { // PBR needed for both HDR texture (gamma space) & a sky box var isPBR = parsedData.isPBR !== undefined ? parsedData.isPBR : true; if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") { var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128; var hdrTexture = new _Materials_Textures_hdrCubeTexture__WEBPACK_IMPORTED_MODULE_9__["HDRCubeTexture"](rootUrl + parsedData.environmentTexture, scene, hdrSize, true, !isPBR); if (parsedData.environmentTextureRotationY) { hdrTexture.rotationY = parsedData.environmentTextureRotationY; } scene.environmentTexture = hdrTexture; } else { if (_Misc_tools__WEBPACK_IMPORTED_MODULE_24__["Tools"].EndsWith(parsedData.environmentTexture, ".env")) { var compressedTexture = new _Materials_Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_8__["CubeTexture"](rootUrl + parsedData.environmentTexture, scene); if (parsedData.environmentTextureRotationY) { compressedTexture.rotationY = parsedData.environmentTextureRotationY; } scene.environmentTexture = compressedTexture; } else { var cubeTexture = _Materials_Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_8__["CubeTexture"].CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene); if (parsedData.environmentTextureRotationY) { cubeTexture.rotationY = parsedData.environmentTextureRotationY; } scene.environmentTexture = cubeTexture; } } if (parsedData.createDefaultSkybox === true) { var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000; var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0; scene.createDefaultSkybox(scene.environmentTexture, isPBR, skyboxScale, skyboxBlurLevel); } } // Finish return true; } catch (err) { var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log; if (onError) { onError(msg, err); } else { _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Log(msg); throw err; } } finally { if (log !== null && _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].loggingLevel !== _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].NO_LOGGING) { _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (_Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].loggingLevel !== _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_13__["SceneLoader"].MINIMAL_LOGGING ? log : "")); } } return false; }, loadAssetContainer: function (scene, data, rootUrl, onError) { var container = loadAssetContainer(scene, data, rootUrl, onError); return container; } }); /***/ }), /***/ "./Loading/Plugins/index.ts": /*!**********************************!*\ !*** ./Loading/Plugins/index.ts ***! \**********************************/ /*! exports provided: _BabylonLoaderRegistered */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _babylonFileLoader__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./babylonFileLoader */ "./Loading/Plugins/babylonFileLoader.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_BabylonLoaderRegistered", function() { return _babylonFileLoader__WEBPACK_IMPORTED_MODULE_0__["_BabylonLoaderRegistered"]; }); /***/ }), /***/ "./Loading/index.ts": /*!**************************!*\ !*** ./Loading/index.ts ***! \**************************/ /*! exports provided: DefaultLoadingScreen, SceneLoaderProgressEvent, SceneLoader, SceneLoaderFlags, _BabylonLoaderRegistered */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _loadingScreen__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./loadingScreen */ "./Loading/loadingScreen.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DefaultLoadingScreen", function() { return _loadingScreen__WEBPACK_IMPORTED_MODULE_0__["DefaultLoadingScreen"]; }); /* harmony import */ var _Plugins_index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Plugins/index */ "./Loading/Plugins/index.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_BabylonLoaderRegistered", function() { return _Plugins_index__WEBPACK_IMPORTED_MODULE_1__["_BabylonLoaderRegistered"]; }); /* harmony import */ var _sceneLoader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./sceneLoader */ "./Loading/sceneLoader.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneLoaderProgressEvent", function() { return _sceneLoader__WEBPACK_IMPORTED_MODULE_2__["SceneLoaderProgressEvent"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneLoader", function() { return _sceneLoader__WEBPACK_IMPORTED_MODULE_2__["SceneLoader"]; }); /* harmony import */ var _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./sceneLoaderFlags */ "./Loading/sceneLoaderFlags.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneLoaderFlags", function() { return _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_3__["SceneLoaderFlags"]; }); /***/ }), /***/ "./Loading/loadingScreen.ts": /*!**********************************!*\ !*** ./Loading/loadingScreen.ts ***! \**********************************/ /*! exports provided: DefaultLoadingScreen */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DefaultLoadingScreen", function() { return DefaultLoadingScreen; }); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); /** * Class used for the default loading screen * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen */ var DefaultLoadingScreen = /** @class */ (function () { /** * Creates a new default loading screen * @param _renderingCanvas defines the canvas used to render the scene * @param _loadingText defines the default text to display * @param _loadingDivBackgroundColor defines the default background color */ function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) { if (_loadingText === void 0) { _loadingText = ""; } if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; } var _this = this; this._renderingCanvas = _renderingCanvas; this._loadingText = _loadingText; this._loadingDivBackgroundColor = _loadingDivBackgroundColor; // Resize this._resizeLoadingUI = function () { var canvasRect = _this._renderingCanvas.getBoundingClientRect(); var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position; if (!_this._loadingDiv) { return; } _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute"; _this._loadingDiv.style.left = canvasRect.left + "px"; _this._loadingDiv.style.top = canvasRect.top + "px"; _this._loadingDiv.style.width = canvasRect.width + "px"; _this._loadingDiv.style.height = canvasRect.height + "px"; }; } /** * Function called to display the loading screen */ DefaultLoadingScreen.prototype.displayLoadingUI = function () { if (this._loadingDiv) { // Do not add a loading screen if there is already one return; } this._loadingDiv = document.createElement("div"); this._loadingDiv.id = "babylonjsLoadingDiv"; this._loadingDiv.style.opacity = "0"; this._loadingDiv.style.transition = "opacity 1.5s ease"; this._loadingDiv.style.pointerEvents = "none"; // Loading text this._loadingTextDiv = document.createElement("div"); this._loadingTextDiv.style.position = "absolute"; this._loadingTextDiv.style.left = "0"; this._loadingTextDiv.style.top = "50%"; this._loadingTextDiv.style.marginTop = "80px"; this._loadingTextDiv.style.width = "100%"; this._loadingTextDiv.style.height = "20px"; this._loadingTextDiv.style.fontFamily = "Arial"; this._loadingTextDiv.style.fontSize = "14px"; this._loadingTextDiv.style.color = "white"; this._loadingTextDiv.style.textAlign = "center"; this._loadingTextDiv.innerHTML = "Loading"; this._loadingDiv.appendChild(this._loadingTextDiv); //set the predefined text this._loadingTextDiv.innerHTML = this._loadingText; // Generating keyframes var style = document.createElement('style'); style.type = 'text/css'; var keyFrames = "@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }"; style.innerHTML = keyFrames; document.getElementsByTagName('head')[0].appendChild(style); // Loading img var imgBack = new Image(); imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZQHvphnV65cjTMzxaQY3eA5V9OO/hmnm1lSjE7woFsQbiXki4++foHnXkW4mLC1JUl947333tsMY3emqfB9jtPJlXN5U0+bOXPmWCPxgOccSy4+AfqPio+9/oFnbyatbqVE28GSZfjQ1NT0KQzaHMcdyPfyaNoE12HcvdxT29K3Fkv8A2vWrPmcifAFZNtD91yRY+SBZ+9UsMtEgD+jTpeenp6JXI6xpKkuUDqRcA6Kr0Wpens+InQTnIpV6Fdi+BQT64ulS5eOIzefD62na7CeoGcnLCM8ykt5OWlzcPv772/BS/w3nP+K+xU11+DvQe5dcrQlTfWAwbNMb8XA8AyGX80xtLlA6TAJuteMbVhhia1v5VMcr+LWMeoZ4xiYw7q6urbhHbgG+paCkIRQehHu4pO3O5fVydEomF5Ulx548JfVD2wqfKE2I3R3ob/f2GoC1DWhdz7HG3i5j2pvb9+Z24m6HvVZQtYsZFWcowlzePEP4jJdR/OQhxTVpAs9NMXxmZxuZKo8IG4s+v8R2tUFphSBTBWzH+OAFwn/gS3TuN55xYoVqfc6dXd3fwHZ1xFaTX0iyGbwjJqXXAammxP00EXx6UMGEx7ram7+vKnzBZ/87Xiwp40tEdDTgYwlHG/CmadSjO7L+XiialOZAej7POFG2VK0Khngl6Pn8/LL0YEtlFh4n8oDAqvaAYH8tzH2iNDm1IIFn8Ax50G7xtgCAU07CfAG4RHOz+vLZL7e0dGxlYlKHaj8BHo25xgrsfV5wrYH4KmouxV+ZZDnCUdwmXxMGgFvFUVWD+jQuOot6rI0tb4gcfaG9v+MrcAn+wj38gL8C7cObmlp2ZRjOkWYD6ypuAf6zjFHLSJ0c/6YQ813DM/yZXgehreiVgP8cvSfsOeExYsXuzs6n8v9j8mqBRZQmdjXVPuira1NHSpn8UDf4Xu0vd2uCtDzacJOlDDf5ng94X8JTWarB8R1EK7ju7udiYgEz/v3pLFKm4oHUHhh3iZdfshpaEYpA4pvKLLXBujLYKRq71XLhUHg27z12rW9B6L/QhLrWWxRH7nzeDK8awi/5HRTEx0K6MZQ694LHk0DqrgfADkreIYz1q5c+UlTEQzesIuMryrggYQWjNL3RGO7p2tuFMeqjaOidgzyCz1yJMTJ6L6d66WEVCcHIO/dQkI75Chs2g97Hoc3jRz9Lge1ED5l4r0gckqRPB0gTw34t1B+h3IqxZkmrn2SULUa7ezZszdE5xfR9130Xsm5ilrnHrmkQOcKvrkncxqrIiY6wlewbw7BOUfDo/b84zzvj9C7J7eCS0NrUiRKCPjUE7ScMBdlF/B2HqBi0ERXBcuXL99YnQz9fX2ah3Up4UnsWGEmDRuUhoTn+Z5PfvbZZ2N/fuCZRJgnfhNVBu73EZoIKt7l0L2UBsYeDZg016nb5EUCWuXQewinUtTuyq2aTStF14a8SD+VDQVj6hDYxjuXf4Hjl83sSMCmTp8j4FtoMuRQ5dAZcii3kk/0s2bBhxIcBxjxUlib1hWInEDO/6qKV+y4geO5HAMntEE/pq+nZyo0ywsG1SmwL4Orf+0yqGCfmvR73LAn9lAeBjQTEhkA+1h49a08iRflcq4H5iuXFU9cz4lqihC/LXS/NZa6Bc+pz5gql5ub6VXD2tZWTSPeyS7XgeLhXrMnEhj6MSHSwaIhFGZH8oA/JzzFeexvJbRN2HW03moT6cEChx6w4QY2rurn85JWrxsiCy0FwjcIqos8w7GZNPulkawDEbFHlaBtjzODEDrVztuKXMmADPWA3RaljyJeNdKq98ilAez8iJdyGqfO31V4NoV/EvyaCqR54V2EshE5Lqcb+TrkstkTLD4WKB4PNNZQ8P05HAelMXNSPWChC8JsYvwthJo0jSoF6fIqjjqe08Aat+LIkd+AVjn09zxbZFqK3tjXAUbXUaWDjTUSyN4J45YZX2Igo4cEOVfFson2ALIxSjR0jog5YNgpfNHM90BxIjDyWIB8Z2NfB01HISJ20wPaw4w1FlavXq1v8aPGXhFw9JNRFTDItifU/RwwpfmKxYsDK180kU4x0lhAXvOSJUs+bezlIDL2N4xi4GpjK4MGCuzUA+SPxzn3m4iKgKyV2DCV08DeMWg0B+zHHOt2DpjS3Mz1BfFOM25C5ZH4LxldJBB0g7GVARkaXgv8VsKqZtIMPpN9RUnJgRzU5Wfp22vifcG3+2vQvmdsdQXsX2pm+oKX+GYjjQXkPWqsXshpRhcJ0RpbGShSHiSuheP37ZYHsGusVHOrU1lMxkO9od4eE+8LlSzQqfetpnPAooBN/2Um+gISp89MkF8K4G3RrMJYoOhbYGxlQEGhSOGogfoLwipExGtUZVVBYIVAluaAaUpuWA+YujlPF22Ra/iBLYEOsV6tV4w0FiitfmLsXiBMU0NiAVrfsp77Zd8MHPgbDoHtva6uLs1jiv1piAKy5tCG+4KJ9wVO/p6RDzvy+b5rzSwP9Okh/WKPERiCWzfk4K8bUSTiOljAyCdx5DZG4gE8W5Dov+NYUfsV/j50fUC4dmXIQDh0qQ6PVgJsOcLM8oA410Ggvo6Ojr81di+g2TKuQOiyJOKWxlpCJpM5zUjKAL3awTsamQfEbYhjtDGKa5tPsyn/wAuiURftlBO56h6aunEwCMxxvV1d+2Fr7Jce2vAu5LUtLeoGi/19gtbToCaR97BoD6BvUs+WkXqgbw6OuhC6wH5l4rRGaCFOvYnjYbyxnpcsCvDVhYOxo6+zszNwSNHVTtJEmSiwzlMAQmNPwIPW42Dds2hfEK/5WJo0Fth+5VNxFHSlkoTzFRh/N3wnq0OGWxXtdoO8enFwaI4jsyidYgNZTxhrMEjEJ4w+En65ESWRXZ7Q4K/COqDAPlhka87WedB8KawmngTIHREOJs5pMiRp+p/GGgxL1FiA9hxjK6G1tVVdhJGAV15+cPXq1f7dahVC20Wg4miCp0uTe3Xh4Hwu93rY1B7SR/t7xQbP5R1FGgpy8IlKe+MJhZ9Aa7u5jPm+pGLX2BMDOZ+hDXgQiXIJ5xoXHZg96anEEFcvOTi0SMUXS4w0FijSTzTWYEA3hkTSEtDI2qw6RoytDLA6jctCvzKqJ8oPFOO7kAhnYe9cZGiWiZ/N9ezguWaSL4h3TUfvKJIfoN0I4sjigYSdZyxlcDVMgEczEY41ER6oZFBOh2Yqegf2zYoziFC3DuZZrjSTPLDtMlxaNPmPP/54W2OPxksrVozP5fLPGr8vEOpbxJCr3jQSJyDvGRNRhv7iHh8vE5LMpKznHBz4zSTOaXwe+mXGGh9tbWvVQf+iyfCAON/ZlTj4v43ECfB94Le4CuMrWVpTtw7O9fZOM5M8oD7xVSOLBdLuNWN1g7bgJUF8+4qpBjf7Te9M6hD4tBDc0289Wh2MHbuaSR7gsHOMLBaQ9W/G6o5MJrNDPu9dcYdQ33Yc95I6OFV5hnp2cGCliDingX5KU+9MShd0dmqta/k8J4zwnV2JsuuNxAnI83VwNpO52kiSoC4djA255cuXBzYPycGzjTQWkPdNY00OfRcQVLafRnd39ySLLsG1i20AyPZ3cDb7AyNJgnp1cOhUHUhcFiL045v9jTUa8Gjlm29fsQQhb3DzJLUEhC+oiK7EISPOwapoEh+7JQJti5YfGXs0YNC62ouC1h9lsrlToClsjc/RM7uSe0kd3EmlzTO/Kqk8Q106mM/Yw2aOB9jnOg6sWTHxJ9FraSJMy6nGz7RbZUDYmN7e3BnQ5Gisez7u3J9c0JwA6Pb0aCFvNObgwKk6NoU59uJwaJ8y1viAT4vCtEFXYO8SFQGtCZpllyXQtNqL+4lmZ/BN/5qJKQFZozEHe9JtAGSaw4wsFnie4JmUQcjleh8yZq0Fnmq3y0D02IzPMgnonYqYIfA4pC+TcXrgIahLB+PEb5s5HrjaR0b7kbHGB0pK7TDO1/T39x1lUZGAPlUH0xTbz+KSoC4dDDx2DQCHzTCaWOB5zjbW+KCSpW0IS0BIJmy6zWCk7WDuxZ4r5oO6dHB7e/sBZo4H2OfUsYOv9jHW+ECJdkAtA/c6MpmMd+XaEKj7km9M4F5TEfBzSKovDLKG1cHobw+b6EDa3WOksYBPAhevBUJMxl8GJTRhFyMLBKSJFn5ls9nvmogS0DfaHOzb3h8AcUuNNBLQNiWa0gRv4MwMMyBwCqxAfCIH82JdYSJKQN+ocjA5NHD2I/e1aj/23iPyhbG6A+bAgXsZoUEII/UAkkQORu71JqIE7o22HBw4VaelpWU74mPPDc/39d1trO5Qb4vJ8QXxbwat06WofcTInMCzeToAtN4VXUn/l1AXDkan9tDSfmL6C81BZooHxDkN9CMveLFZFFAWWZtDwVta3G0sJcAbe3bmYEiniShBXabcL+wflQDD5mD0yKlvk0b/Tk33AG5F7idG+/ibRe54oEl1nLG6A+ZYe1jyAIuG/u2LB3MazxwAfL5vJFGJinxQUwcju6c/n3+FNPm5JhJyy2k/sQTp5nm+2HBJCGi1X1WpwzuBoQXAN+IcjDz8mdePKi/WhH1uxd7GcCjIVBcWpUYDfZ0VbclEJSr2akMBhVrdX6j+Jx3DpSh7vKB8CIiqKwcrcXGqdr05k3RKbU9ryTQVkUB3aHMrEshw7kGCXiv8xxG0h6Uzent6Fpn6MhA17A6GT/3yTxNO1coJbgWur3JFf1fXNuTes5AZe18xXobFHJKv04JZc3O7CtIcgGL9KW03u3QCfL4D4b292dhrpoYgsYOhEz4kaOuHqXKqiagYiN9QnUlyKgX84JUYsQFP9GKzMFRSe8XJb9upE9Dn62CK/KQT75wdTLz+NXgPNdrDuYzeUd0ByN4Wp07n+EdCRZuTY1/ymZQDwIjQye9pA32xdw6IiUgHc639mN8kzCLRjkxzQRzitUpkZ8LZBP1CILUd55EVvdgsCrzJl5i8mgCja+Zgjst4Pq3DUnMmtSWqyNIuQruRU3+CbO08n+pvBAZAjf1IU5kcGJc0YRMBfVV3MPd2RN4+YbvYukI/3sSpe+LUmbw0ryG/6ts1oSLeYrMw6C0xeaFAGc+Wq3hbfeRk582b55lrzf3UHJwWkD0Wp+6BQ3+BfXEXw6UCdHX4TVB0BoJi9Y1Cp59XbUWN8HW7lRjLli3zbINE+1hNiCRI1cGakIhT99ani/A6z1z1nDoUqNQfbO40kyqDfrCBwMg3E5rsCy+8sFlHR8dEnFzRTq/I8hQ9NFFOtGhXVOxgFeUqfknUK7Ctpjl1ANKJ/vmUkvrdwRZmWjpA4J9MTyja2toKY8TQa/ufxP/Whdd5c5cQJHIwfBsTvkKiaqd6/fRyOHKqavdL0H+V2sxmWvrQCAeKItfmQlNyDG/8SVwnetMHyxmA7lm0K2I7GFrlVBW/V6FPP9GqeU4V0Kt2+O2yhctUN6AJBEWD9ngMnessJxh5AfCoQe+8q+xQOYLuWbQrQh2MXP1XYh8S9DKC2sI1z6kCatW3/RCZ6Vj9fNPMqx2wQVNJQlcNEl/mGG5pv48bi7HxMVSOoHsW7QqPg5GlvnJtk6/B9+HMqYUfaXE6rampqWy4dVhgi8FfLprnBXEex+i/wCSkNiSNDSpUxxt7Ccj2nQQYAwUHc9yE3HEotuifDklnfFYMdGNC/lWCxotDf4PvB/jHZTs71c+f2n+ryqCPPcb5/pKdGrTvbH2MUjH4ByOLBDpON9YSFi5cuI1FOwFbbyTox5T6y+iwFL8CqvWvwVtolWgSv/N4sXbl5ZP3r8hRLT50d56KgYJDCYXVhYOhtqqReKDdZuGJtSQSOk8f67x581SspvH3lpoBe9Vefbg/lzveaXmnAf6tEDMNGRp3LnV3ch29o10lQIf+bOKZc+XnmMGARF2EK4vUwQiSw33n7ZlqDWwcaK9Ob29vd26vwj+OT8m3kKFxdd9tlILSJ1Wo8Y8RZT/YiKOY4le5P3SGZJAc7telg7FroL16Jc/n/a1cBBCxsSblwT8LOfofcCh4AQ4x1uoCXZtgVKnYDXLMUECnPSQD29VBcrhfVw7GHrVXb6WylGg0SvUZcrr+YPYuwWVfaE9ltmpA2Q6EQq2UY+yigzf2oqCH4v4MIysD94fdwdig9uqDnB4T5/d+gwHPGNVFcOopyJiPLOfmGTwa0Ek8qS8RKDKORLFWH95utwbDd94SRqqN/Cv4PDXbTFfXfUZWBvRUPJCRBJiIqfnnccy0Dz74wHkWoypY2D4ZGU8gK+kKjQKQ8RcTW1uQI2fmc7nH7LIMFEW+sw6xdyN4CgvNByNIDjp+ZyRVhzlV7dVLaZc7t1cRoW0w9of/No6ptbuRdZupqC3QPZY33HchMkbJiRPssgyaHkN82XaJXPtOJuN+JRuixQI6Cu1VXiZtJehcFGpeNPyXI6cqPWTIvsxU1R7o912akevre4OHfTHot3fEfRbD3y8+Qu0djO5Ce5UXNGl7dTt4z0RGqnOuhgLZgmcPk2FHrrd3jgwkAVQ58e1ioxjcHeMLPWQcq+5gZKm9+hJHjXo5z4xQBQsxxyDjEfir+nNq5GfQo/nYh6f9e4NUgGEFx3DEzvw1nPrOhSJ+kh6GUBUHw6//Kmls96dJ2qv6FxNF9z8g405kVLVXDfkaiFAd4JIkttYUGFpyDOf91Ch/YVEe8DA/gORpuywDfLNMjBOQt4qEupbTPTX4YeJig+/qrnoxkfMeIdH2UHGBfP0H6kFepElc1rY5lBQYXZbzuO7BWYH7b3V3d/+TX1FEG/JSExEJdOi7qsnrx3DuNM8Zdg2NqnN/BjK0EXlVhxORr56wP6Lv/DT+X1FzYLynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC"; imgBack.style.position = "absolute"; imgBack.style.left = "50%"; imgBack.style.top = "50%"; imgBack.style.marginLeft = "-60px"; imgBack.style.marginTop = "-60px"; imgBack.style.animation = "spin1 2s infinite ease-in-out"; imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out"; imgBack.style.transformOrigin = "50% 50%"; imgBack.style.webkitTransformOrigin = "50% 50%"; this._loadingDiv.appendChild(imgBack); this._resizeLoadingUI(); window.addEventListener("resize", this._resizeLoadingUI); this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor; document.body.appendChild(this._loadingDiv); this._loadingDiv.style.opacity = "1"; }; /** * Function called to hide the loading screen */ DefaultLoadingScreen.prototype.hideLoadingUI = function () { var _this = this; if (!this._loadingDiv) { return; } var onTransitionEnd = function () { if (!_this._loadingDiv) { return; } if (_this._loadingDiv.parentElement) { _this._loadingDiv.parentElement.removeChild(_this._loadingDiv); } window.removeEventListener("resize", _this._resizeLoadingUI); _this._loadingDiv = null; }; this._loadingDiv.style.opacity = "0"; this._loadingDiv.addEventListener("transitionend", onTransitionEnd); }; Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", { get: function () { return this._loadingText; }, /** * Gets or sets the text to display while loading */ set: function (text) { this._loadingText = text; if (this._loadingTextDiv) { this._loadingTextDiv.innerHTML = this._loadingText; } }, enumerable: true, configurable: true }); Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", { /** * Gets or sets the color to use for the background */ get: function () { return this._loadingDivBackgroundColor; }, set: function (color) { this._loadingDivBackgroundColor = color; if (!this._loadingDiv) { return; } this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor; }, enumerable: true, configurable: true }); return DefaultLoadingScreen; }()); _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].DefaultLoadingScreenFactory = function (canvas) { return new DefaultLoadingScreen(canvas); }; /***/ }), /***/ "./Loading/sceneLoader.ts": /*!********************************!*\ !*** ./Loading/sceneLoader.ts ***! \********************************/ /*! exports provided: SceneLoaderProgressEvent, SceneLoader */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SceneLoaderProgressEvent", function() { return SceneLoaderProgressEvent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SceneLoader", function() { return SceneLoader; }); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Misc_filesInputStore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/filesInputStore */ "./Misc/filesInputStore.ts"); /* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../scene */ "./scene.ts"); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); /* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); /* harmony import */ var _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./sceneLoaderFlags */ "./Loading/sceneLoaderFlags.ts"); /** * Class used to represent data loading progression */ var SceneLoaderProgressEvent = /** @class */ (function () { /** * Create a new progress event * @param lengthComputable defines if data length to load can be evaluated * @param loaded defines the loaded data length * @param total defines the data length to load */ function SceneLoaderProgressEvent( /** defines if data length to load can be evaluated */ lengthComputable, /** defines the loaded data length */ loaded, /** defines the data length to load */ total) { this.lengthComputable = lengthComputable; this.loaded = loaded; this.total = total; } /** * Creates a new SceneLoaderProgressEvent from a ProgressEvent * @param event defines the source event * @returns a new SceneLoaderProgressEvent */ SceneLoaderProgressEvent.FromProgressEvent = function (event) { return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total); }; return SceneLoaderProgressEvent; }()); /** * Class used to load scene from various file formats using registered plugins * @see http://doc.babylonjs.com/how_to/load_from_any_file_type */ var SceneLoader = /** @class */ (function () { function SceneLoader() { } Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", { /** * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data */ get: function () { return _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__["SceneLoaderFlags"].ForceFullSceneLoadingForIncremental; }, set: function (value) { _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__["SceneLoaderFlags"].ForceFullSceneLoadingForIncremental = value; }, enumerable: true, configurable: true }); Object.defineProperty(SceneLoader, "ShowLoadingScreen", { /** * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene */ get: function () { return _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__["SceneLoaderFlags"].ShowLoadingScreen; }, set: function (value) { _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__["SceneLoaderFlags"].ShowLoadingScreen = value; }, enumerable: true, configurable: true }); Object.defineProperty(SceneLoader, "loggingLevel", { /** * Defines the current logging level (while loading the scene) * @ignorenaming */ get: function () { return _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__["SceneLoaderFlags"].loggingLevel; }, set: function (value) { _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__["SceneLoaderFlags"].loggingLevel = value; }, enumerable: true, configurable: true }); Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", { /** * Gets or set a boolean indicating if matrix weights must be cleaned upon loading */ get: function () { return _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__["SceneLoaderFlags"].CleanBoneMatrixWeights; }, set: function (value) { _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__["SceneLoaderFlags"].CleanBoneMatrixWeights = value; }, enumerable: true, configurable: true }); SceneLoader._getDefaultPlugin = function () { return SceneLoader._registeredPlugins[".babylon"]; }; SceneLoader._getPluginForExtension = function (extension) { var registeredPlugin = SceneLoader._registeredPlugins[extension]; if (registeredPlugin) { return registeredPlugin; } _Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type"); return SceneLoader._getDefaultPlugin(); }; SceneLoader._getPluginForDirectLoad = function (data) { for (var extension in SceneLoader._registeredPlugins) { var plugin = SceneLoader._registeredPlugins[extension].plugin; if (plugin.canDirectLoad && plugin.canDirectLoad(data)) { return SceneLoader._registeredPlugins[extension]; } } return SceneLoader._getDefaultPlugin(); }; SceneLoader._getPluginForFilename = function (sceneFilename) { var queryStringPosition = sceneFilename.indexOf("?"); if (queryStringPosition !== -1) { sceneFilename = sceneFilename.substring(0, queryStringPosition); } var dotPosition = sceneFilename.lastIndexOf("."); var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase(); return SceneLoader._getPluginForExtension(extension); }; // use babylon file loader directly if sceneFilename is prefixed with "data:" SceneLoader._getDirectLoad = function (sceneFilename) { if (sceneFilename.substr(0, 5) === "data:") { return sceneFilename.substr(5); } return null; }; SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) { var directLoad = SceneLoader._getDirectLoad(fileInfo.name); var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name)); var plugin; if (registeredPlugin.plugin.createPlugin) { plugin = registeredPlugin.plugin.createPlugin(); } else { plugin = registeredPlugin.plugin; } if (!plugin) { throw "The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before."; } var useArrayBuffer = registeredPlugin.isBinary; var offlineProvider; SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin); var dataCallback = function (data, responseURL) { if (scene.isDisposed) { onError("Scene has been disposed"); return; } scene.offlineProvider = offlineProvider; onSuccess(plugin, data, responseURL); }; var request = null; var pluginDisposed = false; var onDisposeObservable = plugin.onDisposeObservable; if (onDisposeObservable) { onDisposeObservable.add(function () { pluginDisposed = true; if (request) { request.abort(); request = null; } onDispose(); }); } var manifestChecked = function () { if (pluginDisposed) { return; } request = _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) { onProgress(SceneLoaderProgressEvent.FromProgressEvent(event)); } : undefined, offlineProvider, useArrayBuffer, function (request, exception) { onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception); }); }; if (directLoad) { dataCallback(directLoad); return plugin; } var file = fileInfo.file || _Misc_filesInputStore__WEBPACK_IMPORTED_MODULE_2__["FilesInputStore"].FilesToLoad[fileInfo.name.toLowerCase()]; if (fileInfo.rootUrl.indexOf("file:") === -1 || (fileInfo.rootUrl.indexOf("file:") !== -1 && !file)) { var engine = scene.getEngine(); var canUseOfflineSupport = engine.enableOfflineSupport; if (canUseOfflineSupport) { // Also check for exceptions var exceptionFound = false; for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) { var regex = _a[_i]; if (regex.test(fileInfo.url)) { exceptionFound = true; break; } } canUseOfflineSupport = !exceptionFound; } if (canUseOfflineSupport && _Engines_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].OfflineProviderFactory) { // Checking if a manifest file has been set for this scene and if offline mode has been requested offlineProvider = _Engines_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].OfflineProviderFactory(fileInfo.url, manifestChecked, engine.disableManifestCheck); } else { manifestChecked(); } } // Loading file from disk via input file or drag'n'drop else { if (file) { request = _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].ReadFile(file, dataCallback, onProgress, useArrayBuffer); } else { onError("Unable to find file named " + fileInfo.name); } } return plugin; }; SceneLoader._getFileInfo = function (rootUrl, sceneFilename) { var url; var name; var file = null; if (!sceneFilename) { url = rootUrl; name = _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].GetFilename(rootUrl); rootUrl = _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].GetFolderPath(rootUrl); } else if (sceneFilename.name) { var sceneFile = sceneFilename; url = rootUrl + sceneFile.name; name = sceneFile.name; file = sceneFile; } else { var filename = sceneFilename; if (filename.substr(0, 1) === "/") { _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error("Wrong sceneFilename parameter"); return null; } url = rootUrl + filename; name = filename; } return { url: url, rootUrl: rootUrl, name: name, file: file }; }; // Public functions /** * Gets a plugin that can load the given extension * @param extension defines the extension to load * @returns a plugin or null if none works */ SceneLoader.GetPluginForExtension = function (extension) { return SceneLoader._getPluginForExtension(extension).plugin; }; /** * Gets a boolean indicating that the given extension can be loaded * @param extension defines the extension to load * @returns true if the extension is supported */ SceneLoader.IsPluginForExtensionAvailable = function (extension) { return !!SceneLoader._registeredPlugins[extension]; }; /** * Adds a new plugin to the list of registered plugins * @param plugin defines the plugin to add */ SceneLoader.RegisterPlugin = function (plugin) { if (typeof plugin.extensions === "string") { var extension = plugin.extensions; SceneLoader._registeredPlugins[extension.toLowerCase()] = { plugin: plugin, isBinary: false }; } else { var extensions = plugin.extensions; Object.keys(extensions).forEach(function (extension) { SceneLoader._registeredPlugins[extension.toLowerCase()] = { plugin: plugin, isBinary: extensions[extension].isBinary }; }); } }; /** * Import meshes into a scene * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string) * @param scene the instance of BABYLON.Scene to append to * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds * @param onProgress a callback with a progress event for each file being loaded * @param onError a callback with the scene, a message, and possibly an exception when import fails * @param pluginExtension the extension used to determine the plugin * @returns The loaded plugin */ SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) { if (sceneFilename === void 0) { sceneFilename = ""; } if (scene === void 0) { scene = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; } if (onSuccess === void 0) { onSuccess = null; } if (onProgress === void 0) { onProgress = null; } if (onError === void 0) { onError = null; } if (pluginExtension === void 0) { pluginExtension = null; } if (!scene) { _Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Error("No scene available to import mesh to"); return null; } var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename); if (!fileInfo) { return null; } var loadingToken = {}; scene._addPendingData(loadingToken); var disposeHandler = function () { scene._removePendingData(loadingToken); }; var errorHandler = function (message, exception) { var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message; if (onError) { onError(scene, errorMessage, exception); } else { _Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Error(errorMessage); // should the exception be thrown? } disposeHandler(); }; var progressHandler = onProgress ? function (event) { try { onProgress(event); } catch (e) { errorHandler("Error in onProgress callback", e); } } : undefined; var successHandler = function (meshes, particleSystems, skeletons, animationGroups) { scene.importedMeshesFiles.push(fileInfo.url); if (onSuccess) { try { onSuccess(meshes, particleSystems, skeletons, animationGroups); } catch (e) { errorHandler("Error in onSuccess callback", e); } } scene._removePendingData(loadingToken); }; return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) { if (plugin.rewriteRootURL) { fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL); } if (plugin.importMesh) { var syncedPlugin = plugin; var meshes = new Array(); var particleSystems = new Array(); var skeletons = new Array(); if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) { return; } scene.loadingPluginName = plugin.name; successHandler(meshes, particleSystems, skeletons, []); } else { var asyncedPlugin = plugin; asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) { scene.loadingPluginName = plugin.name; successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups); }).catch(function (error) { errorHandler(error.message, error); }); } }, progressHandler, errorHandler, disposeHandler, pluginExtension); }; /** * Import meshes into a scene * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string) * @param scene the instance of BABYLON.Scene to append to * @param onProgress a callback with a progress event for each file being loaded * @param pluginExtension the extension used to determine the plugin * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups */ SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) { if (sceneFilename === void 0) { sceneFilename = ""; } if (scene === void 0) { scene = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; } if (onProgress === void 0) { onProgress = null; } if (pluginExtension === void 0) { pluginExtension = null; } return new Promise(function (resolve, reject) { SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) { resolve({ meshes: meshes, particleSystems: particleSystems, skeletons: skeletons, animationGroups: animationGroups }); }, onProgress, function (scene, message, exception) { reject(exception || new Error(message)); }, pluginExtension); }); }; /** * Load a scene * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string) * @param engine is the instance of BABYLON.Engine to use to create the scene * @param onSuccess a callback with the scene when import succeeds * @param onProgress a callback with a progress event for each file being loaded * @param onError a callback with the scene, a message, and possibly an exception when import fails * @param pluginExtension the extension used to determine the plugin * @returns The loaded plugin */ SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) { if (sceneFilename === void 0) { sceneFilename = ""; } if (engine === void 0) { engine = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedEngine; } if (onSuccess === void 0) { onSuccess = null; } if (onProgress === void 0) { onProgress = null; } if (onError === void 0) { onError = null; } if (pluginExtension === void 0) { pluginExtension = null; } if (!engine) { _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error("No engine available"); return null; } return SceneLoader.Append(rootUrl, sceneFilename, new _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"](engine), onSuccess, onProgress, onError, pluginExtension); }; /** * Load a scene * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string) * @param engine is the instance of BABYLON.Engine to use to create the scene * @param onProgress a callback with a progress event for each file being loaded * @param pluginExtension the extension used to determine the plugin * @returns The loaded scene */ SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) { if (sceneFilename === void 0) { sceneFilename = ""; } if (engine === void 0) { engine = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedEngine; } if (onProgress === void 0) { onProgress = null; } if (pluginExtension === void 0) { pluginExtension = null; } return new Promise(function (resolve, reject) { SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) { resolve(scene); }, onProgress, function (scene, message, exception) { reject(exception || new Error(message)); }, pluginExtension); }); }; /** * Append a scene * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string) * @param scene is the instance of BABYLON.Scene to append to * @param onSuccess a callback with the scene when import succeeds * @param onProgress a callback with a progress event for each file being loaded * @param onError a callback with the scene, a message, and possibly an exception when import fails * @param pluginExtension the extension used to determine the plugin * @returns The loaded plugin */ SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) { if (sceneFilename === void 0) { sceneFilename = ""; } if (scene === void 0) { scene = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; } if (onSuccess === void 0) { onSuccess = null; } if (onProgress === void 0) { onProgress = null; } if (onError === void 0) { onError = null; } if (pluginExtension === void 0) { pluginExtension = null; } if (!scene) { _Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Error("No scene available to append to"); return null; } var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename); if (!fileInfo) { return null; } if (SceneLoader.ShowLoadingScreen) { scene.getEngine().displayLoadingUI(); } var loadingToken = {}; scene._addPendingData(loadingToken); var disposeHandler = function () { scene._removePendingData(loadingToken); scene.getEngine().hideLoadingUI(); }; var errorHandler = function (message, exception) { var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : ""); if (onError) { onError(scene, errorMessage, exception); } else { _Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Error(errorMessage); // should the exception be thrown? } disposeHandler(); }; var progressHandler = onProgress ? function (event) { try { onProgress(event); } catch (e) { errorHandler("Error in onProgress callback", e); } } : undefined; var successHandler = function () { if (onSuccess) { try { onSuccess(scene); } catch (e) { errorHandler("Error in onSuccess callback", e); } } scene._removePendingData(loadingToken); }; return SceneLoader._loadData(fileInfo, scene, function (plugin, data) { if (plugin.load) { var syncedPlugin = plugin; if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) { return; } scene.loadingPluginName = plugin.name; successHandler(); } else { var asyncedPlugin = plugin; asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () { scene.loadingPluginName = plugin.name; successHandler(); }).catch(function (error) { errorHandler(error.message, error); }); } if (SceneLoader.ShowLoadingScreen) { scene.executeWhenReady(function () { scene.getEngine().hideLoadingUI(); }); } }, progressHandler, errorHandler, disposeHandler, pluginExtension); }; /** * Append a scene * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string) * @param scene is the instance of BABYLON.Scene to append to * @param onProgress a callback with a progress event for each file being loaded * @param pluginExtension the extension used to determine the plugin * @returns The given scene */ SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) { if (sceneFilename === void 0) { sceneFilename = ""; } if (scene === void 0) { scene = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; } if (onProgress === void 0) { onProgress = null; } if (pluginExtension === void 0) { pluginExtension = null; } return new Promise(function (resolve, reject) { SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) { resolve(scene); }, onProgress, function (scene, message, exception) { reject(exception || new Error(message)); }, pluginExtension); }); }; /** * Load a scene into an asset container * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string) * @param scene is the instance of BABYLON.Scene to append to (default: last created scene) * @param onSuccess a callback with the scene when import succeeds * @param onProgress a callback with a progress event for each file being loaded * @param onError a callback with the scene, a message, and possibly an exception when import fails * @param pluginExtension the extension used to determine the plugin * @returns The loaded plugin */ SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) { if (sceneFilename === void 0) { sceneFilename = ""; } if (scene === void 0) { scene = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; } if (onSuccess === void 0) { onSuccess = null; } if (onProgress === void 0) { onProgress = null; } if (onError === void 0) { onError = null; } if (pluginExtension === void 0) { pluginExtension = null; } if (!scene) { _Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Error("No scene available to load asset container to"); return null; } var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename); if (!fileInfo) { return null; } var loadingToken = {}; scene._addPendingData(loadingToken); var disposeHandler = function () { scene._removePendingData(loadingToken); }; var errorHandler = function (message, exception) { var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : ""); if (onError) { onError(scene, errorMessage, exception); } else { _Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Error(errorMessage); // should the exception be thrown? } disposeHandler(); }; var progressHandler = onProgress ? function (event) { try { onProgress(event); } catch (e) { errorHandler("Error in onProgress callback", e); } } : undefined; var successHandler = function (assets) { if (onSuccess) { try { onSuccess(assets); } catch (e) { errorHandler("Error in onSuccess callback", e); } } scene._removePendingData(loadingToken); }; return SceneLoader._loadData(fileInfo, scene, function (plugin, data) { if (plugin.loadAssetContainer) { var syncedPlugin = plugin; var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler); if (!assetContainer) { return; } scene.loadingPluginName = plugin.name; successHandler(assetContainer); } else if (plugin.loadAssetContainerAsync) { var asyncedPlugin = plugin; asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) { scene.loadingPluginName = plugin.name; successHandler(assetContainer); }).catch(function (error) { errorHandler(error.message, error); }); } else { errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method."); } if (SceneLoader.ShowLoadingScreen) { scene.executeWhenReady(function () { scene.getEngine().hideLoadingUI(); }); } }, progressHandler, errorHandler, disposeHandler, pluginExtension); }; /** * Load a scene into an asset container * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb) * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string) * @param scene is the instance of Scene to append to * @param onProgress a callback with a progress event for each file being loaded * @param pluginExtension the extension used to determine the plugin * @returns The loaded asset container */ SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) { if (sceneFilename === void 0) { sceneFilename = ""; } if (scene === void 0) { scene = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; } if (onProgress === void 0) { onProgress = null; } if (pluginExtension === void 0) { pluginExtension = null; } return new Promise(function (resolve, reject) { SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) { resolve(assetContainer); }, onProgress, function (scene, message, exception) { reject(exception || new Error(message)); }, pluginExtension); }); }; /** * No logging while loading */ SceneLoader.NO_LOGGING = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].SCENELOADER_NO_LOGGING; /** * Minimal logging while loading */ SceneLoader.MINIMAL_LOGGING = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].SCENELOADER_MINIMAL_LOGGING; /** * Summary logging while loading */ SceneLoader.SUMMARY_LOGGING = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].SCENELOADER_SUMMARY_LOGGING; /** * Detailled logging while loading */ SceneLoader.DETAILED_LOGGING = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].SCENELOADER_DETAILED_LOGGING; // Members /** * Event raised when a plugin is used to load a scene */ SceneLoader.OnPluginActivatedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); SceneLoader._registeredPlugins = {}; return SceneLoader; }()); /***/ }), /***/ "./Loading/sceneLoaderFlags.ts": /*!*************************************!*\ !*** ./Loading/sceneLoaderFlags.ts ***! \*************************************/ /*! exports provided: SceneLoaderFlags */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SceneLoaderFlags", function() { return SceneLoaderFlags; }); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); /** * Class used to represent data loading progression */ var SceneLoaderFlags = /** @class */ (function () { function SceneLoaderFlags() { } Object.defineProperty(SceneLoaderFlags, "ForceFullSceneLoadingForIncremental", { /** * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data */ get: function () { return SceneLoaderFlags._ForceFullSceneLoadingForIncremental; }, set: function (value) { SceneLoaderFlags._ForceFullSceneLoadingForIncremental = value; }, enumerable: true, configurable: true }); Object.defineProperty(SceneLoaderFlags, "ShowLoadingScreen", { /** * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene */ get: function () { return SceneLoaderFlags._ShowLoadingScreen; }, set: function (value) { SceneLoaderFlags._ShowLoadingScreen = value; }, enumerable: true, configurable: true }); Object.defineProperty(SceneLoaderFlags, "loggingLevel", { /** * Defines the current logging level (while loading the scene) * @ignorenaming */ get: function () { return SceneLoaderFlags._loggingLevel; }, set: function (value) { SceneLoaderFlags._loggingLevel = value; }, enumerable: true, configurable: true }); Object.defineProperty(SceneLoaderFlags, "CleanBoneMatrixWeights", { /** * Gets or set a boolean indicating if matrix weights must be cleaned upon loading */ get: function () { return SceneLoaderFlags._CleanBoneMatrixWeights; }, set: function (value) { SceneLoaderFlags._CleanBoneMatrixWeights = value; }, enumerable: true, configurable: true }); // Flags SceneLoaderFlags._ForceFullSceneLoadingForIncremental = false; SceneLoaderFlags._ShowLoadingScreen = true; SceneLoaderFlags._CleanBoneMatrixWeights = false; SceneLoaderFlags._loggingLevel = _Engines_constants__WEBPACK_IMPORTED_MODULE_0__["Constants"].SCENELOADER_NO_LOGGING; return SceneLoaderFlags; }()); /***/ }), /***/ "./Materials/Background/backgroundMaterial.ts": /*!****************************************************!*\ !*** ./Materials/Background/backgroundMaterial.ts ***! \****************************************************/ /*! exports provided: BackgroundMaterial */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BackgroundMaterial", function() { return BackgroundMaterial; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Misc_smartArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/smartArray */ "./Misc/smartArray.ts"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Meshes/buffer */ "./Meshes/buffer.ts"); /* harmony import */ var _Materials_effect__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Materials/effect */ "./Materials/effect.ts"); /* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Materials/materialHelper */ "./Materials/materialHelper.ts"); /* harmony import */ var _Materials_materialDefines__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../Materials/materialDefines */ "./Materials/materialDefines.ts"); /* harmony import */ var _Materials_pushMaterial__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../Materials/pushMaterial */ "./Materials/pushMaterial.ts"); /* harmony import */ var _Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../Materials/imageProcessingConfiguration */ "./Materials/imageProcessingConfiguration.ts"); /* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts"); /* harmony import */ var _materialFlags__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../materialFlags */ "./Materials/materialFlags.ts"); /* harmony import */ var _Shaders_background_fragment__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../../Shaders/background.fragment */ "./Shaders/background.fragment.ts"); /* harmony import */ var _Shaders_background_vertex__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../../Shaders/background.vertex */ "./Shaders/background.vertex.ts"); /** * Background material defines definition. * @hidden Mainly internal Use */ var BackgroundMaterialDefines = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BackgroundMaterialDefines, _super); /** * Constructor of the defines. */ function BackgroundMaterialDefines() { var _this = _super.call(this) || this; /** * True if the diffuse texture is in use. */ _this.DIFFUSE = false; /** * The direct UV channel to use. */ _this.DIFFUSEDIRECTUV = 0; /** * True if the diffuse texture is in gamma space. */ _this.GAMMADIFFUSE = false; /** * True if the diffuse texture has opacity in the alpha channel. */ _this.DIFFUSEHASALPHA = false; /** * True if you want the material to fade to transparent at grazing angle. */ _this.OPACITYFRESNEL = false; /** * True if an extra blur needs to be added in the reflection. */ _this.REFLECTIONBLUR = false; /** * True if you want the material to fade to reflection at grazing angle. */ _this.REFLECTIONFRESNEL = false; /** * True if you want the material to falloff as far as you move away from the scene center. */ _this.REFLECTIONFALLOFF = false; /** * False if the current Webgl implementation does not support the texture lod extension. */ _this.TEXTURELODSUPPORT = false; /** * True to ensure the data are premultiplied. */ _this.PREMULTIPLYALPHA = false; /** * True if the texture contains cooked RGB values and not gray scaled multipliers. */ _this.USERGBCOLOR = false; /** * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color * stays aligned with the desired configuration. */ _this.USEHIGHLIGHTANDSHADOWCOLORS = false; /** * True to add noise in order to reduce the banding effect. */ _this.NOISE = false; /** * is the reflection texture in BGR color scheme? * Mainly used to solve a bug in ios10 video tag */ _this.REFLECTIONBGR = false; _this.IMAGEPROCESSING = false; _this.VIGNETTE = false; _this.VIGNETTEBLENDMODEMULTIPLY = false; _this.VIGNETTEBLENDMODEOPAQUE = false; _this.TONEMAPPING = false; _this.TONEMAPPING_ACES = false; _this.CONTRAST = false; _this.COLORCURVES = false; _this.COLORGRADING = false; _this.COLORGRADING3D = false; _this.SAMPLER3DGREENDEPTH = false; _this.SAMPLER3DBGRMAP = false; _this.IMAGEPROCESSINGPOSTPROCESS = false; _this.EXPOSURE = false; _this.MULTIVIEW = false; // Reflection. _this.REFLECTION = false; _this.REFLECTIONMAP_3D = false; _this.REFLECTIONMAP_SPHERICAL = false; _this.REFLECTIONMAP_PLANAR = false; _this.REFLECTIONMAP_CUBIC = false; _this.REFLECTIONMAP_PROJECTION = false; _this.REFLECTIONMAP_SKYBOX = false; _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false; _this.REFLECTIONMAP_EXPLICIT = false; _this.REFLECTIONMAP_EQUIRECTANGULAR = false; _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false; _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false; _this.INVERTCUBICMAP = false; _this.REFLECTIONMAP_OPPOSITEZ = false; _this.LODINREFLECTIONALPHA = false; _this.GAMMAREFLECTION = false; _this.RGBDREFLECTION = false; _this.EQUIRECTANGULAR_RELFECTION_FOV = false; // Default BJS. _this.MAINUV1 = false; _this.MAINUV2 = false; _this.UV1 = false; _this.UV2 = false; _this.CLIPPLANE = false; _this.CLIPPLANE2 = false; _this.CLIPPLANE3 = false; _this.CLIPPLANE4 = false; _this.POINTSIZE = false; _this.FOG = false; _this.NORMAL = false; _this.NUM_BONE_INFLUENCERS = 0; _this.BonesPerMesh = 0; _this.INSTANCES = false; _this.SHADOWFLOAT = false; _this.rebuild(); return _this; } return BackgroundMaterialDefines; }(_Materials_materialDefines__WEBPACK_IMPORTED_MODULE_8__["MaterialDefines"])); /** * Background material used to create an efficient environement around your scene. */ var BackgroundMaterial = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](BackgroundMaterial, _super); /** * Instantiates a Background Material in the given scene * @param name The friendly name of the material * @param scene The scene to add the material to */ function BackgroundMaterial(name, scene) { var _this = _super.call(this, name, scene) || this; /** * Key light Color (multiply against the environement texture) */ _this.primaryColor = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Color3"].White(); _this._primaryColorShadowLevel = 0; _this._primaryColorHighlightLevel = 0; /** * Reflection Texture used in the material. * Should be author in a specific way for the best result (refer to the documentation). */ _this.reflectionTexture = null; /** * Reflection Texture level of blur. * * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the * texture twice. */ _this.reflectionBlur = 0; /** * Diffuse Texture used in the material. * Should be author in a specific way for the best result (refer to the documentation). */ _this.diffuseTexture = null; _this._shadowLights = null; /** * Specify the list of lights casting shadow on the material. * All scene shadow lights will be included if null. */ _this.shadowLights = null; /** * Helps adjusting the shadow to a softer level if required. * 0 means black shadows and 1 means no shadows. */ _this.shadowLevel = 0; /** * In case of opacity Fresnel or reflection falloff, this is use as a scene center. * It is usually zero but might be interesting to modify according to your setup. */ _this.sceneCenter = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(); /** * This helps specifying that the material is falling off to the sky box at grazing angle. * This helps ensuring a nice transition when the camera goes under the ground. */ _this.opacityFresnel = true; /** * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle. * This helps adding a mirror texture on the ground. */ _this.reflectionFresnel = false; /** * This helps specifying the falloff radius off the reflection texture from the sceneCenter. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance. */ _this.reflectionFalloffDistance = 0.0; /** * This specifies the weight of the reflection against the background in case of reflection Fresnel. */ _this.reflectionAmount = 1.0; /** * This specifies the weight of the reflection at grazing angle. */ _this.reflectionReflectance0 = 0.05; /** * This specifies the weight of the reflection at a perpendicular point of view. */ _this.reflectionReflectance90 = 0.5; /** * Helps to directly use the maps channels instead of their level. */ _this.useRGBColor = true; /** * This helps reducing the banding effect that could occur on the background. */ _this.enableNoise = false; _this._fovMultiplier = 1.0; /** * Enable the FOV adjustment feature controlled by fovMultiplier. */ _this.useEquirectangularFOV = false; _this._maxSimultaneousLights = 4; /** * Number of Simultaneous lights allowed on the material. */ _this.maxSimultaneousLights = 4; /** * Keep track of the image processing observer to allow dispose and replace. */ _this._imageProcessingObserver = null; /** * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB. * Setting this flag to true (not done automatically!) will convert it back to RGB. */ _this.switchToBGR = false; // Temp values kept as cache in the material. _this._renderTargets = new _Misc_smartArray__WEBPACK_IMPORTED_MODULE_2__["SmartArray"](16); _this._reflectionControls = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector4"].Zero(); _this._white = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Color3"].White(); _this._primaryShadowColor = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Color3"].Black(); _this._primaryHighlightColor = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Color3"].Black(); // Setup the default processing configuration to the scene. _this._attachImageProcessingConfiguration(null); _this.getRenderTargetTextures = function () { _this._renderTargets.reset(); if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) { _this._renderTargets.push(_this._diffuseTexture); } if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) { _this._renderTargets.push(_this._reflectionTexture); } return _this._renderTargets; }; return _this; } Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", { /** * Experimental Internal Use Only. * * Key light Color in "perceptual value" meaning the color you would like to see on screen. * This acts as a helper to set the primary color to a more "human friendly" value. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the * output color as close as possible from the chosen value. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly * part of lighting setup.) */ get: function () { return this.__perceptualColor; }, set: function (value) { this.__perceptualColor = value; this._computePrimaryColorFromPerceptualColor(); this._markAllSubMeshesAsLightsDirty(); }, enumerable: true, configurable: true }); Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", { /** * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors. * The color opposite to the primary color is used at the level chosen to define what the black area would look. */ get: function () { return this._primaryColorShadowLevel; }, set: function (value) { this._primaryColorShadowLevel = value; this._computePrimaryColors(); this._markAllSubMeshesAsLightsDirty(); }, enumerable: true, configurable: true }); Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", { /** * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors. * The primary color is used at the level chosen to define what the white area would look. */ get: function () { return this._primaryColorHighlightLevel; }, set: function (value) { this._primaryColorHighlightLevel = value; this._computePrimaryColors(); this._markAllSubMeshesAsLightsDirty(); }, enumerable: true, configurable: true }); Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", { /** * Sets the reflection reflectance fresnel values according to the default standard * empirically know to work well :-) */ set: function (value) { var reflectionWeight = value; if (reflectionWeight < 0.5) { reflectionWeight = reflectionWeight * 2.0; this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight; this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight; } else { reflectionWeight = reflectionWeight * 2.0 - 1.0; this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight; this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight; } }, enumerable: true, configurable: true }); Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", { /** * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out". * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov. * Recommended to be keep at 1.0 except for special cases. */ get: function () { return this._fovMultiplier; }, set: function (value) { if (isNaN(value)) { value = 1.0; } this._fovMultiplier = Math.max(0.0, Math.min(2.0, value)); }, enumerable: true, configurable: true }); /** * Attaches a new image processing configuration to the PBR Material. * @param configuration (if null the scene configuration will be use) */ BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) { var _this = this; if (configuration === this._imageProcessingConfiguration) { return; } // Detaches observer. if (this._imageProcessingConfiguration && this._imageProcessingObserver) { this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); } // Pick the scene configuration if needed. if (!configuration) { this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration; } else { this._imageProcessingConfiguration = configuration; } // Attaches observer. if (this._imageProcessingConfiguration) { this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function () { _this._computePrimaryColorFromPerceptualColor(); _this._markAllSubMeshesAsImageProcessingDirty(); }); } }; Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", { /** * Gets the image processing configuration used either in this material. */ get: function () { return this._imageProcessingConfiguration; }, /** * Sets the Default image processing configuration used either in the this material. * * If sets to null, the scene one is in use. */ set: function (value) { this._attachImageProcessingConfiguration(value); // Ensure the effect will be rebuilt. this._markAllSubMeshesAsTexturesDirty(); }, enumerable: true, configurable: true }); Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", { /** * Gets wether the color curves effect is enabled. */ get: function () { return this.imageProcessingConfiguration.colorCurvesEnabled; }, /** * Sets wether the color curves effect is enabled. */ set: function (value) { this.imageProcessingConfiguration.colorCurvesEnabled = value; }, enumerable: true, configurable: true }); Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", { /** * Gets wether the color grading effect is enabled. */ get: function () { return this.imageProcessingConfiguration.colorGradingEnabled; }, /** * Gets wether the color grading effect is enabled. */ set: function (value) { this.imageProcessingConfiguration.colorGradingEnabled = value; }, enumerable: true, configurable: true }); Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", { /** * Gets wether tonemapping is enabled or not. */ get: function () { return this._imageProcessingConfiguration.toneMappingEnabled; }, /** * Sets wether tonemapping is enabled or not */ set: function (value) { this._imageProcessingConfiguration.toneMappingEnabled = value; }, enumerable: true, configurable: true }); Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", { /** * The camera exposure used on this material. * This property is here and not in the camera to allow controlling exposure without full screen post process. * This corresponds to a photographic exposure. */ get: function () { return this._imageProcessingConfiguration.exposure; }, /** * The camera exposure used on this material. * This property is here and not in the camera to allow controlling exposure without full screen post process. * This corresponds to a photographic exposure. */ set: function (value) { this._imageProcessingConfiguration.exposure = value; }, enumerable: true, configurable: true }); Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", { /** * Gets The camera contrast used on this material. */ get: function () { return this._imageProcessingConfiguration.contrast; }, /** * Sets The camera contrast used on this material. */ set: function (value) { this._imageProcessingConfiguration.contrast = value; }, enumerable: true, configurable: true }); Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", { /** * Gets the Color Grading 2D Lookup Texture. */ get: function () { return this._imageProcessingConfiguration.colorGradingTexture; }, /** * Sets the Color Grading 2D Lookup Texture. */ set: function (value) { this.imageProcessingConfiguration.colorGradingTexture = value; }, enumerable: true, configurable: true }); Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", { /** * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; * corresponding to low luminance, medium luminance, and high luminance areas respectively. */ get: function () { return this.imageProcessingConfiguration.colorCurves; }, /** * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; * corresponding to low luminance, medium luminance, and high luminance areas respectively. */ set: function (value) { this.imageProcessingConfiguration.colorCurves = value; }, enumerable: true, configurable: true }); Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", { /** * Gets a boolean indicating that current material needs to register RTT */ get: function () { if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) { return true; } if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) { return true; } return false; }, enumerable: true, configurable: true }); /** * The entire material has been created in order to prevent overdraw. * @returns false */ BackgroundMaterial.prototype.needAlphaTesting = function () { return true; }; /** * The entire material has been created in order to prevent overdraw. * @returns true if blending is enable */ BackgroundMaterial.prototype.needAlphaBlending = function () { return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha)); }; /** * Checks wether the material is ready to be rendered for a given mesh. * @param mesh The mesh to render * @param subMesh The submesh to check against * @param useInstances Specify wether or not the material is used with instances * @returns true if all the dependencies are ready (Textures, Effects...) */ BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) { var _this = this; if (useInstances === void 0) { useInstances = false; } if (subMesh.effect && this.isFrozen) { if (this._wasPreviouslyReady) { return true; } } if (!subMesh._materialDefines) { subMesh._materialDefines = new BackgroundMaterialDefines(); } var scene = this.getScene(); var defines = subMesh._materialDefines; if (!this.checkReadyOnEveryCall && subMesh.effect) { if (defines._renderId === scene.getRenderId()) { return true; } } var engine = scene.getEngine(); // Lights _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights); defines._needNormals = true; // Multiview _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].PrepareDefinesForMultiview(scene, defines); // Textures if (defines._areTexturesDirty) { defines._needUVs = false; if (scene.texturesEnabled) { if (scene.getEngine().getCaps().textureLOD) { defines.TEXTURELODSUPPORT = true; } if (this._diffuseTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_14__["MaterialFlags"].DiffuseTextureEnabled) { if (!this._diffuseTexture.isReadyOrNotBlocking()) { return false; } _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE"); defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha; defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace; defines.OPACITYFRESNEL = this._opacityFresnel; } else { defines.DIFFUSE = false; defines.DIFFUSEHASALPHA = false; defines.GAMMADIFFUSE = false; defines.OPACITYFRESNEL = false; } var reflectionTexture = this._reflectionTexture; if (reflectionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_14__["MaterialFlags"].ReflectionTextureEnabled) { if (!reflectionTexture.isReadyOrNotBlocking()) { return false; } defines.REFLECTION = true; defines.GAMMAREFLECTION = reflectionTexture.gammaSpace; defines.RGBDREFLECTION = reflectionTexture.isRGBD; defines.REFLECTIONBLUR = this._reflectionBlur > 0; defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ; defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha; defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV; defines.REFLECTIONBGR = this.switchToBGR; if (reflectionTexture.coordinatesMode === _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_11__["Texture"].INVCUBIC_MODE) { defines.INVERTCUBICMAP = true; } defines.REFLECTIONMAP_3D = reflectionTexture.isCube; switch (reflectionTexture.coordinatesMode) { case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_11__["Texture"].EXPLICIT_MODE: defines.REFLECTIONMAP_EXPLICIT = true; break; case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_11__["Texture"].PLANAR_MODE: defines.REFLECTIONMAP_PLANAR = true; break; case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_11__["Texture"].PROJECTION_MODE: defines.REFLECTIONMAP_PROJECTION = true; break; case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_11__["Texture"].SKYBOX_MODE: defines.REFLECTIONMAP_SKYBOX = true; defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity(); break; case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_11__["Texture"].SPHERICAL_MODE: defines.REFLECTIONMAP_SPHERICAL = true; break; case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_11__["Texture"].EQUIRECTANGULAR_MODE: defines.REFLECTIONMAP_EQUIRECTANGULAR = true; break; case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_11__["Texture"].FIXED_EQUIRECTANGULAR_MODE: defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true; break; case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_11__["Texture"].FIXED_EQUIRECTANGULAR_MIRRORED_MODE: defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true; break; case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_11__["Texture"].CUBIC_MODE: case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_11__["Texture"].INVCUBIC_MODE: default: defines.REFLECTIONMAP_CUBIC = true; break; } if (this.reflectionFresnel) { defines.REFLECTIONFRESNEL = true; defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0; this._reflectionControls.x = this.reflectionAmount; this._reflectionControls.y = this.reflectionReflectance0; this._reflectionControls.z = this.reflectionReflectance90; this._reflectionControls.w = 1 / this.reflectionFalloffDistance; } else { defines.REFLECTIONFRESNEL = false; defines.REFLECTIONFALLOFF = false; } } else { defines.REFLECTION = false; defines.REFLECTIONFRESNEL = false; defines.REFLECTIONFALLOFF = false; defines.REFLECTIONBLUR = false; defines.REFLECTIONMAP_3D = false; defines.REFLECTIONMAP_SPHERICAL = false; defines.REFLECTIONMAP_PLANAR = false; defines.REFLECTIONMAP_CUBIC = false; defines.REFLECTIONMAP_PROJECTION = false; defines.REFLECTIONMAP_SKYBOX = false; defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false; defines.REFLECTIONMAP_EXPLICIT = false; defines.REFLECTIONMAP_EQUIRECTANGULAR = false; defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false; defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false; defines.INVERTCUBICMAP = false; defines.REFLECTIONMAP_OPPOSITEZ = false; defines.LODINREFLECTIONALPHA = false; defines.GAMMAREFLECTION = false; defines.RGBDREFLECTION = false; } } defines.PREMULTIPLYALPHA = (this.alphaMode === _Engines_constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].ALPHA_PREMULTIPLIED || this.alphaMode === _Engines_constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].ALPHA_PREMULTIPLIED_PORTERDUFF); defines.USERGBCOLOR = this._useRGBColor; defines.NOISE = this._enableNoise; } if (defines._areLightsDirty) { defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0); } if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) { if (!this._imageProcessingConfiguration.isReady()) { return false; } this._imageProcessingConfiguration.prepareDefines(defines); } // Misc. _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines); // Values that need to be evaluated on every frame _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances); // Attribs if (_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].PrepareDefinesForAttributes(mesh, defines, false, true, false)) { if (mesh) { if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].NormalKind)) { mesh.createNormals(true); _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name); } } } // Get correct effect if (defines.isDirty) { defines.markAsProcessed(); scene.resetCachedMaterial(); // Fallbacks var fallbacks = new _Materials_effect__WEBPACK_IMPORTED_MODULE_6__["EffectFallbacks"](); if (defines.FOG) { fallbacks.addFallback(0, "FOG"); } if (defines.POINTSIZE) { fallbacks.addFallback(1, "POINTSIZE"); } if (defines.MULTIVIEW) { fallbacks.addFallback(0, "MULTIVIEW"); } _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights); if (defines.NUM_BONE_INFLUENCERS > 0) { fallbacks.addCPUSkinningFallback(0, mesh); } //Attributes var attribs = [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].PositionKind]; if (defines.NORMAL) { attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].NormalKind); } if (defines.UV1) { attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].UVKind); } if (defines.UV2) { attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].UV2Kind); } _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].PrepareAttributesForBones(attribs, mesh, defines, fallbacks); _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].PrepareAttributesForInstances(attribs, defines); var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vFogInfos", "vFogColor", "pointSize", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones", "vPrimaryColor", "vPrimaryColorShadow", "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier", "shadowLevel", "alpha", "vBackgroundCenter", "vReflectionControl", "vDiffuseInfos", "diffuseMatrix", ]; var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"]; var uniformBuffers = ["Material", "Scene"]; if (_Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_10__["ImageProcessingConfiguration"]) { _Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_10__["ImageProcessingConfiguration"].PrepareUniforms(uniforms, defines); _Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_10__["ImageProcessingConfiguration"].PrepareSamplers(samplers, defines); } _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].PrepareUniformsAndSamplersList({ uniformsNames: uniforms, uniformBuffersNames: uniformBuffers, samplers: samplers, defines: defines, maxSimultaneousLights: this._maxSimultaneousLights }); var onCompiled = function (effect) { if (_this.onCompiled) { _this.onCompiled(effect); } _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer()); }; var join = defines.toString(); subMesh.setEffect(scene.getEngine().createEffect("background", { attributes: attribs, uniformsNames: uniforms, uniformBuffersNames: uniformBuffers, samplers: samplers, defines: join, fallbacks: fallbacks, onCompiled: onCompiled, onError: this.onError, indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights } }, engine), defines); this.buildUniformLayout(); } if (!subMesh.effect || !subMesh.effect.isReady()) { return false; } defines._renderId = scene.getRenderId(); this._wasPreviouslyReady = true; return true; }; /** * Compute the primary color according to the chosen perceptual color. */ BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () { if (!this.__perceptualColor) { return; } this._primaryColor.copyFrom(this.__perceptualColor); // Revert gamma space. this._primaryColor.toLinearSpaceToRef(this._primaryColor); // Revert image processing configuration. if (this._imageProcessingConfiguration) { // Revert Exposure. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor); } this._computePrimaryColors(); }; /** * Compute the highlights and shadow colors according to their chosen levels. */ BackgroundMaterial.prototype._computePrimaryColors = function () { if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) { return; } // Find the highlight color based on the configuration. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor); this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor); // Find the shadow color based on the configuration. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor); this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor); this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor); }; /** * Build the uniform buffer used in the material. */ BackgroundMaterial.prototype.buildUniformLayout = function () { // Order is important ! this._uniformBuffer.addUniform("vPrimaryColor", 4); this._uniformBuffer.addUniform("vPrimaryColorShadow", 4); this._uniformBuffer.addUniform("vDiffuseInfos", 2); this._uniformBuffer.addUniform("vReflectionInfos", 2); this._uniformBuffer.addUniform("diffuseMatrix", 16); this._uniformBuffer.addUniform("reflectionMatrix", 16); this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3); this._uniformBuffer.addUniform("fFovMultiplier", 1); this._uniformBuffer.addUniform("pointSize", 1); this._uniformBuffer.addUniform("shadowLevel", 1); this._uniformBuffer.addUniform("alpha", 1); this._uniformBuffer.addUniform("vBackgroundCenter", 3); this._uniformBuffer.addUniform("vReflectionControl", 4); this._uniformBuffer.create(); }; /** * Unbind the material. */ BackgroundMaterial.prototype.unbind = function () { if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) { this._uniformBuffer.setTexture("diffuseSampler", null); } if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) { this._uniformBuffer.setTexture("reflectionSampler", null); } _super.prototype.unbind.call(this); }; /** * Bind only the world matrix to the material. * @param world The world matrix to bind. */ BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) { this._activeEffect.setMatrix("world", world); }; /** * Bind the material for a dedicated submeh (every used meshes will be considered opaque). * @param world The world matrix to bind. * @param subMesh The submesh to bind for. */ BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) { var scene = this.getScene(); var defines = subMesh._materialDefines; if (!defines) { return; } var effect = subMesh.effect; if (!effect) { return; } this._activeEffect = effect; // Matrices this.bindOnlyWorldMatrix(world); // Bones _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].BindBonesParameters(mesh, this._activeEffect); var mustRebind = this._mustRebind(scene, effect, mesh.visibility); if (mustRebind) { this._uniformBuffer.bindToEffect(effect, "Material"); this.bindViewProjection(effect); var reflectionTexture = this._reflectionTexture; if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) { // Texture uniforms if (scene.texturesEnabled) { if (this._diffuseTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_14__["MaterialFlags"].DiffuseTextureEnabled) { this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level); _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse"); } if (reflectionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_14__["MaterialFlags"].ReflectionTextureEnabled) { this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix()); this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur); this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset); } } if (this.shadowLevel > 0) { this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel); } this._uniformBuffer.updateFloat("alpha", this.alpha); // Point size if (this.pointsCloud) { this._uniformBuffer.updateFloat("pointSize", this.pointSize); } if (defines.USEHIGHLIGHTANDSHADOWCOLORS) { this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0); this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0); } else { this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0); } } this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier); // Textures if (scene.texturesEnabled) { if (this._diffuseTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_14__["MaterialFlags"].DiffuseTextureEnabled) { this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture); } if (reflectionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_14__["MaterialFlags"].ReflectionTextureEnabled) { if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) { this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture); } else if (!defines.REFLECTIONBLUR) { this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture); } else { this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture); this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture); this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture); } if (defines.REFLECTIONFRESNEL) { this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z); this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w); } } } // Clip plane _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].BindClipPlane(this._activeEffect, scene); _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].BindEyePosition(effect, scene); } if (mustRebind || !this.isFrozen) { if (scene.lightsEnabled) { _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false); } // View this.bindView(effect); // Fog _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"].BindFogParameters(scene, mesh, this._activeEffect, true); // image processing if (this._imageProcessingConfiguration) { this._imageProcessingConfiguration.bind(this._activeEffect); } } this._uniformBuffer.update(); this._afterBind(mesh, this._activeEffect); }; /** * Dispose the material. * @param forceDisposeEffect Force disposal of the associated effect. * @param forceDisposeTextures Force disposal of the associated textures. */ BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) { if (forceDisposeEffect === void 0) { forceDisposeEffect = false; } if (forceDisposeTextures === void 0) { forceDisposeTextures = false; } if (forceDisposeTextures) { if (this.diffuseTexture) { this.diffuseTexture.dispose(); } if (this.reflectionTexture) { this.reflectionTexture.dispose(); } } this._renderTargets.dispose(); if (this._imageProcessingConfiguration && this._imageProcessingObserver) { this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); } _super.prototype.dispose.call(this, forceDisposeEffect); }; /** * Clones the material. * @param name The cloned name. * @returns The cloned material. */ BackgroundMaterial.prototype.clone = function (name) { var _this = this; return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this); }; /** * Serializes the current material to its JSON representation. * @returns The JSON representation. */ BackgroundMaterial.prototype.serialize = function () { var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); serializationObject.customType = "BABYLON.BackgroundMaterial"; return serializationObject; }; /** * Gets the class name of the material * @returns "BackgroundMaterial" */ BackgroundMaterial.prototype.getClassName = function () { return "BackgroundMaterial"; }; /** * Parse a JSON input to create back a background material. * @param source The JSON data to parse * @param scene The scene to create the parsed material in * @param rootUrl The root url of the assets the material depends upon * @returns the instantiated BackgroundMaterial. */ BackgroundMaterial.Parse = function (source, scene, rootUrl) { return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl); }; /** * Standard reflectance value at parallel view angle. */ BackgroundMaterial.StandardReflectance0 = 0.05; /** * Standard reflectance value at grazing angle. */ BackgroundMaterial.StandardReflectance90 = 0.5; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])() ], BackgroundMaterial.prototype, "_primaryColor", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsLightsDirty") ], BackgroundMaterial.prototype, "primaryColor", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])() ], BackgroundMaterial.prototype, "__perceptualColor", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsLightsDirty") ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])() ], BackgroundMaterial.prototype, "_reflectionTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], BackgroundMaterial.prototype, "reflectionTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BackgroundMaterial.prototype, "_reflectionBlur", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], BackgroundMaterial.prototype, "reflectionBlur", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])() ], BackgroundMaterial.prototype, "_diffuseTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], BackgroundMaterial.prototype, "diffuseTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], BackgroundMaterial.prototype, "shadowLights", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BackgroundMaterial.prototype, "_shadowLevel", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], BackgroundMaterial.prototype, "shadowLevel", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])() ], BackgroundMaterial.prototype, "_sceneCenter", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], BackgroundMaterial.prototype, "sceneCenter", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BackgroundMaterial.prototype, "_opacityFresnel", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], BackgroundMaterial.prototype, "opacityFresnel", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], BackgroundMaterial.prototype, "reflectionFresnel", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BackgroundMaterial.prototype, "_reflectionAmount", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], BackgroundMaterial.prototype, "reflectionAmount", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BackgroundMaterial.prototype, "_useRGBColor", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], BackgroundMaterial.prototype, "useRGBColor", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BackgroundMaterial.prototype, "_enableNoise", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], BackgroundMaterial.prototype, "enableNoise", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsImageProcessingConfiguration"])() ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0); return BackgroundMaterial; }(_Materials_pushMaterial__WEBPACK_IMPORTED_MODULE_9__["PushMaterial"])); _Misc_typeStore__WEBPACK_IMPORTED_MODULE_13__["_TypeStore"].RegisteredTypes["BABYLON.BackgroundMaterial"] = BackgroundMaterial; /***/ }), /***/ "./Materials/Background/index.ts": /*!***************************************!*\ !*** ./Materials/Background/index.ts ***! \***************************************/ /*! exports provided: BackgroundMaterial */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _backgroundMaterial__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./backgroundMaterial */ "./Materials/Background/backgroundMaterial.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BackgroundMaterial", function() { return _backgroundMaterial__WEBPACK_IMPORTED_MODULE_0__["BackgroundMaterial"]; }); /***/ }), /***/ "./Materials/PBR/index.ts": /*!********************************!*\ !*** ./Materials/PBR/index.ts ***! \********************************/ /*! exports provided: PBRMaterialDefines, PBRBaseMaterial, PBRBaseSimpleMaterial, PBRMaterial, PBRMetallicRoughnessMaterial, PBRSpecularGlossinessMaterial */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./pbrBaseMaterial */ "./Materials/PBR/pbrBaseMaterial.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMaterialDefines", function() { return _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_0__["PBRMaterialDefines"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRBaseMaterial", function() { return _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_0__["PBRBaseMaterial"]; }); /* harmony import */ var _pbrBaseSimpleMaterial__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./pbrBaseSimpleMaterial */ "./Materials/PBR/pbrBaseSimpleMaterial.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRBaseSimpleMaterial", function() { return _pbrBaseSimpleMaterial__WEBPACK_IMPORTED_MODULE_1__["PBRBaseSimpleMaterial"]; }); /* harmony import */ var _pbrMaterial__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./pbrMaterial */ "./Materials/PBR/pbrMaterial.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMaterial", function() { return _pbrMaterial__WEBPACK_IMPORTED_MODULE_2__["PBRMaterial"]; }); /* harmony import */ var _pbrMetallicRoughnessMaterial__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./pbrMetallicRoughnessMaterial */ "./Materials/PBR/pbrMetallicRoughnessMaterial.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMetallicRoughnessMaterial", function() { return _pbrMetallicRoughnessMaterial__WEBPACK_IMPORTED_MODULE_3__["PBRMetallicRoughnessMaterial"]; }); /* harmony import */ var _pbrSpecularGlossinessMaterial__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./pbrSpecularGlossinessMaterial */ "./Materials/PBR/pbrSpecularGlossinessMaterial.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRSpecularGlossinessMaterial", function() { return _pbrSpecularGlossinessMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRSpecularGlossinessMaterial"]; }); /***/ }), /***/ "./Materials/PBR/pbrAnisotropicConfiguration.ts": /*!******************************************************!*\ !*** ./Materials/PBR/pbrAnisotropicConfiguration.ts ***! \******************************************************/ /*! exports provided: PBRAnisotropicConfiguration */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRAnisotropicConfiguration", function() { return PBRAnisotropicConfiguration; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Meshes/buffer */ "./Meshes/buffer.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/materialFlags */ "./Materials/materialFlags.ts"); /* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Materials/materialHelper */ "./Materials/materialHelper.ts"); /** * Define the code related to the anisotropic parameters of the pbr material. */ var PBRAnisotropicConfiguration = /** @class */ (function () { /** * Instantiate a new istance of anisotropy configuration. * @param markAllSubMeshesAsTexturesDirty Callback to flag the material to dirty */ function PBRAnisotropicConfiguration(markAllSubMeshesAsTexturesDirty) { this._isEnabled = false; /** * Defines if the anisotropy is enabled in the material. */ this.isEnabled = false; /** * Defines the anisotropy strength (between 0 and 1) it defaults to 1. */ this.intensity = 1; /** * Defines if the effect is along the tangents, bitangents or in between. * By default, the effect is "strectching" the highlights along the tangents. */ this.direction = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector2"](1, 0); this._texture = null; /** * Stores the anisotropy values in a texture. * rg is direction (like normal from -1 to 1) * b is a intensity */ this.texture = null; this._internalMarkAllSubMeshesAsTexturesDirty = markAllSubMeshesAsTexturesDirty; } /** @hidden */ PBRAnisotropicConfiguration.prototype._markAllSubMeshesAsTexturesDirty = function () { this._internalMarkAllSubMeshesAsTexturesDirty(); }; /** * Specifies that the submesh is ready to be used. * @param defines the list of "defines" to update. * @param scene defines the scene the material belongs to. * @returns - boolean indicating that the submesh is ready or not. */ PBRAnisotropicConfiguration.prototype.isReadyForSubMesh = function (defines, scene) { if (defines._areTexturesDirty) { if (scene.texturesEnabled) { if (this._texture && _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_4__["MaterialFlags"].AnisotropicTextureEnabled) { if (!this._texture.isReadyOrNotBlocking()) { return false; } } } } return true; }; /** * Checks to see if a texture is used in the material. * @param defines the list of "defines" to update. * @param mesh the mesh we are preparing the defines for. * @param scene defines the scene the material belongs to. */ PBRAnisotropicConfiguration.prototype.prepareDefines = function (defines, mesh, scene) { if (this._isEnabled) { defines.ANISOTROPIC = this._isEnabled; if (this._isEnabled && !mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].TangentKind)) { defines._needUVs = true; defines.MAINUV1 = true; } if (defines._areTexturesDirty) { if (scene.texturesEnabled) { if (this._texture && _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_4__["MaterialFlags"].AnisotropicTextureEnabled) { _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_5__["MaterialHelper"].PrepareDefinesForMergedUV(this._texture, defines, "ANISOTROPIC_TEXTURE"); } else { defines.ANISOTROPIC_TEXTURE = false; } } } } else { defines.ANISOTROPIC = false; defines.ANISOTROPIC_TEXTURE = false; } }; /** * Binds the material data. * @param uniformBuffer defines the Uniform buffer to fill in. * @param scene defines the scene the material belongs to. * @param isFrozen defines wether the material is frozen or not. */ PBRAnisotropicConfiguration.prototype.bindForSubMesh = function (uniformBuffer, scene, isFrozen) { if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) { if (this._texture && _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_4__["MaterialFlags"].AnisotropicTextureEnabled) { uniformBuffer.updateFloat2("vAnisotropyInfos", this._texture.coordinatesIndex, this._texture.level); _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_5__["MaterialHelper"].BindTextureMatrix(this._texture, uniformBuffer, "anisotropy"); } // Anisotropy uniformBuffer.updateFloat3("vAnisotropy", this.direction.x, this.direction.y, this.intensity); } // Textures if (scene.texturesEnabled) { if (this._texture && _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_4__["MaterialFlags"].AnisotropicTextureEnabled) { uniformBuffer.setTexture("anisotropySampler", this._texture); } } }; /** * Checks to see if a texture is used in the material. * @param texture - Base texture to use. * @returns - Boolean specifying if a texture is used in the material. */ PBRAnisotropicConfiguration.prototype.hasTexture = function (texture) { if (this._texture === texture) { return true; } return false; }; /** * Returns an array of the actively used textures. * @param activeTextures Array of BaseTextures */ PBRAnisotropicConfiguration.prototype.getActiveTextures = function (activeTextures) { if (this._texture) { activeTextures.push(this._texture); } }; /** * Returns the animatable textures. * @param animatables Array of animatable textures. */ PBRAnisotropicConfiguration.prototype.getAnimatables = function (animatables) { if (this._texture && this._texture.animations && this._texture.animations.length > 0) { animatables.push(this._texture); } }; /** * Disposes the resources of the material. * @param forceDisposeTextures - Forces the disposal of all textures. */ PBRAnisotropicConfiguration.prototype.dispose = function (forceDisposeTextures) { if (forceDisposeTextures) { if (this._texture) { this._texture.dispose(); } } }; /** * Get the current class name of the texture useful for serialization or dynamic coding. * @returns "PBRAnisotropicConfiguration" */ PBRAnisotropicConfiguration.prototype.getClassName = function () { return "PBRAnisotropicConfiguration"; }; /** * Add fallbacks to the effect fallbacks list. * @param defines defines the Base texture to use. * @param fallbacks defines the current fallback list. * @param currentRank defines the current fallback rank. * @returns the new fallback rank. */ PBRAnisotropicConfiguration.AddFallbacks = function (defines, fallbacks, currentRank) { if (defines.ANISOTROPIC) { fallbacks.addFallback(currentRank++, "ANISOTROPIC"); } return currentRank; }; /** * Add the required uniforms to the current list. * @param uniforms defines the current uniform list. */ PBRAnisotropicConfiguration.AddUniforms = function (uniforms) { uniforms.push("vAnisotropy", "vAnisotropyInfos", "anisotropyMatrix"); }; /** * Add the required uniforms to the current buffer. * @param uniformBuffer defines the current uniform buffer. */ PBRAnisotropicConfiguration.PrepareUniformBuffer = function (uniformBuffer) { uniformBuffer.addUniform("vAnisotropy", 3); uniformBuffer.addUniform("vAnisotropyInfos", 2); uniformBuffer.addUniform("anisotropyMatrix", 16); }; /** * Add the required samplers to the current list. * @param samplers defines the current sampler list. */ PBRAnisotropicConfiguration.AddSamplers = function (samplers) { samplers.push("anisotropySampler"); }; /** * Makes a duplicate of the current configuration into another one. * @param anisotropicConfiguration define the config where to copy the info */ PBRAnisotropicConfiguration.prototype.copyTo = function (anisotropicConfiguration) { _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return anisotropicConfiguration; }, this); }; /** * Serializes this anisotropy configuration. * @returns - An object with the serialized config. */ PBRAnisotropicConfiguration.prototype.serialize = function () { return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); }; /** * Parses a anisotropy Configuration from a serialized object. * @param source - Serialized object. */ PBRAnisotropicConfiguration.prototype.parse = function (source) { var _this = this; _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return _this; }, source, null); }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRAnisotropicConfiguration.prototype, "_isEnabled", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRAnisotropicConfiguration.prototype, "isEnabled", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRAnisotropicConfiguration.prototype, "intensity", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector2"])() ], PBRAnisotropicConfiguration.prototype, "direction", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])() ], PBRAnisotropicConfiguration.prototype, "_texture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRAnisotropicConfiguration.prototype, "texture", void 0); return PBRAnisotropicConfiguration; }()); /***/ }), /***/ "./Materials/PBR/pbrBRDFConfiguration.ts": /*!***********************************************!*\ !*** ./Materials/PBR/pbrBRDFConfiguration.ts ***! \***********************************************/ /*! exports provided: PBRBRDFConfiguration */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRBRDFConfiguration", function() { return PBRBRDFConfiguration; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /** * Define the code related to the BRDF parameters of the pbr material. */ var PBRBRDFConfiguration = /** @class */ (function () { /** * Instantiate a new istance of clear coat configuration. * @param markAllSubMeshesAsMiscDirty Callback to flag the material to dirty */ function PBRBRDFConfiguration(markAllSubMeshesAsMiscDirty) { this._useEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION; /** * Defines if the material uses energy conservation. */ this.useEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION; this._useSmithVisibilityHeightCorrelated = PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED; /** * LEGACY Mode set to false * Defines if the material uses height smith correlated visibility term. * If you intent to not use our default BRDF, you need to load a separate BRDF Texture for the PBR * You can either load https://assets.babylonjs.com/environments/uncorrelatedBRDF.png * or https://assets.babylonjs.com/environments/uncorrelatedBRDF.dds to have more precision * Not relying on height correlated will also disable energy conservation. */ this.useSmithVisibilityHeightCorrelated = PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED; this._internalMarkAllSubMeshesAsMiscDirty = markAllSubMeshesAsMiscDirty; } /** @hidden */ PBRBRDFConfiguration.prototype._markAllSubMeshesAsMiscDirty = function () { this._internalMarkAllSubMeshesAsMiscDirty(); }; /** * Checks to see if a texture is used in the material. * @param defines the list of "defines" to update. */ PBRBRDFConfiguration.prototype.prepareDefines = function (defines) { defines.BRDF_V_HEIGHT_CORRELATED = this._useSmithVisibilityHeightCorrelated; defines.MS_BRDF_ENERGY_CONSERVATION = this._useEnergyConservation && this._useSmithVisibilityHeightCorrelated; }; /** * Get the current class name of the texture useful for serialization or dynamic coding. * @returns "PBRClearCoatConfiguration" */ PBRBRDFConfiguration.prototype.getClassName = function () { return "PBRClearCoatConfiguration"; }; /** * Makes a duplicate of the current configuration into another one. * @param brdfConfiguration define the config where to copy the info */ PBRBRDFConfiguration.prototype.copyTo = function (brdfConfiguration) { _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return brdfConfiguration; }, this); }; /** * Serializes this BRDF configuration. * @returns - An object with the serialized config. */ PBRBRDFConfiguration.prototype.serialize = function () { return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); }; /** * Parses a BRDF Configuration from a serialized object. * @param source - Serialized object. */ PBRBRDFConfiguration.prototype.parse = function (source) { var _this = this; _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return _this; }, source, null); }; /** * Default value used for the energy conservation. * This should only be changed to adapt to the type of texture in scene.environmentBRDFTexture. */ PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION = true; /** * Default value used for the Smith Visibility Height Correlated mode. * This should only be changed to adapt to the type of texture in scene.environmentBRDFTexture. */ PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED = true; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRBRDFConfiguration.prototype, "_useEnergyConservation", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsMiscDirty") ], PBRBRDFConfiguration.prototype, "useEnergyConservation", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRBRDFConfiguration.prototype, "_useSmithVisibilityHeightCorrelated", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsMiscDirty") ], PBRBRDFConfiguration.prototype, "useSmithVisibilityHeightCorrelated", void 0); return PBRBRDFConfiguration; }()); /***/ }), /***/ "./Materials/PBR/pbrBaseMaterial.ts": /*!******************************************!*\ !*** ./Materials/PBR/pbrBaseMaterial.ts ***! \******************************************/ /*! exports provided: PBRMaterialDefines, PBRBaseMaterial */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRMaterialDefines", function() { return PBRMaterialDefines; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRBaseMaterial", function() { return PBRBaseMaterial; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Misc_smartArray__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/smartArray */ "./Misc/smartArray.ts"); /* harmony import */ var _Misc_brdfTextureTools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Misc/brdfTextureTools */ "./Misc/brdfTextureTools.ts"); /* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../scene */ "./scene.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Meshes/buffer */ "./Meshes/buffer.ts"); /* harmony import */ var _pbrClearCoatConfiguration__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./pbrClearCoatConfiguration */ "./Materials/PBR/pbrClearCoatConfiguration.ts"); /* harmony import */ var _pbrAnisotropicConfiguration__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./pbrAnisotropicConfiguration */ "./Materials/PBR/pbrAnisotropicConfiguration.ts"); /* harmony import */ var _pbrBRDFConfiguration__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./pbrBRDFConfiguration */ "./Materials/PBR/pbrBRDFConfiguration.ts"); /* harmony import */ var _pbrSheenConfiguration__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./pbrSheenConfiguration */ "./Materials/PBR/pbrSheenConfiguration.ts"); /* harmony import */ var _pbrSubSurfaceConfiguration__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./pbrSubSurfaceConfiguration */ "./Materials/PBR/pbrSubSurfaceConfiguration.ts"); /* harmony import */ var _Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../../Materials/imageProcessingConfiguration */ "./Materials/imageProcessingConfiguration.ts"); /* harmony import */ var _Materials_effect__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../../Materials/effect */ "./Materials/effect.ts"); /* harmony import */ var _Materials_materialDefines__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../../Materials/materialDefines */ "./Materials/materialDefines.ts"); /* harmony import */ var _Materials_pushMaterial__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../../Materials/pushMaterial */ "./Materials/pushMaterial.ts"); /* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../../Materials/materialHelper */ "./Materials/materialHelper.ts"); /* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); /* harmony import */ var _materialFlags__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../materialFlags */ "./Materials/materialFlags.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); /* harmony import */ var _Shaders_pbr_fragment__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../../Shaders/pbr.fragment */ "./Shaders/pbr.fragment.ts"); /* harmony import */ var _Shaders_pbr_vertex__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../../Shaders/pbr.vertex */ "./Shaders/pbr.vertex.ts"); /** * Manages the defines for the PBR Material. * @hidden */ var PBRMaterialDefines = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PBRMaterialDefines, _super); /** * Initializes the PBR Material defines. */ function PBRMaterialDefines() { var _this = _super.call(this) || this; _this.PBR = true; _this.MAINUV1 = false; _this.MAINUV2 = false; _this.UV1 = false; _this.UV2 = false; _this.ALBEDO = false; _this.ALBEDODIRECTUV = 0; _this.VERTEXCOLOR = false; _this.AMBIENT = false; _this.AMBIENTDIRECTUV = 0; _this.AMBIENTINGRAYSCALE = false; _this.OPACITY = false; _this.VERTEXALPHA = false; _this.OPACITYDIRECTUV = 0; _this.OPACITYRGB = false; _this.ALPHATEST = false; _this.DEPTHPREPASS = false; _this.ALPHABLEND = false; _this.ALPHAFROMALBEDO = false; _this.ALPHATESTVALUE = "0.5"; _this.SPECULAROVERALPHA = false; _this.RADIANCEOVERALPHA = false; _this.ALPHAFRESNEL = false; _this.LINEARALPHAFRESNEL = false; _this.PREMULTIPLYALPHA = false; _this.EMISSIVE = false; _this.EMISSIVEDIRECTUV = 0; _this.REFLECTIVITY = false; _this.REFLECTIVITYDIRECTUV = 0; _this.SPECULARTERM = false; _this.MICROSURFACEFROMREFLECTIVITYMAP = false; _this.MICROSURFACEAUTOMATIC = false; _this.LODBASEDMICROSFURACE = false; _this.MICROSURFACEMAP = false; _this.MICROSURFACEMAPDIRECTUV = 0; _this.METALLICWORKFLOW = false; _this.ROUGHNESSSTOREINMETALMAPALPHA = false; _this.ROUGHNESSSTOREINMETALMAPGREEN = false; _this.METALLNESSSTOREINMETALMAPBLUE = false; _this.AOSTOREINMETALMAPRED = false; _this.ENVIRONMENTBRDF = false; _this.ENVIRONMENTBRDF_RGBD = false; _this.NORMAL = false; _this.TANGENT = false; _this.BUMP = false; _this.BUMPDIRECTUV = 0; _this.OBJECTSPACE_NORMALMAP = false; _this.PARALLAX = false; _this.PARALLAXOCCLUSION = false; _this.NORMALXYSCALE = true; _this.LIGHTMAP = false; _this.LIGHTMAPDIRECTUV = 0; _this.USELIGHTMAPASSHADOWMAP = false; _this.GAMMALIGHTMAP = false; _this.REFLECTION = false; _this.REFLECTIONMAP_3D = false; _this.REFLECTIONMAP_SPHERICAL = false; _this.REFLECTIONMAP_PLANAR = false; _this.REFLECTIONMAP_CUBIC = false; _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false; _this.REFLECTIONMAP_PROJECTION = false; _this.REFLECTIONMAP_SKYBOX = false; _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false; _this.REFLECTIONMAP_EXPLICIT = false; _this.REFLECTIONMAP_EQUIRECTANGULAR = false; _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false; _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false; _this.INVERTCUBICMAP = false; _this.USESPHERICALFROMREFLECTIONMAP = false; _this.USESPHERICALINVERTEX = false; _this.REFLECTIONMAP_OPPOSITEZ = false; _this.LODINREFLECTIONALPHA = false; _this.GAMMAREFLECTION = false; _this.RGBDREFLECTION = false; _this.RADIANCEOCCLUSION = false; _this.HORIZONOCCLUSION = false; _this.INSTANCES = false; _this.NUM_BONE_INFLUENCERS = 0; _this.BonesPerMesh = 0; _this.BONETEXTURE = false; _this.NONUNIFORMSCALING = false; _this.MORPHTARGETS = false; _this.MORPHTARGETS_NORMAL = false; _this.MORPHTARGETS_TANGENT = false; _this.NUM_MORPH_INFLUENCERS = 0; _this.IMAGEPROCESSING = false; _this.VIGNETTE = false; _this.VIGNETTEBLENDMODEMULTIPLY = false; _this.VIGNETTEBLENDMODEOPAQUE = false; _this.TONEMAPPING = false; _this.TONEMAPPING_ACES = false; _this.CONTRAST = false; _this.COLORCURVES = false; _this.COLORGRADING = false; _this.COLORGRADING3D = false; _this.SAMPLER3DGREENDEPTH = false; _this.SAMPLER3DBGRMAP = false; _this.IMAGEPROCESSINGPOSTPROCESS = false; _this.EXPOSURE = false; _this.MULTIVIEW = false; _this.USEPHYSICALLIGHTFALLOFF = false; _this.USEGLTFLIGHTFALLOFF = false; _this.TWOSIDEDLIGHTING = false; _this.SHADOWFLOAT = false; _this.CLIPPLANE = false; _this.CLIPPLANE2 = false; _this.CLIPPLANE3 = false; _this.CLIPPLANE4 = false; _this.POINTSIZE = false; _this.FOG = false; _this.LOGARITHMICDEPTH = false; _this.FORCENORMALFORWARD = false; _this.SPECULARAA = false; _this.CLEARCOAT = false; _this.CLEARCOAT_DEFAULTIOR = false; _this.CLEARCOAT_TEXTURE = false; _this.CLEARCOAT_TEXTUREDIRECTUV = 0; _this.CLEARCOAT_BUMP = false; _this.CLEARCOAT_BUMPDIRECTUV = 0; _this.CLEARCOAT_TINT = false; _this.CLEARCOAT_TINT_TEXTURE = false; _this.CLEARCOAT_TINT_TEXTUREDIRECTUV = 0; _this.ANISOTROPIC = false; _this.ANISOTROPIC_TEXTURE = false; _this.ANISOTROPIC_TEXTUREDIRECTUV = 0; _this.BRDF_V_HEIGHT_CORRELATED = false; _this.MS_BRDF_ENERGY_CONSERVATION = false; _this.SHEEN = false; _this.SHEEN_TEXTURE = false; _this.SHEEN_TEXTUREDIRECTUV = 0; _this.SHEEN_LINKWITHALBEDO = false; _this.SUBSURFACE = false; _this.SS_REFRACTION = false; _this.SS_TRANSLUCENCY = false; _this.SS_SCATERRING = false; _this.SS_THICKNESSANDMASK_TEXTURE = false; _this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV = 0; _this.SS_REFRACTIONMAP_3D = false; _this.SS_REFRACTIONMAP_OPPOSITEZ = false; _this.SS_LODINREFRACTIONALPHA = false; _this.SS_GAMMAREFRACTION = false; _this.SS_RGBDREFRACTION = false; _this.SS_LINKREFRACTIONTOTRANSPARENCY = false; _this.SS_MASK_FROM_THICKNESS_TEXTURE = false; _this.UNLIT = false; _this.DEBUGMODE = 0; _this.rebuild(); return _this; } /** * Resets the PBR Material defines. */ PBRMaterialDefines.prototype.reset = function () { _super.prototype.reset.call(this); this.ALPHATESTVALUE = "0.5"; this.PBR = true; }; return PBRMaterialDefines; }(_Materials_materialDefines__WEBPACK_IMPORTED_MODULE_15__["MaterialDefines"])); /** * The Physically based material base class of BJS. * * This offers the main features of a standard PBR material. * For more information, please refer to the documentation : * http://doc.babylonjs.com/extensions/Physically_Based_Rendering */ var PBRBaseMaterial = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PBRBaseMaterial, _super); /** * Instantiates a new PBRMaterial instance. * * @param name The material name * @param scene The scene the material will be use in. */ function PBRBaseMaterial(name, scene) { var _this = _super.call(this, name, scene) || this; /** * Intensity of the direct lights e.g. the four lights available in your scene. * This impacts both the direct diffuse and specular highlights. */ _this._directIntensity = 1.0; /** * Intensity of the emissive part of the material. * This helps controlling the emissive effect without modifying the emissive color. */ _this._emissiveIntensity = 1.0; /** * Intensity of the environment e.g. how much the environment will light the object * either through harmonics for rough material or through the refelction for shiny ones. */ _this._environmentIntensity = 1.0; /** * This is a special control allowing the reduction of the specular highlights coming from the * four lights of the scene. Those highlights may not be needed in full environment lighting. */ _this._specularIntensity = 1.0; /** * This stores the direct, emissive, environment, and specular light intensities into a Vector4. */ _this._lightingInfos = new _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Vector4"](_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity); /** * Debug Control allowing disabling the bump map on this material. */ _this._disableBumpMap = false; /** * AKA Occlusion Texture Intensity in other nomenclature. */ _this._ambientTextureStrength = 1.0; /** * Defines how much the AO map is occluding the analytical lights (point spot...). * 1 means it completely occludes it * 0 mean it has no impact */ _this._ambientTextureImpactOnAnalyticalLights = PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS; /** * The color of a material in ambient lighting. */ _this._ambientColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Color3"](0, 0, 0); /** * AKA Diffuse Color in other nomenclature. */ _this._albedoColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Color3"](1, 1, 1); /** * AKA Specular Color in other nomenclature. */ _this._reflectivityColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Color3"](1, 1, 1); /** * The color applied when light is reflected from a material. */ _this._reflectionColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Color3"](1, 1, 1); /** * The color applied when light is emitted from a material. */ _this._emissiveColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Color3"](0, 0, 0); /** * AKA Glossiness in other nomenclature. */ _this._microSurface = 0.9; /** * Specifies that the material will use the light map as a show map. */ _this._useLightmapAsShadowmap = false; /** * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal * makes the reflect vector face the model (under horizon). */ _this._useHorizonOcclusion = true; /** * This parameters will enable/disable radiance occlusion by preventing the radiance to lit * too much the area relying on ambient texture to define their ambient occlusion. */ _this._useRadianceOcclusion = true; /** * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending. */ _this._useAlphaFromAlbedoTexture = false; /** * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones). * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind. */ _this._useSpecularOverAlpha = true; /** * Specifies if the reflectivity texture contains the glossiness information in its alpha channel. */ _this._useMicroSurfaceFromReflectivityMapAlpha = false; /** * Specifies if the metallic texture contains the roughness information in its alpha channel. */ _this._useRoughnessFromMetallicTextureAlpha = true; /** * Specifies if the metallic texture contains the roughness information in its green channel. */ _this._useRoughnessFromMetallicTextureGreen = false; /** * Specifies if the metallic texture contains the metallness information in its blue channel. */ _this._useMetallnessFromMetallicTextureBlue = false; /** * Specifies if the metallic texture contains the ambient occlusion information in its red channel. */ _this._useAmbientOcclusionFromMetallicTextureRed = false; /** * Specifies if the ambient texture contains the ambient occlusion information in its red channel only. */ _this._useAmbientInGrayScale = false; /** * In case the reflectivity map does not contain the microsurface information in its alpha channel, * The material will try to infer what glossiness each pixel should be. */ _this._useAutoMicroSurfaceFromReflectivityMap = false; /** * Defines the falloff type used in this material. * It by default is Physical. */ _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL; /** * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones). * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind. */ _this._useRadianceOverAlpha = true; /** * Allows using an object space normal map (instead of tangent space). */ _this._useObjectSpaceNormalMap = false; /** * Allows using the bump map in parallax mode. */ _this._useParallax = false; /** * Allows using the bump map in parallax occlusion mode. */ _this._useParallaxOcclusion = false; /** * Controls the scale bias of the parallax mode. */ _this._parallaxScaleBias = 0.05; /** * If sets to true, disables all the lights affecting the material. */ _this._disableLighting = false; /** * Number of Simultaneous lights allowed on the material. */ _this._maxSimultaneousLights = 4; /** * If sets to true, x component of normal map value will be inverted (x = 1.0 - x). */ _this._invertNormalMapX = false; /** * If sets to true, y component of normal map value will be inverted (y = 1.0 - y). */ _this._invertNormalMapY = false; /** * If sets to true and backfaceCulling is false, normals will be flipped on the backside. */ _this._twoSidedLighting = false; /** * Defines the alpha limits in alpha test mode. */ _this._alphaCutOff = 0.4; /** * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations. */ _this._forceAlphaTest = false; /** * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel) */ _this._useAlphaFresnel = false; /** * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel) */ _this._useLinearAlphaFresnel = false; /** * The transparency mode of the material. */ _this._transparencyMode = null; /** * Specifies the environment BRDF texture used to comput the scale and offset roughness values * from cos thetav and roughness: * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf */ _this._environmentBRDFTexture = null; /** * Force the shader to compute irradiance in the fragment shader in order to take bump in account. */ _this._forceIrradianceInFragment = false; /** * Force normal to face away from face. */ _this._forceNormalForward = false; /** * Enables specular anti aliasing in the PBR shader. * It will both interacts on the Geometry for analytical and IBL lighting. * It also prefilter the roughness map based on the bump values. */ _this._enableSpecularAntiAliasing = false; /** * Stores the available render targets. */ _this._renderTargets = new _Misc_smartArray__WEBPACK_IMPORTED_MODULE_3__["SmartArray"](16); /** * Sets the global ambient color for the material used in lighting calculations. */ _this._globalAmbientColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Color3"](0, 0, 0); /** * If set to true, no lighting calculations will be applied. */ _this._unlit = false; _this._debugMode = 0; /** * @hidden * This is reserved for the inspector. * Defines the material debug mode. * It helps seeing only some components of the material while troubleshooting. */ _this.debugMode = 0; /** * @hidden * This is reserved for the inspector. * Specify from where on screen the debug mode should start. * The value goes from -1 (full screen) to 1 (not visible) * It helps with side by side comparison against the final render * This defaults to -1 */ _this.debugLimit = -1; /** * @hidden * This is reserved for the inspector. * As the default viewing range might not be enough (if the ambient is really small for instance) * You can use the factor to better multiply the final value. */ _this.debugFactor = 1; /** * Defines the clear coat layer parameters for the material. */ _this.clearCoat = new _pbrClearCoatConfiguration__WEBPACK_IMPORTED_MODULE_8__["PBRClearCoatConfiguration"](_this._markAllSubMeshesAsTexturesDirty.bind(_this)); /** * Defines the anisotropic parameters for the material. */ _this.anisotropy = new _pbrAnisotropicConfiguration__WEBPACK_IMPORTED_MODULE_9__["PBRAnisotropicConfiguration"](_this._markAllSubMeshesAsTexturesDirty.bind(_this)); /** * Defines the BRDF parameters for the material. */ _this.brdf = new _pbrBRDFConfiguration__WEBPACK_IMPORTED_MODULE_10__["PBRBRDFConfiguration"](_this._markAllSubMeshesAsMiscDirty.bind(_this)); /** * Defines the Sheen parameters for the material. */ _this.sheen = new _pbrSheenConfiguration__WEBPACK_IMPORTED_MODULE_11__["PBRSheenConfiguration"](_this._markAllSubMeshesAsTexturesDirty.bind(_this)); /** * Defines the SubSurface parameters for the material. */ _this.subSurface = new _pbrSubSurfaceConfiguration__WEBPACK_IMPORTED_MODULE_12__["PBRSubSurfaceConfiguration"](_this._markAllSubMeshesAsTexturesDirty.bind(_this)); // Setup the default processing configuration to the scene. _this._attachImageProcessingConfiguration(null); _this.getRenderTargetTextures = function () { _this._renderTargets.reset(); if (_materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) { _this._renderTargets.push(_this._reflectionTexture); } _this.subSurface.fillRenderTargetTextures(_this._renderTargets); return _this._renderTargets; }; _this._environmentBRDFTexture = _Misc_brdfTextureTools__WEBPACK_IMPORTED_MODULE_4__["BRDFTextureTools"].GetEnvironmentBRDFTexture(scene); return _this; } /** * Attaches a new image processing configuration to the PBR Material. * @param configuration */ PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) { var _this = this; if (configuration === this._imageProcessingConfiguration) { return; } // Detaches observer. if (this._imageProcessingConfiguration && this._imageProcessingObserver) { this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); } // Pick the scene configuration if needed. if (!configuration) { this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration; } else { this._imageProcessingConfiguration = configuration; } // Attaches observer. if (this._imageProcessingConfiguration) { this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function () { _this._markAllSubMeshesAsImageProcessingDirty(); }); } }; Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", { /** * Gets a boolean indicating that current material needs to register RTT */ get: function () { if (_materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) { return true; } return this.subSurface.hasRenderTargetTextures(); }, enumerable: true, configurable: true }); /** * Gets the name of the material class. */ PBRBaseMaterial.prototype.getClassName = function () { return "PBRBaseMaterial"; }; Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", { /** * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers. */ get: function () { return this._useLogarithmicDepth; }, /** * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers. */ set: function (value) { this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported; }, enumerable: true, configurable: true }); Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", { /** * Gets the current transparency mode. */ get: function () { return this._transparencyMode; }, /** * Sets the transparency mode of the material. * * | Value | Type | Description | * | ----- | ----------------------------------- | ----------- | * | 0 | OPAQUE | | * | 1 | ALPHATEST | | * | 2 | ALPHABLEND | | * | 3 | ALPHATESTANDBLEND | | * */ set: function (value) { if (this._transparencyMode === value) { return; } this._transparencyMode = value; this._forceAlphaTest = (value === PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND); this._markAllSubMeshesAsTexturesAndMiscDirty(); }, enumerable: true, configurable: true }); Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", { /** * Returns true if alpha blending should be disabled. */ get: function () { return (this.subSurface.disableAlphaBlending || this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_OPAQUE || this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_ALPHATEST); }, enumerable: true, configurable: true }); /** * Specifies whether or not this material should be rendered in alpha blend mode. */ PBRBaseMaterial.prototype.needAlphaBlending = function () { if (this._disableAlphaBlending) { return false; } return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture(); }; /** * Specifies if the mesh will require alpha blending. * @param mesh - BJS mesh. */ PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) { if (this._disableAlphaBlending && mesh.visibility >= 1.0) { return false; } return _super.prototype.needAlphaBlendingForMesh.call(this, mesh); }; /** * Specifies whether or not this material should be rendered in alpha test mode. */ PBRBaseMaterial.prototype.needAlphaTesting = function () { if (this._forceAlphaTest) { return true; } if (this.subSurface.disableAlphaBlending) { return false; } return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_ALPHATEST); }; /** * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending. */ PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () { return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== PBRBaseMaterial.PBRMATERIAL_OPAQUE; }; /** * Gets the texture used for the alpha test. */ PBRBaseMaterial.prototype.getAlphaTestTexture = function () { return this._albedoTexture; }; /** * Specifies that the submesh is ready to be used. * @param mesh - BJS mesh. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready. * @param useInstances - Specifies that instances should be used. * @returns - boolean indicating that the submesh is ready or not. */ PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) { if (subMesh.effect && this.isFrozen) { if (this._wasPreviouslyReady) { return true; } } if (!subMesh._materialDefines) { subMesh._materialDefines = new PBRMaterialDefines(); } var defines = subMesh._materialDefines; if (!this.checkReadyOnEveryCall && subMesh.effect) { if (defines._renderId === this.getScene().getRenderId()) { return true; } } var scene = this.getScene(); var engine = scene.getEngine(); if (defines._areTexturesDirty) { if (scene.texturesEnabled) { if (this._albedoTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].DiffuseTextureEnabled) { if (!this._albedoTexture.isReadyOrNotBlocking()) { return false; } } if (this._ambientTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].AmbientTextureEnabled) { if (!this._ambientTexture.isReadyOrNotBlocking()) { return false; } } if (this._opacityTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].OpacityTextureEnabled) { if (!this._opacityTexture.isReadyOrNotBlocking()) { return false; } } var reflectionTexture = this._getReflectionTexture(); if (reflectionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].ReflectionTextureEnabled) { if (!reflectionTexture.isReadyOrNotBlocking()) { return false; } } if (this._lightmapTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].LightmapTextureEnabled) { if (!this._lightmapTexture.isReadyOrNotBlocking()) { return false; } } if (this._emissiveTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].EmissiveTextureEnabled) { if (!this._emissiveTexture.isReadyOrNotBlocking()) { return false; } } if (_materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].SpecularTextureEnabled) { if (this._metallicTexture) { if (!this._metallicTexture.isReadyOrNotBlocking()) { return false; } } else if (this._reflectivityTexture) { if (!this._reflectivityTexture.isReadyOrNotBlocking()) { return false; } } if (this._microSurfaceTexture) { if (!this._microSurfaceTexture.isReadyOrNotBlocking()) { return false; } } } if (engine.getCaps().standardDerivatives && this._bumpTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].BumpTextureEnabled && !this._disableBumpMap) { // Bump texture cannot be not blocking. if (!this._bumpTexture.isReady()) { return false; } } if (this._environmentBRDFTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].ReflectionTextureEnabled) { // This is blocking. if (!this._environmentBRDFTexture.isReady()) { return false; } } } } if (!this.subSurface.isReadyForSubMesh(defines, scene) || !this.clearCoat.isReadyForSubMesh(defines, scene, engine, this._disableBumpMap) || !this.sheen.isReadyForSubMesh(defines, scene) || !this.anisotropy.isReadyForSubMesh(defines, scene)) { return false; } if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) { if (!this._imageProcessingConfiguration.isReady()) { return false; } } if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].NormalKind)) { mesh.createNormals(true); _Misc_logger__WEBPACK_IMPORTED_MODULE_2__["Logger"].Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name); } var previousEffect = subMesh.effect; var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances); if (effect) { // Use previous effect while new one is compiling if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) { effect = previousEffect; defines.markAsUnprocessed(); } else { scene.resetCachedMaterial(); subMesh.setEffect(effect, defines); this.buildUniformLayout(); } } if (!subMesh.effect || !subMesh.effect.isReady()) { return false; } defines._renderId = scene.getRenderId(); this._wasPreviouslyReady = true; return true; }; /** * Specifies if the material uses metallic roughness workflow. * @returns boolean specifiying if the material uses metallic roughness workflow. */ PBRBaseMaterial.prototype.isMetallicWorkflow = function () { if (this._metallic != null || this._roughness != null || this._metallicTexture) { return true; } return false; }; PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) { if (onCompiled === void 0) { onCompiled = null; } if (onError === void 0) { onError = null; } if (useInstances === void 0) { useInstances = null; } if (useClipPlane === void 0) { useClipPlane = null; } this._prepareDefines(mesh, defines, useInstances, useClipPlane); if (!defines.isDirty) { return null; } defines.markAsProcessed(); var scene = this.getScene(); var engine = scene.getEngine(); // Fallbacks var fallbacks = new _Materials_effect__WEBPACK_IMPORTED_MODULE_14__["EffectFallbacks"](); var fallbackRank = 0; if (defines.USESPHERICALINVERTEX) { fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX"); } if (defines.FOG) { fallbacks.addFallback(fallbackRank, "FOG"); } if (defines.SPECULARAA) { fallbacks.addFallback(fallbackRank, "SPECULARAA"); } if (defines.POINTSIZE) { fallbacks.addFallback(fallbackRank, "POINTSIZE"); } if (defines.LOGARITHMICDEPTH) { fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH"); } if (defines.PARALLAX) { fallbacks.addFallback(fallbackRank, "PARALLAX"); } if (defines.PARALLAXOCCLUSION) { fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION"); } fallbackRank = _pbrAnisotropicConfiguration__WEBPACK_IMPORTED_MODULE_9__["PBRAnisotropicConfiguration"].AddFallbacks(defines, fallbacks, fallbackRank); fallbackRank = _pbrAnisotropicConfiguration__WEBPACK_IMPORTED_MODULE_9__["PBRAnisotropicConfiguration"].AddFallbacks(defines, fallbacks, fallbackRank); fallbackRank = _pbrSubSurfaceConfiguration__WEBPACK_IMPORTED_MODULE_12__["PBRSubSurfaceConfiguration"].AddFallbacks(defines, fallbacks, fallbackRank); fallbackRank = _pbrSheenConfiguration__WEBPACK_IMPORTED_MODULE_11__["PBRSheenConfiguration"].AddFallbacks(defines, fallbacks, fallbackRank); if (defines.ENVIRONMENTBRDF) { fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF"); } if (defines.TANGENT) { fallbacks.addFallback(fallbackRank++, "TANGENT"); } if (defines.BUMP) { fallbacks.addFallback(fallbackRank++, "BUMP"); } fallbackRank = _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++); if (defines.SPECULARTERM) { fallbacks.addFallback(fallbackRank++, "SPECULARTERM"); } if (defines.USESPHERICALFROMREFLECTIONMAP) { fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP"); } if (defines.LIGHTMAP) { fallbacks.addFallback(fallbackRank++, "LIGHTMAP"); } if (defines.NORMAL) { fallbacks.addFallback(fallbackRank++, "NORMAL"); } if (defines.AMBIENT) { fallbacks.addFallback(fallbackRank++, "AMBIENT"); } if (defines.EMISSIVE) { fallbacks.addFallback(fallbackRank++, "EMISSIVE"); } if (defines.VERTEXCOLOR) { fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR"); } if (defines.NUM_BONE_INFLUENCERS > 0) { fallbacks.addCPUSkinningFallback(fallbackRank++, mesh); } if (defines.MORPHTARGETS) { fallbacks.addFallback(fallbackRank++, "MORPHTARGETS"); } if (defines.MULTIVIEW) { fallbacks.addFallback(0, "MULTIVIEW"); } //Attributes var attribs = [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].PositionKind]; if (defines.NORMAL) { attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].NormalKind); } if (defines.TANGENT) { attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].TangentKind); } if (defines.UV1) { attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].UVKind); } if (defines.UV2) { attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].UV2Kind); } if (defines.VERTEXCOLOR) { attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].ColorKind); } _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareAttributesForBones(attribs, mesh, defines, fallbacks); _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareAttributesForInstances(attribs, defines); _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareAttributesForMorphTargets(attribs, mesh, defines); var shaderName = "pbr"; var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "visibility", "vReflectionColor", "vFogInfos", "vFogColor", "pointSize", "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "mBones", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "vLightingIntensity", "logarithmicDepthConstant", "vSphericalX", "vSphericalY", "vSphericalZ", "vSphericalXX", "vSphericalYY", "vSphericalZZ", "vSphericalXY", "vSphericalYZ", "vSphericalZX", "vReflectionMicrosurfaceInfos", "vTangentSpaceParams", "boneTextureWidth", "vDebugMode" ]; var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler", "bumpSampler", "lightmapSampler", "opacitySampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh", "microSurfaceSampler", "environmentBrdfSampler", "boneSampler"]; var uniformBuffers = ["Material", "Scene"]; _pbrSubSurfaceConfiguration__WEBPACK_IMPORTED_MODULE_12__["PBRSubSurfaceConfiguration"].AddUniforms(uniforms); _pbrSubSurfaceConfiguration__WEBPACK_IMPORTED_MODULE_12__["PBRSubSurfaceConfiguration"].AddSamplers(samplers); _pbrClearCoatConfiguration__WEBPACK_IMPORTED_MODULE_8__["PBRClearCoatConfiguration"].AddUniforms(uniforms); _pbrClearCoatConfiguration__WEBPACK_IMPORTED_MODULE_8__["PBRClearCoatConfiguration"].AddSamplers(samplers); _pbrAnisotropicConfiguration__WEBPACK_IMPORTED_MODULE_9__["PBRAnisotropicConfiguration"].AddUniforms(uniforms); _pbrAnisotropicConfiguration__WEBPACK_IMPORTED_MODULE_9__["PBRAnisotropicConfiguration"].AddSamplers(samplers); _pbrSheenConfiguration__WEBPACK_IMPORTED_MODULE_11__["PBRSheenConfiguration"].AddUniforms(uniforms); _pbrSheenConfiguration__WEBPACK_IMPORTED_MODULE_11__["PBRSheenConfiguration"].AddSamplers(samplers); if (_Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_13__["ImageProcessingConfiguration"]) { _Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_13__["ImageProcessingConfiguration"].PrepareUniforms(uniforms, defines); _Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_13__["ImageProcessingConfiguration"].PrepareSamplers(samplers, defines); } _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareUniformsAndSamplersList({ uniformsNames: uniforms, uniformBuffersNames: uniformBuffers, samplers: samplers, defines: defines, maxSimultaneousLights: this._maxSimultaneousLights }); if (this.customShaderNameResolve) { shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines); } var join = defines.toString(); return engine.createEffect(shaderName, { attributes: attribs, uniformsNames: uniforms, uniformBuffersNames: uniformBuffers, samplers: samplers, defines: join, fallbacks: fallbacks, onCompiled: onCompiled, onError: onError, indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS } }, engine); }; PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) { if (useInstances === void 0) { useInstances = null; } if (useClipPlane === void 0) { useClipPlane = null; } var scene = this.getScene(); var engine = scene.getEngine(); // Lights _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting); defines._needNormals = true; // Multiview _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForMultiview(scene, defines); // Textures defines.METALLICWORKFLOW = this.isMetallicWorkflow(); if (defines._areTexturesDirty) { defines._needUVs = false; if (scene.texturesEnabled) { if (scene.getEngine().getCaps().textureLOD) { defines.LODBASEDMICROSFURACE = true; } if (this._albedoTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].DiffuseTextureEnabled) { _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO"); } else { defines.ALBEDO = false; } if (this._ambientTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].AmbientTextureEnabled) { _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT"); defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale; } else { defines.AMBIENT = false; } if (this._opacityTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].OpacityTextureEnabled) { _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY"); defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB; } else { defines.OPACITY = false; } var reflectionTexture = this._getReflectionTexture(); if (reflectionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].ReflectionTextureEnabled) { defines.REFLECTION = true; defines.GAMMAREFLECTION = reflectionTexture.gammaSpace; defines.RGBDREFLECTION = reflectionTexture.isRGBD; defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ; defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha; if (reflectionTexture.coordinatesMode === _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__["Texture"].INVCUBIC_MODE) { defines.INVERTCUBICMAP = true; } defines.REFLECTIONMAP_3D = reflectionTexture.isCube; 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; defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false; switch (reflectionTexture.coordinatesMode) { case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__["Texture"].EXPLICIT_MODE: defines.REFLECTIONMAP_EXPLICIT = true; break; case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__["Texture"].PLANAR_MODE: defines.REFLECTIONMAP_PLANAR = true; break; case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__["Texture"].PROJECTION_MODE: defines.REFLECTIONMAP_PROJECTION = true; break; case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__["Texture"].SKYBOX_MODE: defines.REFLECTIONMAP_SKYBOX = true; break; case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__["Texture"].SPHERICAL_MODE: defines.REFLECTIONMAP_SPHERICAL = true; break; case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__["Texture"].EQUIRECTANGULAR_MODE: defines.REFLECTIONMAP_EQUIRECTANGULAR = true; break; case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__["Texture"].FIXED_EQUIRECTANGULAR_MODE: defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true; break; case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__["Texture"].FIXED_EQUIRECTANGULAR_MIRRORED_MODE: defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true; break; case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__["Texture"].CUBIC_MODE: case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__["Texture"].INVCUBIC_MODE: default: defines.REFLECTIONMAP_CUBIC = true; defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false; break; } if (reflectionTexture.coordinatesMode !== _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_18__["Texture"].SKYBOX_MODE) { if (reflectionTexture.sphericalPolynomial) { defines.USESPHERICALFROMREFLECTIONMAP = true; if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) { defines.USESPHERICALINVERTEX = false; } else { defines.USESPHERICALINVERTEX = true; } } } else { defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity(); } } 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_SKYBOX_TRANSFORMED = 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.USESPHERICALINVERTEX = false; defines.REFLECTIONMAP_OPPOSITEZ = false; defines.LODINREFLECTIONALPHA = false; defines.GAMMAREFLECTION = false; defines.RGBDREFLECTION = false; } if (this._lightmapTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].LightmapTextureEnabled) { _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP"); defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap; defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace; } else { defines.LIGHTMAP = false; } if (this._emissiveTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].EmissiveTextureEnabled) { _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE"); } else { defines.EMISSIVE = false; } if (_materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].SpecularTextureEnabled) { if (this._metallicTexture) { _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY"); defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha; defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen; defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue; defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed; } else if (this._reflectivityTexture) { _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY"); defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha; defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap; } else { defines.REFLECTIVITY = false; } if (this._microSurfaceTexture) { _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP"); } else { defines.MICROSURFACEMAP = false; } } else { defines.REFLECTIVITY = false; defines.MICROSURFACEMAP = false; } if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].BumpTextureEnabled && !this._disableBumpMap) { _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP"); if (this._useParallax && this._albedoTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].DiffuseTextureEnabled) { defines.PARALLAX = true; defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion; } else { defines.PARALLAX = false; } defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap; } else { defines.BUMP = false; } if (this._environmentBRDFTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].ReflectionTextureEnabled) { defines.ENVIRONMENTBRDF = true; // Not actual true RGBD, only the B chanel is encoded as RGBD for sheen. defines.ENVIRONMENTBRDF_RGBD = this._environmentBRDFTexture.isRGBD; } else { defines.ENVIRONMENTBRDF = false; defines.ENVIRONMENTBRDF_RGBD = false; } if (this._shouldUseAlphaFromAlbedoTexture()) { defines.ALPHAFROMALBEDO = true; } else { defines.ALPHAFROMALBEDO = false; } } defines.SPECULAROVERALPHA = this._useSpecularOverAlpha; if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) { defines.USEPHYSICALLIGHTFALLOFF = false; defines.USEGLTFLIGHTFALLOFF = false; } else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) { defines.USEPHYSICALLIGHTFALLOFF = false; defines.USEGLTFLIGHTFALLOFF = true; } else { defines.USEPHYSICALLIGHTFALLOFF = true; defines.USEGLTFLIGHTFALLOFF = false; } defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha; if (!this.backFaceCulling && this._twoSidedLighting) { defines.TWOSIDEDLIGHTING = true; } else { defines.TWOSIDEDLIGHTING = false; } defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : ""); defines.PREMULTIPLYALPHA = (this.alphaMode === _Engines_constants__WEBPACK_IMPORTED_MODULE_20__["Constants"].ALPHA_PREMULTIPLIED || this.alphaMode === _Engines_constants__WEBPACK_IMPORTED_MODULE_20__["Constants"].ALPHA_PREMULTIPLIED_PORTERDUFF); defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh); defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel; defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel; defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing; } if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) { this._imageProcessingConfiguration.prepareDefines(defines); } defines.FORCENORMALFORWARD = this._forceNormalForward; defines.RADIANCEOCCLUSION = this._useRadianceOcclusion; defines.HORIZONOCCLUSION = this._useHorizonOcclusion; // Misc. if (defines._areMiscDirty) { _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines); defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].NormalKind)); defines.DEBUGMODE = this._debugMode; } // External config this.subSurface.prepareDefines(defines, scene); this.clearCoat.prepareDefines(defines, scene); this.anisotropy.prepareDefines(defines, mesh, scene); this.brdf.prepareDefines(defines); this.sheen.prepareDefines(defines, scene); // Values that need to be evaluated on every frame _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane); // Attribs _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== PBRBaseMaterial.PBRMATERIAL_OPAQUE); }; /** * Force shader compilation */ PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) { var _this = this; var localOptions = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ clipPlane: false }, options); var defines = new PBRMaterialDefines(); var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane); if (effect.isReady()) { if (onCompiled) { onCompiled(this); } } else { effect.onCompileObservable.add(function () { if (onCompiled) { onCompiled(_this); } }); } }; /** * Initializes the uniform buffer layout for the shader. */ PBRBaseMaterial.prototype.buildUniformLayout = function () { // Order is important ! this._uniformBuffer.addUniform("vAlbedoInfos", 2); this._uniformBuffer.addUniform("vAmbientInfos", 4); this._uniformBuffer.addUniform("vOpacityInfos", 2); this._uniformBuffer.addUniform("vEmissiveInfos", 2); this._uniformBuffer.addUniform("vLightmapInfos", 2); this._uniformBuffer.addUniform("vReflectivityInfos", 3); this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2); this._uniformBuffer.addUniform("vReflectionInfos", 2); this._uniformBuffer.addUniform("vReflectionPosition", 3); this._uniformBuffer.addUniform("vReflectionSize", 3); this._uniformBuffer.addUniform("vBumpInfos", 3); this._uniformBuffer.addUniform("albedoMatrix", 16); this._uniformBuffer.addUniform("ambientMatrix", 16); this._uniformBuffer.addUniform("opacityMatrix", 16); this._uniformBuffer.addUniform("emissiveMatrix", 16); this._uniformBuffer.addUniform("lightmapMatrix", 16); this._uniformBuffer.addUniform("reflectivityMatrix", 16); this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16); this._uniformBuffer.addUniform("bumpMatrix", 16); this._uniformBuffer.addUniform("vTangentSpaceParams", 2); this._uniformBuffer.addUniform("reflectionMatrix", 16); this._uniformBuffer.addUniform("vReflectionColor", 3); this._uniformBuffer.addUniform("vAlbedoColor", 4); this._uniformBuffer.addUniform("vLightingIntensity", 4); this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3); this._uniformBuffer.addUniform("pointSize", 1); this._uniformBuffer.addUniform("vReflectivityColor", 4); this._uniformBuffer.addUniform("vEmissiveColor", 3); this._uniformBuffer.addUniform("visibility", 1); _pbrClearCoatConfiguration__WEBPACK_IMPORTED_MODULE_8__["PBRClearCoatConfiguration"].PrepareUniformBuffer(this._uniformBuffer); _pbrAnisotropicConfiguration__WEBPACK_IMPORTED_MODULE_9__["PBRAnisotropicConfiguration"].PrepareUniformBuffer(this._uniformBuffer); _pbrSheenConfiguration__WEBPACK_IMPORTED_MODULE_11__["PBRSheenConfiguration"].PrepareUniformBuffer(this._uniformBuffer); _pbrSubSurfaceConfiguration__WEBPACK_IMPORTED_MODULE_12__["PBRSubSurfaceConfiguration"].PrepareUniformBuffer(this._uniformBuffer); this._uniformBuffer.create(); }; /** * Unbinds the material from the mesh */ PBRBaseMaterial.prototype.unbind = function () { if (this._activeEffect) { var needFlag = false; if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) { this._activeEffect.setTexture("reflection2DSampler", null); needFlag = true; } if (this.subSurface.unbind(this._activeEffect)) { needFlag = true; } if (needFlag) { this._markAllSubMeshesAsTexturesDirty(); } } _super.prototype.unbind.call(this); }; /** * Binds the submesh data. * @param world - The world matrix. * @param mesh - The BJS mesh. * @param subMesh - A submesh of the BJS mesh. */ PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) { var scene = this.getScene(); var defines = subMesh._materialDefines; if (!defines) { return; } var effect = subMesh.effect; if (!effect) { return; } this._activeEffect = effect; // Matrices this.bindOnlyWorldMatrix(world); // Normal Matrix if (defines.OBJECTSPACE_NORMALMAP) { world.toNormalMatrix(this._normalMatrix); this.bindOnlyNormalMatrix(this._normalMatrix); } var mustRebind = this._mustRebind(scene, effect, mesh.visibility); // Bones _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindBonesParameters(mesh, this._activeEffect); var reflectionTexture = null; if (mustRebind) { var engine = scene.getEngine(); this._uniformBuffer.bindToEffect(effect, "Material"); this.bindViewProjection(effect); reflectionTexture = this._getReflectionTexture(); if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) { // Texture uniforms if (scene.texturesEnabled) { if (this._albedoTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].DiffuseTextureEnabled) { this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level); _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo"); } if (this._ambientTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].AmbientTextureEnabled) { this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights); _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient"); } if (this._opacityTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].OpacityTextureEnabled) { this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level); _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity"); } if (reflectionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].ReflectionTextureEnabled) { this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix()); this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0); if (reflectionTexture.boundingBoxSize) { var cubeTexture = reflectionTexture; this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition); this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize); } var polynomials = reflectionTexture.sphericalPolynomial; if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) { this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z); this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z); this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z); this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z); this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z); this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z); this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z); this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z); this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z); } this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset); } if (this._emissiveTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].EmissiveTextureEnabled) { this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level); _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive"); } if (this._lightmapTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].LightmapTextureEnabled) { this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level); _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap"); } if (_materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].SpecularTextureEnabled) { if (this._metallicTexture) { this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength); _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity"); } else if (this._reflectivityTexture) { this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0); _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity"); } if (this._microSurfaceTexture) { this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level); _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler"); } } if (this._bumpTexture && engine.getCaps().standardDerivatives && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].BumpTextureEnabled && !this._disableBumpMap) { this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias); _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump"); if (scene._mirroredCameraPosition) { this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0); } else { this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0); } } } // Point size if (this.pointsCloud) { this._uniformBuffer.updateFloat("pointSize", this.pointSize); } // Colors if (defines.METALLICWORKFLOW) { _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Tmp"].Color3[0].r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic; _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Tmp"].Color3[0].g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness; this._uniformBuffer.updateColor4("vReflectivityColor", _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Tmp"].Color3[0], 0); } else { this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface); } this._uniformBuffer.updateColor3("vEmissiveColor", _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].EmissiveTextureEnabled ? this._emissiveColor : _Maths_math__WEBPACK_IMPORTED_MODULE_6__["Color3"].BlackReadOnly); this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor); this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha); // Visibility this._uniformBuffer.updateFloat("visibility", mesh.visibility); // Misc this._lightingInfos.x = this._directIntensity; this._lightingInfos.y = this._emissiveIntensity; this._lightingInfos.z = this._environmentIntensity; this._lightingInfos.w = this._specularIntensity; this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos); } // Textures if (scene.texturesEnabled) { if (this._albedoTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].DiffuseTextureEnabled) { this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture); } if (this._ambientTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].AmbientTextureEnabled) { this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture); } if (this._opacityTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].OpacityTextureEnabled) { this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture); } if (reflectionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].ReflectionTextureEnabled) { if (defines.LODBASEDMICROSFURACE) { this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture); } else { this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture); this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture); this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture); } } if (defines.ENVIRONMENTBRDF) { this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture); } if (this._emissiveTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].EmissiveTextureEnabled) { this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture); } if (this._lightmapTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].LightmapTextureEnabled) { this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture); } if (_materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].SpecularTextureEnabled) { if (this._metallicTexture) { this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture); } else if (this._reflectivityTexture) { this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture); } if (this._microSurfaceTexture) { this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture); } } if (this._bumpTexture && engine.getCaps().standardDerivatives && _materialFlags__WEBPACK_IMPORTED_MODULE_19__["MaterialFlags"].BumpTextureEnabled && !this._disableBumpMap) { this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture); } } this.subSurface.bindForSubMesh(this._uniformBuffer, scene, engine, this.isFrozen, defines.LODBASEDMICROSFURACE); this.clearCoat.bindForSubMesh(this._uniformBuffer, scene, engine, this._disableBumpMap, this.isFrozen, this._invertNormalMapX, this._invertNormalMapY); this.anisotropy.bindForSubMesh(this._uniformBuffer, scene, this.isFrozen); this.sheen.bindForSubMesh(this._uniformBuffer, scene, this.isFrozen); // Clip plane _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindClipPlane(this._activeEffect, scene); // Colors scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor); var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition); var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null)); effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1); effect.setColor3("vAmbientColor", this._globalAmbientColor); effect.setFloat2("vDebugMode", this.debugLimit, this.debugFactor); } if (mustRebind || !this.isFrozen) { // Lights if (scene.lightsEnabled && !this._disableLighting) { _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD); } // View if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== _scene__WEBPACK_IMPORTED_MODULE_5__["Scene"].FOGMODE_NONE || reflectionTexture) { this.bindView(effect); } // Fog _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindFogParameters(scene, mesh, this._activeEffect, true); // Morph targets if (defines.NUM_MORPH_INFLUENCERS) { _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindMorphTargetParameters(mesh, this._activeEffect); } // image processing this._imageProcessingConfiguration.bind(this._activeEffect); // Log. depth _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_17__["MaterialHelper"].BindLogDepth(defines, this._activeEffect, scene); } this._uniformBuffer.update(); this._afterBind(mesh, this._activeEffect); }; /** * Returns the animatable textures. * @returns - Array of animatable textures. */ PBRBaseMaterial.prototype.getAnimatables = function () { var results = []; if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) { results.push(this._albedoTexture); } if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) { results.push(this._ambientTexture); } if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) { results.push(this._opacityTexture); } if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) { results.push(this._reflectionTexture); } if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) { results.push(this._emissiveTexture); } if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) { results.push(this._metallicTexture); } else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) { results.push(this._reflectivityTexture); } if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) { results.push(this._bumpTexture); } if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) { results.push(this._lightmapTexture); } this.subSurface.getAnimatables(results); this.clearCoat.getAnimatables(results); this.sheen.getAnimatables(results); this.anisotropy.getAnimatables(results); return results; }; /** * Returns the texture used for reflections. * @returns - Reflection texture if present. Otherwise, returns the environment texture. */ PBRBaseMaterial.prototype._getReflectionTexture = function () { if (this._reflectionTexture) { return this._reflectionTexture; } return this.getScene().environmentTexture; }; /** * Returns an array of the actively used textures. * @returns - Array of BaseTextures */ PBRBaseMaterial.prototype.getActiveTextures = function () { var activeTextures = _super.prototype.getActiveTextures.call(this); if (this._albedoTexture) { activeTextures.push(this._albedoTexture); } if (this._ambientTexture) { activeTextures.push(this._ambientTexture); } if (this._opacityTexture) { activeTextures.push(this._opacityTexture); } if (this._reflectionTexture) { activeTextures.push(this._reflectionTexture); } if (this._emissiveTexture) { activeTextures.push(this._emissiveTexture); } if (this._reflectivityTexture) { activeTextures.push(this._reflectivityTexture); } if (this._metallicTexture) { activeTextures.push(this._metallicTexture); } if (this._microSurfaceTexture) { activeTextures.push(this._microSurfaceTexture); } if (this._bumpTexture) { activeTextures.push(this._bumpTexture); } if (this._lightmapTexture) { activeTextures.push(this._lightmapTexture); } this.subSurface.getActiveTextures(activeTextures); this.clearCoat.getActiveTextures(activeTextures); this.sheen.getActiveTextures(activeTextures); this.anisotropy.getActiveTextures(activeTextures); return activeTextures; }; /** * Checks to see if a texture is used in the material. * @param texture - Base texture to use. * @returns - Boolean specifying if a texture is used in the material. */ PBRBaseMaterial.prototype.hasTexture = function (texture) { if (_super.prototype.hasTexture.call(this, texture)) { return true; } if (this._albedoTexture === texture) { return true; } if (this._ambientTexture === texture) { return true; } if (this._opacityTexture === texture) { return true; } if (this._reflectionTexture === texture) { return true; } if (this._reflectivityTexture === texture) { return true; } if (this._metallicTexture === texture) { return true; } if (this._microSurfaceTexture === texture) { return true; } if (this._bumpTexture === texture) { return true; } if (this._lightmapTexture === texture) { return true; } return this.subSurface.hasTexture(texture) || this.clearCoat.hasTexture(texture) || this.sheen.hasTexture(texture) || this.anisotropy.hasTexture(texture); }; /** * Disposes the resources of the material. * @param forceDisposeEffect - Forces the disposal of effects. * @param forceDisposeTextures - Forces the disposal of all textures. */ PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) { if (forceDisposeTextures) { if (this._albedoTexture) { this._albedoTexture.dispose(); } if (this._ambientTexture) { this._ambientTexture.dispose(); } if (this._opacityTexture) { this._opacityTexture.dispose(); } if (this._reflectionTexture) { this._reflectionTexture.dispose(); } if (this._environmentBRDFTexture && this.getScene().environmentBRDFTexture !== this._environmentBRDFTexture) { this._environmentBRDFTexture.dispose(); } if (this._emissiveTexture) { this._emissiveTexture.dispose(); } if (this._metallicTexture) { this._metallicTexture.dispose(); } if (this._reflectivityTexture) { this._reflectivityTexture.dispose(); } if (this._bumpTexture) { this._bumpTexture.dispose(); } if (this._lightmapTexture) { this._lightmapTexture.dispose(); } } this.subSurface.dispose(forceDisposeTextures); this.clearCoat.dispose(forceDisposeTextures); this.sheen.dispose(forceDisposeTextures); this.anisotropy.dispose(forceDisposeTextures); this._renderTargets.dispose(); if (this._imageProcessingConfiguration && this._imageProcessingObserver) { this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); } _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures); }; /** * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use. */ PBRBaseMaterial.PBRMATERIAL_OPAQUE = 0; /** * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value. */ PBRBaseMaterial.PBRMATERIAL_ALPHATEST = 1; /** * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer. */ PBRBaseMaterial.PBRMATERIAL_ALPHABLEND = 2; /** * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer. * They are also discarded below the alpha cutoff threshold to improve performances. */ PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3; /** * Defines the default value of how much AO map is occluding the analytical lights * (point spot...). */ PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 0; /** * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law. */ PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0; /** * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document * to enhance interoperability with other engines. */ PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1; /** * PBRMaterialLightFalloff Standard: light is falling off like in the standard material * to enhance interoperability with other materials. */ PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsImageProcessingConfiguration"])() ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsMiscDirty") ], PBRBaseMaterial.prototype, "debugMode", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRBaseMaterial.prototype, "transparencyMode", null); return PBRBaseMaterial; }(_Materials_pushMaterial__WEBPACK_IMPORTED_MODULE_16__["PushMaterial"])); /***/ }), /***/ "./Materials/PBR/pbrBaseSimpleMaterial.ts": /*!************************************************!*\ !*** ./Materials/PBR/pbrBaseSimpleMaterial.ts ***! \************************************************/ /*! exports provided: PBRBaseSimpleMaterial */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRBaseSimpleMaterial", function() { return PBRBaseSimpleMaterial; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./pbrBaseMaterial */ "./Materials/PBR/pbrBaseMaterial.ts"); /** * The Physically based simple base material of BJS. * * This enables better naming and convention enforcements on top of the pbrMaterial. * It is used as the base class for both the specGloss and metalRough conventions. */ var PBRBaseSimpleMaterial = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PBRBaseSimpleMaterial, _super); /** * Instantiates a new PBRMaterial instance. * * @param name The material name * @param scene The scene the material will be use in. */ function PBRBaseSimpleMaterial(name, scene) { var _this = _super.call(this, name, scene) || this; /** * Number of Simultaneous lights allowed on the material. */ _this.maxSimultaneousLights = 4; /** * If sets to true, disables all the lights affecting the material. */ _this.disableLighting = false; /** * If sets to true, x component of normal map value will invert (x = 1.0 - x). */ _this.invertNormalMapX = false; /** * If sets to true, y component of normal map value will invert (y = 1.0 - y). */ _this.invertNormalMapY = false; /** * Emissivie color used to self-illuminate the model. */ _this.emissiveColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"](0, 0, 0); /** * Occlusion Channel Strenght. */ _this.occlusionStrength = 1.0; /** * If true, the light map contains occlusion information instead of lighting info. */ _this.useLightmapAsShadowmap = false; _this._useAlphaFromAlbedoTexture = true; _this._useAmbientInGrayScale = true; return _this; } Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", { /** * Gets the current double sided mode. */ get: function () { return this._twoSidedLighting; }, /** * If sets to true and backfaceCulling is false, normals will be flipped on the backside. */ set: function (value) { if (this._twoSidedLighting === value) { return; } this._twoSidedLighting = value; this.backFaceCulling = !value; this._markAllSubMeshesAsTexturesDirty(); }, enumerable: true, configurable: true }); PBRBaseSimpleMaterial.prototype.getClassName = function () { return "PBRBaseSimpleMaterial"; }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsLightsDirty") ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsLightsDirty") ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture") ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_bumpTexture") ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])("emissive"), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength") ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_ambientTexture") ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff") ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRBaseSimpleMaterial.prototype, "doubleSided", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", null) ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0); return PBRBaseSimpleMaterial; }(_pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_3__["PBRBaseMaterial"])); /***/ }), /***/ "./Materials/PBR/pbrClearCoatConfiguration.ts": /*!****************************************************!*\ !*** ./Materials/PBR/pbrClearCoatConfiguration.ts ***! \****************************************************/ /*! exports provided: PBRClearCoatConfiguration */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRClearCoatConfiguration", function() { return PBRClearCoatConfiguration; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _materialFlags__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../materialFlags */ "./Materials/materialFlags.ts"); /* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/materialHelper */ "./Materials/materialHelper.ts"); /** * Define the code related to the clear coat parameters of the pbr material. */ var PBRClearCoatConfiguration = /** @class */ (function () { /** * Instantiate a new istance of clear coat configuration. * @param markAllSubMeshesAsTexturesDirty Callback to flag the material to dirty */ function PBRClearCoatConfiguration(markAllSubMeshesAsTexturesDirty) { this._isEnabled = false; /** * Defines if the clear coat is enabled in the material. */ this.isEnabled = false; /** * Defines the clear coat layer strength (between 0 and 1) it defaults to 1. */ this.intensity = 1; /** * Defines the clear coat layer roughness. */ this.roughness = 0; this._indiceOfRefraction = PBRClearCoatConfiguration._DefaultIndiceOfRefraction; /** * Defines the indice of refraction of the clear coat. * This defaults to 1.5 corresponding to a 0.04 f0 or a 4% reflectance at normal incidence * The default fits with a polyurethane material. * Changing the default value is more performance intensive. */ this.indiceOfRefraction = PBRClearCoatConfiguration._DefaultIndiceOfRefraction; this._texture = null; /** * Stores the clear coat values in a texture. */ this.texture = null; this._bumpTexture = null; /** * Define the clear coat specific bump texture. */ this.bumpTexture = null; this._isTintEnabled = false; /** * Defines if the clear coat tint is enabled in the material. */ this.isTintEnabled = false; /** * Defines the clear coat tint of the material. * This is only use if tint is enabled */ this.tintColor = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"].White(); /** * Defines the distance at which the tint color should be found in the * clear coat media. * This is only use if tint is enabled */ this.tintColorAtDistance = 1; /** * Defines the clear coat layer thickness. * This is only use if tint is enabled */ this.tintThickness = 1; this._tintTexture = null; /** * Stores the clear tint values in a texture. * rgb is tint * a is a thickness factor */ this.tintTexture = null; this._internalMarkAllSubMeshesAsTexturesDirty = markAllSubMeshesAsTexturesDirty; } /** @hidden */ PBRClearCoatConfiguration.prototype._markAllSubMeshesAsTexturesDirty = function () { this._internalMarkAllSubMeshesAsTexturesDirty(); }; /** * Gets wehter the submesh is ready to be used or not. * @param defines the list of "defines" to update. * @param scene defines the scene the material belongs to. * @param engine defines the engine the material belongs to. * @param disableBumpMap defines wether the material disables bump or not. * @returns - boolean indicating that the submesh is ready or not. */ PBRClearCoatConfiguration.prototype.isReadyForSubMesh = function (defines, scene, engine, disableBumpMap) { if (defines._areTexturesDirty) { if (scene.texturesEnabled) { if (this._texture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTextureEnabled) { if (!this._texture.isReadyOrNotBlocking()) { return false; } } if (engine.getCaps().standardDerivatives && this._bumpTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatBumpTextureEnabled && !disableBumpMap) { // Bump texture cannot be not blocking. if (!this._bumpTexture.isReady()) { return false; } } if (this._isTintEnabled && this._tintTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTintTextureEnabled) { if (!this._tintTexture.isReadyOrNotBlocking()) { return false; } } } } return true; }; /** * Checks to see if a texture is used in the material. * @param defines the list of "defines" to update. * @param scene defines the scene to the material belongs to. */ PBRClearCoatConfiguration.prototype.prepareDefines = function (defines, scene) { if (this._isEnabled) { defines.CLEARCOAT = true; if (defines._areTexturesDirty) { if (scene.texturesEnabled) { if (this._texture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTextureEnabled) { _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].PrepareDefinesForMergedUV(this._texture, defines, "CLEARCOAT_TEXTURE"); } else { defines.CLEARCOAT_TEXTURE = false; } if (this._bumpTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatBumpTextureEnabled) { _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].PrepareDefinesForMergedUV(this._bumpTexture, defines, "CLEARCOAT_BUMP"); } else { defines.CLEARCOAT_BUMP = false; } defines.CLEARCOAT_DEFAULTIOR = this._indiceOfRefraction === PBRClearCoatConfiguration._DefaultIndiceOfRefraction; if (this._isTintEnabled) { defines.CLEARCOAT_TINT = true; if (this._tintTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTintTextureEnabled) { _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].PrepareDefinesForMergedUV(this._tintTexture, defines, "CLEARCOAT_TINT_TEXTURE"); } else { defines.CLEARCOAT_TINT_TEXTURE = false; } } else { defines.CLEARCOAT_TINT = false; defines.CLEARCOAT_TINT_TEXTURE = false; } } } } else { defines.CLEARCOAT = false; defines.CLEARCOAT_TEXTURE = false; defines.CLEARCOAT_BUMP = false; defines.CLEARCOAT_TINT = false; defines.CLEARCOAT_TINT_TEXTURE = false; } }; /** * Binds the material data. * @param uniformBuffer defines the Uniform buffer to fill in. * @param scene defines the scene the material belongs to. * @param engine defines the engine the material belongs to. * @param disableBumpMap defines wether the material disables bump or not. * @param isFrozen defines wether the material is frozen or not. * @param invertNormalMapX If sets to true, x component of normal map value will be inverted (x = 1.0 - x). * @param invertNormalMapY If sets to true, y component of normal map value will be inverted (y = 1.0 - y). */ PBRClearCoatConfiguration.prototype.bindForSubMesh = function (uniformBuffer, scene, engine, disableBumpMap, isFrozen, invertNormalMapX, invertNormalMapY) { if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) { if (this._texture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTextureEnabled) { uniformBuffer.updateFloat2("vClearCoatInfos", this._texture.coordinatesIndex, this._texture.level); _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].BindTextureMatrix(this._texture, uniformBuffer, "clearCoat"); } if (this._bumpTexture && engine.getCaps().standardDerivatives && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTextureEnabled && !disableBumpMap) { uniformBuffer.updateFloat2("vClearCoatBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level); _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].BindTextureMatrix(this._bumpTexture, uniformBuffer, "clearCoatBump"); if (scene._mirroredCameraPosition) { uniformBuffer.updateFloat2("vClearCoatTangentSpaceParams", invertNormalMapX ? 1.0 : -1.0, invertNormalMapY ? 1.0 : -1.0); } else { uniformBuffer.updateFloat2("vClearCoatTangentSpaceParams", invertNormalMapX ? -1.0 : 1.0, invertNormalMapY ? -1.0 : 1.0); } } if (this._tintTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTintTextureEnabled) { uniformBuffer.updateFloat2("vClearCoatTintInfos", this._tintTexture.coordinatesIndex, this._tintTexture.level); _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].BindTextureMatrix(this._tintTexture, uniformBuffer, "clearCoatTint"); } // Clear Coat General params uniformBuffer.updateFloat2("vClearCoatParams", this.intensity, this.roughness); // Clear Coat Refraction params var a = 1 - this._indiceOfRefraction; var b = 1 + this._indiceOfRefraction; var f0 = Math.pow((-a / b), 2); // Schlicks approx: (ior1 - ior2) / (ior1 + ior2) where ior2 for air is close to vacuum = 1. var eta = 1 / this._indiceOfRefraction; uniformBuffer.updateFloat4("vClearCoatRefractionParams", f0, eta, a, b); if (this._isTintEnabled) { uniformBuffer.updateFloat4("vClearCoatTintParams", this.tintColor.r, this.tintColor.g, this.tintColor.b, Math.max(0.00001, this.tintThickness)); uniformBuffer.updateFloat("clearCoatColorAtDistance", Math.max(0.00001, this.tintColorAtDistance)); } } // Textures if (scene.texturesEnabled) { if (this._texture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTextureEnabled) { uniformBuffer.setTexture("clearCoatSampler", this._texture); } if (this._bumpTexture && engine.getCaps().standardDerivatives && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatBumpTextureEnabled && !disableBumpMap) { uniformBuffer.setTexture("clearCoatBumpSampler", this._bumpTexture); } if (this._isTintEnabled && this._tintTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTintTextureEnabled) { uniformBuffer.setTexture("clearCoatTintSampler", this._tintTexture); } } }; /** * Checks to see if a texture is used in the material. * @param texture - Base texture to use. * @returns - Boolean specifying if a texture is used in the material. */ PBRClearCoatConfiguration.prototype.hasTexture = function (texture) { if (this._texture === texture) { return true; } if (this._bumpTexture === texture) { return true; } if (this._tintTexture === texture) { return true; } return false; }; /** * Returns an array of the actively used textures. * @param activeTextures Array of BaseTextures */ PBRClearCoatConfiguration.prototype.getActiveTextures = function (activeTextures) { if (this._texture) { activeTextures.push(this._texture); } if (this._bumpTexture) { activeTextures.push(this._bumpTexture); } if (this._tintTexture) { activeTextures.push(this._tintTexture); } }; /** * Returns the animatable textures. * @param animatables Array of animatable textures. */ PBRClearCoatConfiguration.prototype.getAnimatables = function (animatables) { if (this._texture && this._texture.animations && this._texture.animations.length > 0) { animatables.push(this._texture); } if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) { animatables.push(this._bumpTexture); } if (this._tintTexture && this._tintTexture.animations && this._tintTexture.animations.length > 0) { animatables.push(this._tintTexture); } }; /** * Disposes the resources of the material. * @param forceDisposeTextures - Forces the disposal of all textures. */ PBRClearCoatConfiguration.prototype.dispose = function (forceDisposeTextures) { if (forceDisposeTextures) { if (this._texture) { this._texture.dispose(); } if (this._bumpTexture) { this._bumpTexture.dispose(); } if (this._tintTexture) { this._tintTexture.dispose(); } } }; /** * Get the current class name of the texture useful for serialization or dynamic coding. * @returns "PBRClearCoatConfiguration" */ PBRClearCoatConfiguration.prototype.getClassName = function () { return "PBRClearCoatConfiguration"; }; /** * Add fallbacks to the effect fallbacks list. * @param defines defines the Base texture to use. * @param fallbacks defines the current fallback list. * @param currentRank defines the current fallback rank. * @returns the new fallback rank. */ PBRClearCoatConfiguration.AddFallbacks = function (defines, fallbacks, currentRank) { if (defines.CLEARCOAT_BUMP) { fallbacks.addFallback(currentRank++, "CLEARCOAT_BUMP"); } if (defines.CLEARCOAT_TINT) { fallbacks.addFallback(currentRank++, "CLEARCOAT_TINT"); } if (defines.CLEARCOAT) { fallbacks.addFallback(currentRank++, "CLEARCOAT"); } return currentRank; }; /** * Add the required uniforms to the current list. * @param uniforms defines the current uniform list. */ PBRClearCoatConfiguration.AddUniforms = function (uniforms) { uniforms.push("vClearCoatTangentSpaceParams", "vClearCoatParams", "vClearCoatRefractionParams", "vClearCoatTintParams", "clearCoatColorAtDistance", "clearCoatMatrix", "clearCoatBumpMatrix", "clearCoatTintMatrix", "vClearCoatInfos", "vClearCoatBumpInfos", "vClearCoatTintInfos"); }; /** * Add the required samplers to the current list. * @param samplers defines the current sampler list. */ PBRClearCoatConfiguration.AddSamplers = function (samplers) { samplers.push("clearCoatSampler", "clearCoatBumpSampler", "clearCoatTintSampler"); }; /** * Add the required uniforms to the current buffer. * @param uniformBuffer defines the current uniform buffer. */ PBRClearCoatConfiguration.PrepareUniformBuffer = function (uniformBuffer) { uniformBuffer.addUniform("vClearCoatParams", 2); uniformBuffer.addUniform("vClearCoatRefractionParams", 4); uniformBuffer.addUniform("vClearCoatInfos", 2); uniformBuffer.addUniform("clearCoatMatrix", 16); uniformBuffer.addUniform("vClearCoatBumpInfos", 2); uniformBuffer.addUniform("vClearCoatTangentSpaceParams", 2); uniformBuffer.addUniform("clearCoatBumpMatrix", 16); uniformBuffer.addUniform("vClearCoatTintParams", 4); uniformBuffer.addUniform("clearCoatColorAtDistance", 1); uniformBuffer.addUniform("vClearCoatTintInfos", 2); uniformBuffer.addUniform("clearCoatTintMatrix", 16); }; /** * Makes a duplicate of the current configuration into another one. * @param clearCoatConfiguration define the config where to copy the info */ PBRClearCoatConfiguration.prototype.copyTo = function (clearCoatConfiguration) { _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return clearCoatConfiguration; }, this); }; /** * Serializes this clear coat configuration. * @returns - An object with the serialized config. */ PBRClearCoatConfiguration.prototype.serialize = function () { return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); }; /** * Parses a Clear Coat Configuration from a serialized object. * @param source - Serialized object. */ PBRClearCoatConfiguration.prototype.parse = function (source) { var _this = this; _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return _this; }, source, null); }; /** * This defaults to 1.5 corresponding to a 0.04 f0 or a 4% reflectance at normal incidence * The default fits with a polyurethane material. */ PBRClearCoatConfiguration._DefaultIndiceOfRefraction = 1.5; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRClearCoatConfiguration.prototype, "_isEnabled", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRClearCoatConfiguration.prototype, "isEnabled", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRClearCoatConfiguration.prototype, "intensity", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRClearCoatConfiguration.prototype, "roughness", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRClearCoatConfiguration.prototype, "_indiceOfRefraction", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRClearCoatConfiguration.prototype, "indiceOfRefraction", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])() ], PBRClearCoatConfiguration.prototype, "_texture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRClearCoatConfiguration.prototype, "texture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])() ], PBRClearCoatConfiguration.prototype, "_bumpTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRClearCoatConfiguration.prototype, "bumpTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRClearCoatConfiguration.prototype, "_isTintEnabled", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRClearCoatConfiguration.prototype, "isTintEnabled", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])() ], PBRClearCoatConfiguration.prototype, "tintColor", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRClearCoatConfiguration.prototype, "tintColorAtDistance", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRClearCoatConfiguration.prototype, "tintThickness", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])() ], PBRClearCoatConfiguration.prototype, "_tintTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRClearCoatConfiguration.prototype, "tintTexture", void 0); return PBRClearCoatConfiguration; }()); /***/ }), /***/ "./Materials/PBR/pbrMaterial.ts": /*!**************************************!*\ !*** ./Materials/PBR/pbrMaterial.ts ***! \**************************************/ /*! exports provided: PBRMaterial */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRMaterial", function() { return PBRMaterial; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Misc_brdfTextureTools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/brdfTextureTools */ "./Misc/brdfTextureTools.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./pbrBaseMaterial */ "./Materials/PBR/pbrBaseMaterial.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts"); /** * The Physically based material of BJS. * * This offers the main features of a standard PBR material. * For more information, please refer to the documentation : * http://doc.babylonjs.com/extensions/Physically_Based_Rendering */ var PBRMaterial = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PBRMaterial, _super); /** * Instantiates a new PBRMaterial instance. * * @param name The material name * @param scene The scene the material will be use in. */ function PBRMaterial(name, scene) { var _this = _super.call(this, name, scene) || this; /** * Intensity of the direct lights e.g. the four lights available in your scene. * This impacts both the direct diffuse and specular highlights. */ _this.directIntensity = 1.0; /** * Intensity of the emissive part of the material. * This helps controlling the emissive effect without modifying the emissive color. */ _this.emissiveIntensity = 1.0; /** * Intensity of the environment e.g. how much the environment will light the object * either through harmonics for rough material or through the refelction for shiny ones. */ _this.environmentIntensity = 1.0; /** * This is a special control allowing the reduction of the specular highlights coming from the * four lights of the scene. Those highlights may not be needed in full environment lighting. */ _this.specularIntensity = 1.0; /** * Debug Control allowing disabling the bump map on this material. */ _this.disableBumpMap = false; /** * AKA Occlusion Texture Intensity in other nomenclature. */ _this.ambientTextureStrength = 1.0; /** * Defines how much the AO map is occluding the analytical lights (point spot...). * 1 means it completely occludes it * 0 mean it has no impact */ _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS; /** * The color of a material in ambient lighting. */ _this.ambientColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"](0, 0, 0); /** * AKA Diffuse Color in other nomenclature. */ _this.albedoColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"](1, 1, 1); /** * AKA Specular Color in other nomenclature. */ _this.reflectivityColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"](1, 1, 1); /** * The color reflected from the material. */ _this.reflectionColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"](1.0, 1.0, 1.0); /** * The color emitted from the material. */ _this.emissiveColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Color3"](0, 0, 0); /** * AKA Glossiness in other nomenclature. */ _this.microSurface = 1.0; /** * If true, the light map contains occlusion information instead of lighting info. */ _this.useLightmapAsShadowmap = false; /** * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending. */ _this.useAlphaFromAlbedoTexture = false; /** * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations. */ _this.forceAlphaTest = false; /** * Defines the alpha limits in alpha test mode. */ _this.alphaCutOff = 0.4; /** * Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones). * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind. */ _this.useSpecularOverAlpha = true; /** * Specifies if the reflectivity texture contains the glossiness information in its alpha channel. */ _this.useMicroSurfaceFromReflectivityMapAlpha = false; /** * Specifies if the metallic texture contains the roughness information in its alpha channel. */ _this.useRoughnessFromMetallicTextureAlpha = true; /** * Specifies if the metallic texture contains the roughness information in its green channel. */ _this.useRoughnessFromMetallicTextureGreen = false; /** * Specifies if the metallic texture contains the metallness information in its blue channel. */ _this.useMetallnessFromMetallicTextureBlue = false; /** * Specifies if the metallic texture contains the ambient occlusion information in its red channel. */ _this.useAmbientOcclusionFromMetallicTextureRed = false; /** * Specifies if the ambient texture contains the ambient occlusion information in its red channel only. */ _this.useAmbientInGrayScale = false; /** * In case the reflectivity map does not contain the microsurface information in its alpha channel, * The material will try to infer what glossiness each pixel should be. */ _this.useAutoMicroSurfaceFromReflectivityMap = false; /** * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones). * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind. */ _this.useRadianceOverAlpha = true; /** * Allows using an object space normal map (instead of tangent space). */ _this.useObjectSpaceNormalMap = false; /** * Allows using the bump map in parallax mode. */ _this.useParallax = false; /** * Allows using the bump map in parallax occlusion mode. */ _this.useParallaxOcclusion = false; /** * Controls the scale bias of the parallax mode. */ _this.parallaxScaleBias = 0.05; /** * If sets to true, disables all the lights affecting the material. */ _this.disableLighting = false; /** * Force the shader to compute irradiance in the fragment shader in order to take bump in account. */ _this.forceIrradianceInFragment = false; /** * Number of Simultaneous lights allowed on the material. */ _this.maxSimultaneousLights = 4; /** * If sets to true, x component of normal map value will invert (x = 1.0 - x). */ _this.invertNormalMapX = false; /** * If sets to true, y component of normal map value will invert (y = 1.0 - y). */ _this.invertNormalMapY = false; /** * If sets to true and backfaceCulling is false, normals will be flipped on the backside. */ _this.twoSidedLighting = false; /** * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel) */ _this.useAlphaFresnel = false; /** * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel) */ _this.useLinearAlphaFresnel = false; /** * Let user defines the brdf lookup texture used for IBL. * A default 8bit version is embedded but you could point at : * * Default texture: https://assets.babylonjs.com/environments/correlatedMSBRDF.png * * Default 16bit pixel depth texture: https://assets.babylonjs.com/environments/correlatedMSBRDF.dds * * LEGACY Default None correlated https://assets.babylonjs.com/environments/uncorrelatedBRDF.png * * LEGACY Default None correlated 16bit pixel depth https://assets.babylonjs.com/environments/uncorrelatedBRDF.dds */ _this.environmentBRDFTexture = null; /** * Force normal to face away from face. */ _this.forceNormalForward = false; /** * Enables specular anti aliasing in the PBR shader. * It will both interacts on the Geometry for analytical and IBL lighting. * It also prefilter the roughness map based on the bump values. */ _this.enableSpecularAntiAliasing = false; /** * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal * makes the reflect vector face the model (under horizon). */ _this.useHorizonOcclusion = true; /** * This parameters will enable/disable radiance occlusion by preventing the radiance to lit * too much the area relying on ambient texture to define their ambient occlusion. */ _this.useRadianceOcclusion = true; /** * If set to true, no lighting calculations will be applied. */ _this.unlit = false; _this._environmentBRDFTexture = _Misc_brdfTextureTools__WEBPACK_IMPORTED_MODULE_2__["BRDFTextureTools"].GetEnvironmentBRDFTexture(scene); return _this; } Object.defineProperty(PBRMaterial.prototype, "refractionTexture", { /** * Stores the refracted light information in a texture. */ get: function () { return this.subSurface.refractionTexture; }, set: function (value) { this.subSurface.refractionTexture = value; if (value) { this.subSurface.isRefractionEnabled = true; } else if (!this.subSurface.linkRefractionWithTransparency) { this.subSurface.isRefractionEnabled = false; } }, enumerable: true, configurable: true }); Object.defineProperty(PBRMaterial.prototype, "indexOfRefraction", { /** * source material index of refraction (IOR)' / 'destination material IOR. */ get: function () { return 1 / this.subSurface.indexOfRefraction; }, set: function (value) { this.subSurface.indexOfRefraction = 1 / value; }, enumerable: true, configurable: true }); Object.defineProperty(PBRMaterial.prototype, "invertRefractionY", { /** * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture. */ get: function () { return this.subSurface.invertRefractionY; }, set: function (value) { this.subSurface.invertRefractionY = value; }, enumerable: true, configurable: true }); Object.defineProperty(PBRMaterial.prototype, "linkRefractionWithTransparency", { /** * This parameters will make the material used its opacity to control how much it is refracting aginst not. * Materials half opaque for instance using refraction could benefit from this control. */ get: function () { return this.subSurface.linkRefractionWithTransparency; }, set: function (value) { this.subSurface.linkRefractionWithTransparency = value; if (value) { this.subSurface.isRefractionEnabled = true; } }, enumerable: true, configurable: true }); Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", { /** * BJS is using an harcoded light falloff based on a manually sets up range. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials. */ get: function () { return this._lightFalloff === _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].LIGHTFALLOFF_PHYSICAL; }, /** * BJS is using an harcoded light falloff based on a manually sets up range. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials. */ set: function (value) { if (value !== this.usePhysicalLightFalloff) { // Ensure the effect will be rebuilt. this._markAllSubMeshesAsTexturesDirty(); if (value) { this._lightFalloff = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].LIGHTFALLOFF_PHYSICAL; } else { this._lightFalloff = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].LIGHTFALLOFF_STANDARD; } } }, enumerable: true, configurable: true }); Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", { /** * In order to support the falloff compatibility with gltf, a special mode has been added * to reproduce the gltf light falloff. */ get: function () { return this._lightFalloff === _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].LIGHTFALLOFF_GLTF; }, /** * In order to support the falloff compatibility with gltf, a special mode has been added * to reproduce the gltf light falloff. */ set: function (value) { if (value !== this.useGLTFLightFalloff) { // Ensure the effect will be rebuilt. this._markAllSubMeshesAsTexturesDirty(); if (value) { this._lightFalloff = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].LIGHTFALLOFF_GLTF; } else { this._lightFalloff = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].LIGHTFALLOFF_STANDARD; } } }, enumerable: true, configurable: true }); Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", { /** * Gets the image processing configuration used either in this material. */ get: function () { return this._imageProcessingConfiguration; }, /** * Sets the Default image processing configuration used either in the this material. * * If sets to null, the scene one is in use. */ set: function (value) { this._attachImageProcessingConfiguration(value); // Ensure the effect will be rebuilt. this._markAllSubMeshesAsTexturesDirty(); }, enumerable: true, configurable: true }); Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", { /** * Gets wether the color curves effect is enabled. */ get: function () { return this.imageProcessingConfiguration.colorCurvesEnabled; }, /** * Sets wether the color curves effect is enabled. */ set: function (value) { this.imageProcessingConfiguration.colorCurvesEnabled = value; }, enumerable: true, configurable: true }); Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", { /** * Gets wether the color grading effect is enabled. */ get: function () { return this.imageProcessingConfiguration.colorGradingEnabled; }, /** * Gets wether the color grading effect is enabled. */ set: function (value) { this.imageProcessingConfiguration.colorGradingEnabled = value; }, enumerable: true, configurable: true }); Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", { /** * Gets wether tonemapping is enabled or not. */ get: function () { return this._imageProcessingConfiguration.toneMappingEnabled; }, /** * Sets wether tonemapping is enabled or not */ set: function (value) { this._imageProcessingConfiguration.toneMappingEnabled = value; }, enumerable: true, configurable: true }); Object.defineProperty(PBRMaterial.prototype, "cameraExposure", { /** * The camera exposure used on this material. * This property is here and not in the camera to allow controlling exposure without full screen post process. * This corresponds to a photographic exposure. */ get: function () { return this._imageProcessingConfiguration.exposure; }, /** * The camera exposure used on this material. * This property is here and not in the camera to allow controlling exposure without full screen post process. * This corresponds to a photographic exposure. */ set: function (value) { this._imageProcessingConfiguration.exposure = value; }, enumerable: true, configurable: true }); Object.defineProperty(PBRMaterial.prototype, "cameraContrast", { /** * Gets The camera contrast used on this material. */ get: function () { return this._imageProcessingConfiguration.contrast; }, /** * Sets The camera contrast used on this material. */ set: function (value) { this._imageProcessingConfiguration.contrast = value; }, enumerable: true, configurable: true }); Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", { /** * Gets the Color Grading 2D Lookup Texture. */ get: function () { return this._imageProcessingConfiguration.colorGradingTexture; }, /** * Sets the Color Grading 2D Lookup Texture. */ set: function (value) { this._imageProcessingConfiguration.colorGradingTexture = value; }, enumerable: true, configurable: true }); Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", { /** * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; * corresponding to low luminance, medium luminance, and high luminance areas respectively. */ get: function () { return this._imageProcessingConfiguration.colorCurves; }, /** * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; * corresponding to low luminance, medium luminance, and high luminance areas respectively. */ set: function (value) { this._imageProcessingConfiguration.colorCurves = value; }, enumerable: true, configurable: true }); /** * Returns the name of this material class. */ PBRMaterial.prototype.getClassName = function () { return "PBRMaterial"; }; /** * Makes a duplicate of the current material. * @param name - name to use for the new material. */ PBRMaterial.prototype.clone = function (name) { var _this = this; var clone = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this); clone.id = name; clone.name = name; this.clearCoat.copyTo(clone.clearCoat); this.anisotropy.copyTo(clone.anisotropy); this.brdf.copyTo(clone.brdf); this.sheen.copyTo(clone.sheen); return clone; }; /** * Serializes this PBR Material. * @returns - An object with the serialized material. */ PBRMaterial.prototype.serialize = function () { var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); serializationObject.customType = "BABYLON.PBRMaterial"; serializationObject.clearCoat = this.clearCoat.serialize(); serializationObject.anisotropy = this.anisotropy.serialize(); serializationObject.brdf = this.brdf.serialize(); serializationObject.sheen = this.sheen.serialize(); return serializationObject; }; // Statics /** * Parses a PBR Material from a serialized object. * @param source - Serialized object. * @param scene - BJS scene instance. * @param rootUrl - url for the scene object * @returns - PBRMaterial */ PBRMaterial.Parse = function (source, scene, rootUrl) { var material = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl); if (source.clearCoat) { material.clearCoat.parse(source.clearCoat); } if (source.anisotropy) { material.anisotropy.parse(source.anisotropy); } if (source.brdf) { material.brdf.parse(source.brdf); } if (source.sheen) { material.sheen.parse(source.brdf); } return material; }; /** * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use. */ PBRMaterial.PBRMATERIAL_OPAQUE = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].PBRMATERIAL_OPAQUE; /** * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value. */ PBRMaterial.PBRMATERIAL_ALPHATEST = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].PBRMATERIAL_ALPHATEST; /** * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer. */ PBRMaterial.PBRMATERIAL_ALPHABLEND = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].PBRMATERIAL_ALPHABLEND; /** * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer. * They are also discarded below the alpha cutoff threshold to improve performances. */ PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].PBRMATERIAL_ALPHATESTANDBLEND; /** * Defines the default value of how much AO map is occluding the analytical lights * (point spot...). */ PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].DEFAULT_AO_ON_ANALYTICAL_LIGHTS; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "directIntensity", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "emissiveIntensity", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "environmentIntensity", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "specularIntensity", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "disableBumpMap", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "albedoTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "ambientTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "ambientTextureStrength", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesAndMiscDirty") ], PBRMaterial.prototype, "opacityTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "reflectionTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "emissiveTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "reflectivityTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "metallicTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "metallic", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "roughness", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "microSurfaceTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "bumpTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", null) ], PBRMaterial.prototype, "lightmapTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])("ambient"), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "ambientColor", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])("albedo"), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "albedoColor", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])("reflectivity"), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "reflectivityColor", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])("reflection"), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "reflectionColor", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])("emissive"), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "emissiveColor", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "microSurface", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesAndMiscDirty") ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesAndMiscDirty") ], PBRMaterial.prototype, "forceAlphaTest", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesAndMiscDirty") ], PBRMaterial.prototype, "alphaCutOff", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRMaterial.prototype, "usePhysicalLightFalloff", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRMaterial.prototype, "useGLTFLightFalloff", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "useParallax", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "useParallaxOcclusion", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "parallaxScaleBias", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsLightsDirty") ], PBRMaterial.prototype, "disableLighting", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsLightsDirty") ], PBRMaterial.prototype, "maxSimultaneousLights", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "invertNormalMapX", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "invertNormalMapY", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "twoSidedLighting", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "useAlphaFresnel", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "environmentBRDFTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "forceNormalForward", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "useHorizonOcclusion", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMaterial.prototype, "useRadianceOcclusion", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsMiscDirty") ], PBRMaterial.prototype, "unlit", void 0); return PBRMaterial; }(_pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"])); _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.PBRMaterial"] = PBRMaterial; /***/ }), /***/ "./Materials/PBR/pbrMetallicRoughnessMaterial.ts": /*!*******************************************************!*\ !*** ./Materials/PBR/pbrMetallicRoughnessMaterial.ts ***! \*******************************************************/ /*! exports provided: PBRMetallicRoughnessMaterial */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRMetallicRoughnessMaterial", function() { return PBRMetallicRoughnessMaterial; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _pbrBaseSimpleMaterial__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./pbrBaseSimpleMaterial */ "./Materials/PBR/pbrBaseSimpleMaterial.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts"); /** * The PBR material of BJS following the metal roughness convention. * * This fits to the PBR convention in the GLTF definition: * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0 */ var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PBRMetallicRoughnessMaterial, _super); /** * Instantiates a new PBRMetalRoughnessMaterial instance. * * @param name The material name * @param scene The scene the material will be use in. */ function PBRMetallicRoughnessMaterial(name, scene) { var _this = _super.call(this, name, scene) || this; _this._useRoughnessFromMetallicTextureAlpha = false; _this._useRoughnessFromMetallicTextureGreen = true; _this._useMetallnessFromMetallicTextureBlue = true; _this.metallic = 1.0; _this.roughness = 1.0; return _this; } /** * Return the currrent class name of the material. */ PBRMetallicRoughnessMaterial.prototype.getClassName = function () { return "PBRMetallicRoughnessMaterial"; }; /** * Makes a duplicate of the current material. * @param name - name to use for the new material. */ PBRMetallicRoughnessMaterial.prototype.clone = function (name) { var _this = this; var clone = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this); clone.id = name; clone.name = name; this.clearCoat.copyTo(clone.clearCoat); this.anisotropy.copyTo(clone.anisotropy); this.brdf.copyTo(clone.brdf); this.sheen.copyTo(clone.sheen); return clone; }; /** * Serialize the material to a parsable JSON object. */ PBRMetallicRoughnessMaterial.prototype.serialize = function () { var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial"; serializationObject.clearCoat = this.clearCoat.serialize(); serializationObject.anisotropy = this.anisotropy.serialize(); serializationObject.brdf = this.brdf.serialize(); serializationObject.sheen = this.sheen.serialize(); return serializationObject; }; /** * Parses a JSON object correponding to the serialize function. */ PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) { var material = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl); if (source.clearCoat) { material.clearCoat.parse(source.clearCoat); } if (source.anisotropy) { material.anisotropy.parse(source.anisotropy); } if (source.brdf) { material.brdf.parse(source.brdf); } if (source.sheen) { material.sheen.parse(source.brdf); } return material; }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_albedoColor") ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_albedoTexture") ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_metallicTexture") ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0); return PBRMetallicRoughnessMaterial; }(_pbrBaseSimpleMaterial__WEBPACK_IMPORTED_MODULE_2__["PBRBaseSimpleMaterial"])); _Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__["_TypeStore"].RegisteredTypes["BABYLON.PBRMetallicRoughnessMaterial"] = PBRMetallicRoughnessMaterial; /***/ }), /***/ "./Materials/PBR/pbrSheenConfiguration.ts": /*!************************************************!*\ !*** ./Materials/PBR/pbrSheenConfiguration.ts ***! \************************************************/ /*! exports provided: PBRSheenConfiguration */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRSheenConfiguration", function() { return PBRSheenConfiguration; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Materials/materialFlags */ "./Materials/materialFlags.ts"); /* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/materialHelper */ "./Materials/materialHelper.ts"); /** * Define the code related to the Sheen parameters of the pbr material. */ var PBRSheenConfiguration = /** @class */ (function () { /** * Instantiate a new istance of clear coat configuration. * @param markAllSubMeshesAsTexturesDirty Callback to flag the material to dirty */ function PBRSheenConfiguration(markAllSubMeshesAsTexturesDirty) { this._isEnabled = false; /** * Defines if the material uses sheen. */ this.isEnabled = false; this._linkSheenWithAlbedo = false; /** * Defines if the sheen is linked to the sheen color. */ this.linkSheenWithAlbedo = false; /** * Defines the sheen intensity. */ this.intensity = 1; /** * Defines the sheen color. */ this.color = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"].White(); this._texture = null; /** * Stores the sheen tint values in a texture. * rgb is tint * a is a intensity */ this.texture = null; this._internalMarkAllSubMeshesAsTexturesDirty = markAllSubMeshesAsTexturesDirty; } /** @hidden */ PBRSheenConfiguration.prototype._markAllSubMeshesAsTexturesDirty = function () { this._internalMarkAllSubMeshesAsTexturesDirty(); }; /** * Specifies that the submesh is ready to be used. * @param defines the list of "defines" to update. * @param scene defines the scene the material belongs to. * @returns - boolean indicating that the submesh is ready or not. */ PBRSheenConfiguration.prototype.isReadyForSubMesh = function (defines, scene) { if (defines._areTexturesDirty) { if (scene.texturesEnabled) { if (this._texture && _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].SheenTextureEnabled) { if (!this._texture.isReadyOrNotBlocking()) { return false; } } } } return true; }; /** * Checks to see if a texture is used in the material. * @param defines the list of "defines" to update. * @param scene defines the scene the material belongs to. */ PBRSheenConfiguration.prototype.prepareDefines = function (defines, scene) { if (this._isEnabled) { defines.SHEEN = this._isEnabled; defines.SHEEN_LINKWITHALBEDO = this._linkSheenWithAlbedo; if (defines._areTexturesDirty) { if (scene.texturesEnabled) { if (this._texture && _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].SheenTextureEnabled) { _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].PrepareDefinesForMergedUV(this._texture, defines, "SHEEN_TEXTURE"); } else { defines.SHEEN_TEXTURE = false; } } } } else { defines.SHEEN = false; defines.SHEEN_TEXTURE = false; defines.SHEEN_LINKWITHALBEDO = false; } }; /** * Binds the material data. * @param uniformBuffer defines the Uniform buffer to fill in. * @param scene defines the scene the material belongs to. * @param isFrozen defines wether the material is frozen or not. */ PBRSheenConfiguration.prototype.bindForSubMesh = function (uniformBuffer, scene, isFrozen) { if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) { if (this._texture && _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].SheenTextureEnabled) { uniformBuffer.updateFloat2("vSheenInfos", this._texture.coordinatesIndex, this._texture.level); _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].BindTextureMatrix(this._texture, uniformBuffer, "sheen"); } // Sheen uniformBuffer.updateFloat4("vSheenColor", this.color.r, this.color.g, this.color.b, this.intensity); } // Textures if (scene.texturesEnabled) { if (this._texture && _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].SheenTextureEnabled) { uniformBuffer.setTexture("sheenSampler", this._texture); } } }; /** * Checks to see if a texture is used in the material. * @param texture - Base texture to use. * @returns - Boolean specifying if a texture is used in the material. */ PBRSheenConfiguration.prototype.hasTexture = function (texture) { if (this._texture === texture) { return true; } return false; }; /** * Returns an array of the actively used textures. * @param activeTextures Array of BaseTextures */ PBRSheenConfiguration.prototype.getActiveTextures = function (activeTextures) { if (this._texture) { activeTextures.push(this._texture); } }; /** * Returns the animatable textures. * @param animatables Array of animatable textures. */ PBRSheenConfiguration.prototype.getAnimatables = function (animatables) { if (this._texture && this._texture.animations && this._texture.animations.length > 0) { animatables.push(this._texture); } }; /** * Disposes the resources of the material. * @param forceDisposeTextures - Forces the disposal of all textures. */ PBRSheenConfiguration.prototype.dispose = function (forceDisposeTextures) { if (forceDisposeTextures) { if (this._texture) { this._texture.dispose(); } } }; /** * Get the current class name of the texture useful for serialization or dynamic coding. * @returns "PBRSheenConfiguration" */ PBRSheenConfiguration.prototype.getClassName = function () { return "PBRSheenConfiguration"; }; /** * Add fallbacks to the effect fallbacks list. * @param defines defines the Base texture to use. * @param fallbacks defines the current fallback list. * @param currentRank defines the current fallback rank. * @returns the new fallback rank. */ PBRSheenConfiguration.AddFallbacks = function (defines, fallbacks, currentRank) { if (defines.SHEEN) { fallbacks.addFallback(currentRank++, "SHEEN"); } return currentRank; }; /** * Add the required uniforms to the current list. * @param uniforms defines the current uniform list. */ PBRSheenConfiguration.AddUniforms = function (uniforms) { uniforms.push("vSheenColor", "vSheenInfos", "sheenMatrix"); }; /** * Add the required uniforms to the current buffer. * @param uniformBuffer defines the current uniform buffer. */ PBRSheenConfiguration.PrepareUniformBuffer = function (uniformBuffer) { uniformBuffer.addUniform("vSheenColor", 4); uniformBuffer.addUniform("vSheenInfos", 2); uniformBuffer.addUniform("sheenMatrix", 16); }; /** * Add the required samplers to the current list. * @param samplers defines the current sampler list. */ PBRSheenConfiguration.AddSamplers = function (samplers) { samplers.push("sheenSampler"); }; /** * Makes a duplicate of the current configuration into another one. * @param sheenConfiguration define the config where to copy the info */ PBRSheenConfiguration.prototype.copyTo = function (sheenConfiguration) { _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return sheenConfiguration; }, this); }; /** * Serializes this BRDF configuration. * @returns - An object with the serialized config. */ PBRSheenConfiguration.prototype.serialize = function () { return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); }; /** * Parses a Sheen Configuration from a serialized object. * @param source - Serialized object. */ PBRSheenConfiguration.prototype.parse = function (source) { var _this = this; _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return _this; }, source, null); }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRSheenConfiguration.prototype, "_isEnabled", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRSheenConfiguration.prototype, "isEnabled", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRSheenConfiguration.prototype, "_linkSheenWithAlbedo", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRSheenConfiguration.prototype, "linkSheenWithAlbedo", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRSheenConfiguration.prototype, "intensity", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])() ], PBRSheenConfiguration.prototype, "color", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])() ], PBRSheenConfiguration.prototype, "_texture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRSheenConfiguration.prototype, "texture", void 0); return PBRSheenConfiguration; }()); /***/ }), /***/ "./Materials/PBR/pbrSpecularGlossinessMaterial.ts": /*!********************************************************!*\ !*** ./Materials/PBR/pbrSpecularGlossinessMaterial.ts ***! \********************************************************/ /*! exports provided: PBRSpecularGlossinessMaterial */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRSpecularGlossinessMaterial", function() { return PBRSpecularGlossinessMaterial; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _pbrBaseSimpleMaterial__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./pbrBaseSimpleMaterial */ "./Materials/PBR/pbrBaseSimpleMaterial.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts"); /** * The PBR material of BJS following the specular glossiness convention. * * This fits to the PBR convention in the GLTF definition: * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness */ var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PBRSpecularGlossinessMaterial, _super); /** * Instantiates a new PBRSpecularGlossinessMaterial instance. * * @param name The material name * @param scene The scene the material will be use in. */ function PBRSpecularGlossinessMaterial(name, scene) { var _this = _super.call(this, name, scene) || this; _this._useMicroSurfaceFromReflectivityMapAlpha = true; return _this; } /** * Return the currrent class name of the material. */ PBRSpecularGlossinessMaterial.prototype.getClassName = function () { return "PBRSpecularGlossinessMaterial"; }; /** * Makes a duplicate of the current material. * @param name - name to use for the new material. */ PBRSpecularGlossinessMaterial.prototype.clone = function (name) { var _this = this; var clone = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this); clone.id = name; clone.name = name; this.clearCoat.copyTo(clone.clearCoat); this.anisotropy.copyTo(clone.anisotropy); this.brdf.copyTo(clone.brdf); this.sheen.copyTo(clone.sheen); return clone; }; /** * Serialize the material to a parsable JSON object. */ PBRSpecularGlossinessMaterial.prototype.serialize = function () { var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial"; serializationObject.clearCoat = this.clearCoat.serialize(); serializationObject.anisotropy = this.anisotropy.serialize(); serializationObject.brdf = this.brdf.serialize(); serializationObject.sheen = this.sheen.serialize(); return serializationObject; }; /** * Parses a JSON object correponding to the serialize function. */ PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) { var material = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl); if (source.clearCoat) { material.clearCoat.parse(source.clearCoat); } if (source.anisotropy) { material.anisotropy.parse(source.anisotropy); } if (source.brdf) { material.brdf.parse(source.brdf); } if (source.sheen) { material.sheen.parse(source.brdf); } return material; }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])("diffuse"), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_albedoColor") ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_albedoTexture") ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])("specular"), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor") ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_microSurface") ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture") ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0); return PBRSpecularGlossinessMaterial; }(_pbrBaseSimpleMaterial__WEBPACK_IMPORTED_MODULE_2__["PBRBaseSimpleMaterial"])); _Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__["_TypeStore"].RegisteredTypes["BABYLON.PBRSpecularGlossinessMaterial"] = PBRSpecularGlossinessMaterial; /***/ }), /***/ "./Materials/PBR/pbrSubSurfaceConfiguration.ts": /*!*****************************************************!*\ !*** ./Materials/PBR/pbrSubSurfaceConfiguration.ts ***! \*****************************************************/ /*! exports provided: PBRSubSurfaceConfiguration */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRSubSurfaceConfiguration", function() { return PBRSubSurfaceConfiguration; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _materialFlags__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../materialFlags */ "./Materials/materialFlags.ts"); /* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/materialHelper */ "./Materials/materialHelper.ts"); /** * Define the code related to the sub surface parameters of the pbr material. */ var PBRSubSurfaceConfiguration = /** @class */ (function () { /** * Instantiate a new istance of sub surface configuration. * @param markAllSubMeshesAsTexturesDirty Callback to flag the material to dirty */ function PBRSubSurfaceConfiguration(markAllSubMeshesAsTexturesDirty) { this._isRefractionEnabled = false; /** * Defines if the refraction is enabled in the material. */ this.isRefractionEnabled = false; this._isTranslucencyEnabled = false; /** * Defines if the translucency is enabled in the material. */ this.isTranslucencyEnabled = false; this._isScatteringEnabled = false; // /** // * Defines if the sub surface scattering is enabled in the material. // */ // @expandToProperty("_markAllSubMeshesAsTexturesDirty") // public isScatteringEnabled = false; /** * Defines the refraction intensity of the material. * The refraction when enabled replaces the Diffuse part of the material. * The intensity helps transitionning between diffuse and refraction. */ this.refractionIntensity = 1; /** * Defines the translucency intensity of the material. * When translucency has been enabled, this defines how much of the "translucency" * is addded to the diffuse part of the material. */ this.translucencyIntensity = 1; /** * Defines the scattering intensity of the material. * When scattering has been enabled, this defines how much of the "scattered light" * is addded to the diffuse part of the material. */ this.scatteringIntensity = 1; this._thicknessTexture = null; /** * Stores the average thickness of a mesh in a texture (The texture is holding the values linearly). * The red channel of the texture should contain the thickness remapped between 0 and 1. * 0 would mean minimumThickness * 1 would mean maximumThickness * The other channels might be use as a mask to vary the different effects intensity. */ this.thicknessTexture = null; this._refractionTexture = null; /** * Defines the texture to use for refraction. */ this.refractionTexture = null; this._indexOfRefraction = 1; /** * Defines the indice of refraction used in the material. * https://en.wikipedia.org/wiki/List_of_refractive_indices */ this.indexOfRefraction = 1; this._invertRefractionY = false; /** * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture. */ this.invertRefractionY = false; this._linkRefractionWithTransparency = false; /** * This parameters will make the material used its opacity to control how much it is refracting aginst not. * Materials half opaque for instance using refraction could benefit from this control. */ this.linkRefractionWithTransparency = false; /** * Defines the minimum thickness stored in the thickness map. * If no thickness map is defined, this value will be used to simulate thickness. */ this.minimumThickness = 0; /** * Defines the maximum thickness stored in the thickness map. */ this.maximumThickness = 1; /** * Defines the volume tint of the material. * This is used for both translucency and scattering. */ this.tintColor = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"].White(); /** * Defines the distance at which the tint color should be found in the media. * This is used for refraction only. */ this.tintColorAtDistance = 1; /** * Defines how far each channel transmit through the media. * It is defined as a color to simplify it selection. */ this.diffusionDistance = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"].White(); this._useMaskFromThicknessTexture = false; /** * Stores the intensity of the different subsurface effects in the thickness texture. * * the green channel is the translucency intensity. * * the blue channel is the scattering intensity. * * the alpha channel is the refraction intensity. */ this.useMaskFromThicknessTexture = false; this._internalMarkAllSubMeshesAsTexturesDirty = markAllSubMeshesAsTexturesDirty; } /** @hidden */ PBRSubSurfaceConfiguration.prototype._markAllSubMeshesAsTexturesDirty = function () { this._internalMarkAllSubMeshesAsTexturesDirty(); }; /** * Gets wehter the submesh is ready to be used or not. * @param defines the list of "defines" to update. * @param scene defines the scene the material belongs to. * @returns - boolean indicating that the submesh is ready or not. */ PBRSubSurfaceConfiguration.prototype.isReadyForSubMesh = function (defines, scene) { if (defines._areTexturesDirty) { if (scene.texturesEnabled) { if (this._thicknessTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ThicknessTextureEnabled) { if (!this._thicknessTexture.isReadyOrNotBlocking()) { return false; } } var refractionTexture = this._getRefractionTexture(scene); if (refractionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].RefractionTextureEnabled) { if (!refractionTexture.isReadyOrNotBlocking()) { return false; } } } } return true; }; /** * Checks to see if a texture is used in the material. * @param defines the list of "defines" to update. * @param scene defines the scene to the material belongs to. */ PBRSubSurfaceConfiguration.prototype.prepareDefines = function (defines, scene) { if (defines._areTexturesDirty) { defines.SUBSURFACE = false; defines.SS_TRANSLUCENCY = this._isTranslucencyEnabled; defines.SS_SCATERRING = this._isScatteringEnabled; defines.SS_THICKNESSANDMASK_TEXTURE = false; defines.SS_MASK_FROM_THICKNESS_TEXTURE = false; defines.SS_REFRACTION = false; defines.SS_REFRACTIONMAP_3D = false; defines.SS_GAMMAREFRACTION = false; defines.SS_RGBDREFRACTION = false; defines.SS_REFRACTIONMAP_OPPOSITEZ = false; defines.SS_LODINREFRACTIONALPHA = false; defines.SS_LINKREFRACTIONTOTRANSPARENCY = false; if (this._isRefractionEnabled || this._isTranslucencyEnabled || this._isScatteringEnabled) { defines.SUBSURFACE = true; if (defines._areTexturesDirty) { if (scene.texturesEnabled) { if (this._thicknessTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ThicknessTextureEnabled) { _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].PrepareDefinesForMergedUV(this._thicknessTexture, defines, "SS_THICKNESSANDMASK_TEXTURE"); } } } defines.SS_MASK_FROM_THICKNESS_TEXTURE = this._useMaskFromThicknessTexture; } if (this._isRefractionEnabled) { if (scene.texturesEnabled) { var refractionTexture = this._getRefractionTexture(scene); if (refractionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].RefractionTextureEnabled) { defines.SS_REFRACTION = true; defines.SS_REFRACTIONMAP_3D = refractionTexture.isCube; defines.SS_GAMMAREFRACTION = refractionTexture.gammaSpace; defines.SS_RGBDREFRACTION = refractionTexture.isRGBD; defines.SS_REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ; defines.SS_LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha; defines.SS_LINKREFRACTIONTOTRANSPARENCY = this._linkRefractionWithTransparency; } } } } }; /** * Binds the material data. * @param uniformBuffer defines the Uniform buffer to fill in. * @param scene defines the scene the material belongs to. * @param engine defines the engine the material belongs to. * @param isFrozen defines wether the material is frozen or not. * @param lodBasedMicrosurface defines wether the material relies on lod based microsurface or not. */ PBRSubSurfaceConfiguration.prototype.bindForSubMesh = function (uniformBuffer, scene, engine, isFrozen, lodBasedMicrosurface) { var refractionTexture = this._getRefractionTexture(scene); if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) { if (this._thicknessTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ThicknessTextureEnabled) { uniformBuffer.updateFloat2("vThicknessInfos", this._thicknessTexture.coordinatesIndex, this._thicknessTexture.level); _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].BindTextureMatrix(this._thicknessTexture, uniformBuffer, "thickness"); } uniformBuffer.updateFloat2("vThicknessParam", this.minimumThickness, this.maximumThickness - this.minimumThickness); if (refractionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].RefractionTextureEnabled) { uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix()); var depth = 1.0; if (!refractionTexture.isCube) { if (refractionTexture.depth) { depth = refractionTexture.depth; } } uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, 1 / this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1); uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset); } uniformBuffer.updateColor3("vDiffusionDistance", this.diffusionDistance); uniformBuffer.updateFloat4("vTintColor", this.tintColor.r, this.tintColor.g, this.tintColor.b, this.tintColorAtDistance); uniformBuffer.updateFloat3("vSubSurfaceIntensity", this.refractionIntensity, this.translucencyIntensity, this.scatteringIntensity); } // Textures if (scene.texturesEnabled) { if (this._thicknessTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ThicknessTextureEnabled) { uniformBuffer.setTexture("thicknessSampler", this._thicknessTexture); } if (refractionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].RefractionTextureEnabled) { if (lodBasedMicrosurface) { uniformBuffer.setTexture("refractionSampler", refractionTexture); } else { uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture); uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture); uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture); } } } }; /** * Unbinds the material from the mesh. * @param activeEffect defines the effect that should be unbound from. * @returns true if unbound, otherwise false */ PBRSubSurfaceConfiguration.prototype.unbind = function (activeEffect) { if (this._refractionTexture && this._refractionTexture.isRenderTarget) { activeEffect.setTexture("refractionSampler", null); return true; } return false; }; /** * Returns the texture used for refraction or null if none is used. * @param scene defines the scene the material belongs to. * @returns - Refraction texture if present. If no refraction texture and refraction * is linked with transparency, returns environment texture. Otherwise, returns null. */ PBRSubSurfaceConfiguration.prototype._getRefractionTexture = function (scene) { if (this._refractionTexture) { return this._refractionTexture; } if (this._isRefractionEnabled) { return scene.environmentTexture; } return null; }; Object.defineProperty(PBRSubSurfaceConfiguration.prototype, "disableAlphaBlending", { /** * Returns true if alpha blending should be disabled. */ get: function () { return this.isRefractionEnabled && this._linkRefractionWithTransparency; }, enumerable: true, configurable: true }); /** * Fills the list of render target textures. * @param renderTargets the list of render targets to update */ PBRSubSurfaceConfiguration.prototype.fillRenderTargetTextures = function (renderTargets) { if (_materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) { renderTargets.push(this._refractionTexture); } }; /** * Checks to see if a texture is used in the material. * @param texture - Base texture to use. * @returns - Boolean specifying if a texture is used in the material. */ PBRSubSurfaceConfiguration.prototype.hasTexture = function (texture) { if (this._thicknessTexture === texture) { return true; } if (this._refractionTexture === texture) { return true; } return false; }; /** * Gets a boolean indicating that current material needs to register RTT * @returns true if this uses a render target otherwise false. */ PBRSubSurfaceConfiguration.prototype.hasRenderTargetTextures = function () { if (_materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) { return true; } return false; }; /** * Returns an array of the actively used textures. * @param activeTextures Array of BaseTextures */ PBRSubSurfaceConfiguration.prototype.getActiveTextures = function (activeTextures) { if (this._thicknessTexture) { activeTextures.push(this._thicknessTexture); } if (this._refractionTexture) { activeTextures.push(this._refractionTexture); } }; /** * Returns the animatable textures. * @param animatables Array of animatable textures. */ PBRSubSurfaceConfiguration.prototype.getAnimatables = function (animatables) { if (this._thicknessTexture && this._thicknessTexture.animations && this._thicknessTexture.animations.length > 0) { animatables.push(this._thicknessTexture); } if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) { animatables.push(this._refractionTexture); } }; /** * Disposes the resources of the material. * @param forceDisposeTextures - Forces the disposal of all textures. */ PBRSubSurfaceConfiguration.prototype.dispose = function (forceDisposeTextures) { if (forceDisposeTextures) { if (this._thicknessTexture) { this._thicknessTexture.dispose(); } if (this._refractionTexture) { this._refractionTexture.dispose(); } } }; /** * Get the current class name of the texture useful for serialization or dynamic coding. * @returns "PBRSubSurfaceConfiguration" */ PBRSubSurfaceConfiguration.prototype.getClassName = function () { return "PBRSubSurfaceConfiguration"; }; /** * Add fallbacks to the effect fallbacks list. * @param defines defines the Base texture to use. * @param fallbacks defines the current fallback list. * @param currentRank defines the current fallback rank. * @returns the new fallback rank. */ PBRSubSurfaceConfiguration.AddFallbacks = function (defines, fallbacks, currentRank) { if (defines.SS_SCATERRING) { fallbacks.addFallback(currentRank++, "SS_SCATERRING"); } if (defines.SS_TRANSLUCENCY) { fallbacks.addFallback(currentRank++, "SS_TRANSLUCENCY"); } return currentRank; }; /** * Add the required uniforms to the current list. * @param uniforms defines the current uniform list. */ PBRSubSurfaceConfiguration.AddUniforms = function (uniforms) { uniforms.push("vDiffusionDistance", "vTintColor", "vSubSurfaceIntensity", "vRefractionMicrosurfaceInfos", "vRefractionInfos", "vThicknessInfos", "vThicknessParam", "refractionMatrix", "thicknessMatrix"); }; /** * Add the required samplers to the current list. * @param samplers defines the current sampler list. */ PBRSubSurfaceConfiguration.AddSamplers = function (samplers) { samplers.push("thicknessSampler", "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh"); }; /** * Add the required uniforms to the current buffer. * @param uniformBuffer defines the current uniform buffer. */ PBRSubSurfaceConfiguration.PrepareUniformBuffer = function (uniformBuffer) { uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3); uniformBuffer.addUniform("vRefractionInfos", 4); uniformBuffer.addUniform("refractionMatrix", 16); uniformBuffer.addUniform("vThicknessInfos", 2); uniformBuffer.addUniform("thicknessMatrix", 16); uniformBuffer.addUniform("vThicknessParam", 2); uniformBuffer.addUniform("vDiffusionDistance", 3); uniformBuffer.addUniform("vTintColor", 4); uniformBuffer.addUniform("vSubSurfaceIntensity", 3); }; /** * Makes a duplicate of the current configuration into another one. * @param configuration define the config where to copy the info */ PBRSubSurfaceConfiguration.prototype.copyTo = function (configuration) { _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return configuration; }, this); }; /** * Serializes this Sub Surface configuration. * @returns - An object with the serialized config. */ PBRSubSurfaceConfiguration.prototype.serialize = function () { return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); }; /** * Parses a Sub Surface Configuration from a serialized object. * @param source - Serialized object. */ PBRSubSurfaceConfiguration.prototype.parse = function (source) { var _this = this; _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return _this; }, source, null); }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRSubSurfaceConfiguration.prototype, "_isRefractionEnabled", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRSubSurfaceConfiguration.prototype, "isRefractionEnabled", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRSubSurfaceConfiguration.prototype, "_isTranslucencyEnabled", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRSubSurfaceConfiguration.prototype, "isTranslucencyEnabled", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRSubSurfaceConfiguration.prototype, "_isScatteringEnabled", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRSubSurfaceConfiguration.prototype, "refractionIntensity", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRSubSurfaceConfiguration.prototype, "translucencyIntensity", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRSubSurfaceConfiguration.prototype, "scatteringIntensity", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])() ], PBRSubSurfaceConfiguration.prototype, "_thicknessTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRSubSurfaceConfiguration.prototype, "thicknessTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRSubSurfaceConfiguration.prototype, "refractionTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRSubSurfaceConfiguration.prototype, "indexOfRefraction", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRSubSurfaceConfiguration.prototype, "invertRefractionY", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(), Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRSubSurfaceConfiguration.prototype, "linkRefractionWithTransparency", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRSubSurfaceConfiguration.prototype, "minimumThickness", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRSubSurfaceConfiguration.prototype, "maximumThickness", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])() ], PBRSubSurfaceConfiguration.prototype, "tintColor", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRSubSurfaceConfiguration.prototype, "tintColorAtDistance", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])() ], PBRSubSurfaceConfiguration.prototype, "diffusionDistance", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], PBRSubSurfaceConfiguration.prototype, "_useMaskFromThicknessTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty") ], PBRSubSurfaceConfiguration.prototype, "useMaskFromThicknessTexture", void 0); return PBRSubSurfaceConfiguration; }()); /***/ }), /***/ "./Materials/Textures/Loaders/ddsTextureLoader.ts": /*!********************************************************!*\ !*** ./Materials/Textures/Loaders/ddsTextureLoader.ts ***! \********************************************************/ /*! exports provided: _DDSTextureLoader */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_DDSTextureLoader", function() { return _DDSTextureLoader; }); /* harmony import */ var _Maths_sphericalPolynomial__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../Maths/sphericalPolynomial */ "./Maths/sphericalPolynomial.ts"); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../Engines/engine */ "./Engines/engine.ts"); /* harmony import */ var _Misc_dds__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../Misc/dds */ "./Misc/dds.ts"); /** * Implementation of the DDS Texture Loader. * @hidden */ var _DDSTextureLoader = /** @class */ (function () { function _DDSTextureLoader() { /** * Defines wether the loader supports cascade loading the different faces. */ this.supportCascades = true; } /** * This returns if the loader support the current file information. * @param extension defines the file extension of the file being loaded * @param textureFormatInUse defines the current compressed format in use iun the engine * @param fallback defines the fallback internal texture if any * @param isBase64 defines whether the texture is encoded as a base64 * @param isBuffer defines whether the texture data are stored as a buffer * @returns true if the loader can load the specified file */ _DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) { return extension.indexOf(".dds") === 0; }; /** * Transform the url before loading if required. * @param rootUrl the url of the texture * @param textureFormatInUse defines the current compressed format in use iun the engine * @returns the transformed texture */ _DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) { return rootUrl; }; /** * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work * @param rootUrl the url of the texture * @param textureFormatInUse defines the current compressed format in use iun the engine * @returns the fallback texture */ _DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) { return null; }; /** * Uploads the cube texture data to the WebGl Texture. It has alreday 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 */ _DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) { var engine = texture.getEngine(); var info; var loadMipmap = false; if (Array.isArray(imgs)) { for (var index = 0; index < imgs.length; index++) { var data_1 = imgs[index]; info = _Misc_dds__WEBPACK_IMPORTED_MODULE_2__["DDSTools"].GetDDSInfo(data_1); texture.width = info.width; texture.height = info.height; loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps; engine._unpackFlipY(info.isCompressed); _Misc_dds__WEBPACK_IMPORTED_MODULE_2__["DDSTools"].UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index); if (!info.isFourCC && info.mipmapCount === 1) { engine.generateMipMapsForCubemap(texture); } } } else { var data = imgs; info = _Misc_dds__WEBPACK_IMPORTED_MODULE_2__["DDSTools"].GetDDSInfo(data); texture.width = info.width; texture.height = info.height; if (createPolynomials) { info.sphericalPolynomial = new _Maths_sphericalPolynomial__WEBPACK_IMPORTED_MODULE_0__["SphericalPolynomial"](); } loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps; engine._unpackFlipY(info.isCompressed); _Misc_dds__WEBPACK_IMPORTED_MODULE_2__["DDSTools"].UploadDDSLevels(engine, texture, data, info, loadMipmap, 6); if (!info.isFourCC && info.mipmapCount === 1) { engine.generateMipMapsForCubemap(texture); } } engine._setCubeMapTextureParams(loadMipmap); texture.isReady = true; if (onLoad) { onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture }); } }; /** * Uploads the 2D texture data to the WebGl Texture. It has alreday 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 */ _DDSTextureLoader.prototype.loadData = function (data, texture, callback) { var info = _Misc_dds__WEBPACK_IMPORTED_MODULE_2__["DDSTools"].GetDDSInfo(data); var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1); callback(info.width, info.height, loadMipmap, info.isFourCC, function () { _Misc_dds__WEBPACK_IMPORTED_MODULE_2__["DDSTools"].UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1); }); }; return _DDSTextureLoader; }()); // Register the loader. _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"]._TextureLoaders.push(new _DDSTextureLoader()); /***/ }), /***/ "./Materials/Textures/Loaders/envTextureLoader.ts": /*!********************************************************!*\ !*** ./Materials/Textures/Loaders/envTextureLoader.ts ***! \********************************************************/ /*! exports provided: _ENVTextureLoader */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_ENVTextureLoader", function() { return _ENVTextureLoader; }); /* harmony import */ var _Misc_environmentTextureTools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../Misc/environmentTextureTools */ "./Misc/environmentTextureTools.ts"); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../Engines/engine */ "./Engines/engine.ts"); /** * Implementation of the ENV Texture Loader. * @hidden */ var _ENVTextureLoader = /** @class */ (function () { function _ENVTextureLoader() { /** * Defines wether the loader supports cascade loading the different faces. */ this.supportCascades = false; } /** * This returns if the loader support the current file information. * @param extension defines the file extension of the file being loaded * @param textureFormatInUse defines the current compressed format in use iun the engine * @param fallback defines the fallback internal texture if any * @param isBase64 defines whether the texture is encoded as a base64 * @param isBuffer defines whether the texture data are stored as a buffer * @returns true if the loader can load the specified file */ _ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) { return extension.indexOf(".env") === 0; }; /** * Transform the url before loading if required. * @param rootUrl the url of the texture * @param textureFormatInUse defines the current compressed format in use iun the engine * @returns the transformed texture */ _ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) { return rootUrl; }; /** * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work * @param rootUrl the url of the texture * @param textureFormatInUse defines the current compressed format in use iun the engine * @returns the fallback texture */ _ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) { return null; }; /** * Uploads the cube texture data to the WebGl Texture. It has alreday 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 */ _ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) { if (Array.isArray(data)) { return; } data = data; var info = _Misc_environmentTextureTools__WEBPACK_IMPORTED_MODULE_0__["EnvironmentTextureTools"].GetEnvInfo(data); if (info) { texture.width = info.width; texture.height = info.width; _Misc_environmentTextureTools__WEBPACK_IMPORTED_MODULE_0__["EnvironmentTextureTools"].UploadEnvSpherical(texture, info); _Misc_environmentTextureTools__WEBPACK_IMPORTED_MODULE_0__["EnvironmentTextureTools"].UploadEnvLevelsAsync(texture, data, info).then(function () { texture.isReady = true; if (onLoad) { onLoad(); } }); } else if (onError) { onError("Can not parse the environment file", null); } }; /** * Uploads the 2D texture data to the WebGl Texture. It has alreday 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 */ _ENVTextureLoader.prototype.loadData = function (data, texture, callback) { throw ".env not supported in 2d."; }; return _ENVTextureLoader; }()); // Register the loader. _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"]._TextureLoaders.push(new _ENVTextureLoader()); /***/ }), /***/ "./Materials/Textures/Loaders/index.ts": /*!*********************************************!*\ !*** ./Materials/Textures/Loaders/index.ts ***! \*********************************************/ /*! exports provided: _DDSTextureLoader, _ENVTextureLoader, _KTXTextureLoader, _TGATextureLoader */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _ddsTextureLoader__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ddsTextureLoader */ "./Materials/Textures/Loaders/ddsTextureLoader.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_DDSTextureLoader", function() { return _ddsTextureLoader__WEBPACK_IMPORTED_MODULE_0__["_DDSTextureLoader"]; }); /* harmony import */ var _envTextureLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./envTextureLoader */ "./Materials/Textures/Loaders/envTextureLoader.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_ENVTextureLoader", function() { return _envTextureLoader__WEBPACK_IMPORTED_MODULE_1__["_ENVTextureLoader"]; }); /* harmony import */ var _ktxTextureLoader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ktxTextureLoader */ "./Materials/Textures/Loaders/ktxTextureLoader.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_KTXTextureLoader", function() { return _ktxTextureLoader__WEBPACK_IMPORTED_MODULE_2__["_KTXTextureLoader"]; }); /* harmony import */ var _tgaTextureLoader__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./tgaTextureLoader */ "./Materials/Textures/Loaders/tgaTextureLoader.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_TGATextureLoader", function() { return _tgaTextureLoader__WEBPACK_IMPORTED_MODULE_3__["_TGATextureLoader"]; }); /***/ }), /***/ "./Materials/Textures/Loaders/ktxTextureLoader.ts": /*!********************************************************!*\ !*** ./Materials/Textures/Loaders/ktxTextureLoader.ts ***! \********************************************************/ /*! exports provided: _KTXTextureLoader */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_KTXTextureLoader", function() { return _KTXTextureLoader; }); /* harmony import */ var _Misc_khronosTextureContainer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../Misc/khronosTextureContainer */ "./Misc/khronosTextureContainer.ts"); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../Engines/engine */ "./Engines/engine.ts"); /** * Implementation of the KTX Texture Loader. * @hidden */ var _KTXTextureLoader = /** @class */ (function () { function _KTXTextureLoader() { /** * Defines wether the loader supports cascade loading the different faces. */ this.supportCascades = false; } /** * This returns if the loader support the current file information. * @param extension defines the file extension of the file being loaded * @param textureFormatInUse defines the current compressed format in use iun the engine * @param fallback defines the fallback internal texture if any * @param isBase64 defines whether the texture is encoded as a base64 * @param isBuffer defines whether the texture data are stored as a buffer * @returns true if the loader can load the specified file */ _KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) { if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) { return true; } return false; }; /** * Transform the url before loading if required. * @param rootUrl the url of the texture * @param textureFormatInUse defines the current compressed format in use iun the engine * @returns the transformed texture */ _KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) { var lastDot = rootUrl.lastIndexOf('.'); if (lastDot != -1 && rootUrl.substring(lastDot + 1) == "ktx") { // Already transformed return rootUrl; } return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse; }; /** * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work * @param rootUrl the url of the texture * @param textureFormatInUse defines the current compressed format in use iun the engine * @returns the fallback texture */ _KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) { // remove the format appended to the rootUrl in the original createCubeTexture call. var exp = new RegExp("" + textureFormatInUse + "$"); return rootUrl.replace(exp, ""); }; /** * Uploads the cube texture data to the WebGl Texture. It has alreday 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 */ _KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) { if (Array.isArray(data)) { return; } // Need to invert vScale as invertY via UNPACK_FLIP_Y_WEBGL is not supported by compressed texture texture._invertVScale = !texture.invertY; var engine = texture.getEngine(); var ktx = new _Misc_khronosTextureContainer__WEBPACK_IMPORTED_MODULE_0__["KhronosTextureContainer"](data, 6); var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps; engine._unpackFlipY(true); ktx.uploadLevels(texture, texture.generateMipMaps); texture.width = ktx.pixelWidth; texture.height = ktx.pixelHeight; engine._setCubeMapTextureParams(loadMipmap); texture.isReady = true; }; /** * Uploads the 2D texture data to the WebGl Texture. It has alreday 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 */ _KTXTextureLoader.prototype.loadData = function (data, texture, callback) { // Need to invert vScale as invertY via UNPACK_FLIP_Y_WEBGL is not supported by compressed texture texture._invertVScale = !texture.invertY; var ktx = new _Misc_khronosTextureContainer__WEBPACK_IMPORTED_MODULE_0__["KhronosTextureContainer"](data, 1); callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () { ktx.uploadLevels(texture, texture.generateMipMaps); }, ktx.isInvalid); }; return _KTXTextureLoader; }()); // Register the loader. _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"]._TextureLoaders.unshift(new _KTXTextureLoader()); /***/ }), /***/ "./Materials/Textures/Loaders/tgaTextureLoader.ts": /*!********************************************************!*\ !*** ./Materials/Textures/Loaders/tgaTextureLoader.ts ***! \********************************************************/ /*! exports provided: _TGATextureLoader */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_TGATextureLoader", function() { return _TGATextureLoader; }); /* harmony import */ var _Misc_tga__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../Misc/tga */ "./Misc/tga.ts"); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../Engines/engine */ "./Engines/engine.ts"); /** * Implementation of the TGA Texture Loader. * @hidden */ var _TGATextureLoader = /** @class */ (function () { function _TGATextureLoader() { /** * Defines wether the loader supports cascade loading the different faces. */ this.supportCascades = false; } /** * This returns if the loader support the current file information. * @param extension defines the file extension of the file being loaded * @param textureFormatInUse defines the current compressed format in use iun the engine * @param fallback defines the fallback internal texture if any * @param isBase64 defines whether the texture is encoded as a base64 * @param isBuffer defines whether the texture data are stored as a buffer * @returns true if the loader can load the specified file */ _TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) { return extension.indexOf(".tga") === 0; }; /** * Transform the url before loading if required. * @param rootUrl the url of the texture * @param textureFormatInUse defines the current compressed format in use iun the engine * @returns the transformed texture */ _TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) { return rootUrl; }; /** * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work * @param rootUrl the url of the texture * @param textureFormatInUse defines the current compressed format in use iun the engine * @returns the fallback texture */ _TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) { return null; }; /** * Uploads the cube texture data to the WebGl Texture. It has alreday 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 */ _TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) { throw ".env not supported in Cube."; }; /** * Uploads the 2D texture data to the WebGl Texture. It has alreday 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 */ _TGATextureLoader.prototype.loadData = function (data, texture, callback) { var uintData = new Uint8Array(data); var header = _Misc_tga__WEBPACK_IMPORTED_MODULE_0__["TGATools"].GetTGAHeader(uintData); callback(header.width, header.height, texture.generateMipMaps, false, function () { _Misc_tga__WEBPACK_IMPORTED_MODULE_0__["TGATools"].UploadContent(texture, uintData); }); }; return _TGATextureLoader; }()); // Register the loader. _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"]._TextureLoaders.push(new _TGATextureLoader()); /***/ }), /***/ "./Materials/Textures/MultiviewRenderTarget.ts": /*!*****************************************************!*\ !*** ./Materials/Textures/MultiviewRenderTarget.ts ***! \*****************************************************/ /*! exports provided: MultiviewRenderTarget */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MultiviewRenderTarget", function() { return MultiviewRenderTarget; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts"); /* harmony import */ var _Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Textures/internalTexture */ "./Materials/Textures/internalTexture.ts"); /** * Renders to multiple views with a single draw call * @see https://www.khronos.org/registry/webgl/extensions/WEBGL_multiview/ */ var MultiviewRenderTarget = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MultiviewRenderTarget, _super); /** * Creates a multiview render target * @param scene scene used with the render target * @param size the size of the render target (used for each view) */ function MultiviewRenderTarget(scene, size) { if (size === void 0) { size = 512; } var _this = _super.call(this, "multiview rtt", size, scene, false, true, _Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTexture"].DATASOURCE_UNKNOWN, false, undefined, false, false, true, undefined, true) || this; var internalTexture = scene.getEngine().createMultiviewRenderTargetTexture(_this.getRenderWidth(), _this.getRenderHeight()); internalTexture.isMultiview = true; _this._texture = internalTexture; return _this; } /** * @hidden * @param faceIndex the face index, if its a cube texture */ MultiviewRenderTarget.prototype._bindFrameBuffer = function (faceIndex) { if (faceIndex === void 0) { faceIndex = 0; } if (!this._texture) { return; } this.getScene().getEngine().bindMultiviewFramebuffer(this._texture); }; /** * Gets the number of views the corresponding to the texture (eg. a MultiviewRenderTarget will have > 1) * @returns the view count */ MultiviewRenderTarget.prototype.getViewCount = function () { return 2; }; return MultiviewRenderTarget; }(_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_1__["RenderTargetTexture"])); /***/ }), /***/ "./Materials/Textures/Procedurals/customProceduralTexture.ts": /*!*******************************************************************!*\ !*** ./Materials/Textures/Procedurals/customProceduralTexture.ts ***! \*******************************************************************/ /*! exports provided: CustomProceduralTexture */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CustomProceduralTexture", function() { return CustomProceduralTexture; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); /* harmony import */ var _proceduralTexture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./proceduralTexture */ "./Materials/Textures/Procedurals/proceduralTexture.ts"); /* harmony import */ var _Misc_webRequest__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../Misc/webRequest */ "./Misc/webRequest.ts"); /** * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images. * Custom Procedural textures are the easiest way to create your own procedural in your application. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures */ var CustomProceduralTexture = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](CustomProceduralTexture, _super); /** * Instantiates a new Custom Procedural Texture. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images. * Custom Procedural textures are the easiest way to create your own procedural in your application. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures * @param name Define the name of the texture * @param texturePath Define the folder path containing all the cutom texture related files (config, shaders...) * @param size Define the size of the texture to create * @param scene Define the scene the texture belongs to * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture * @param generateMipMaps Define if the texture should creates mip maps or not */ function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) { var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this; _this._animate = true; _this._time = 0; _this._texturePath = texturePath; //Try to load json _this._loadJson(texturePath); _this.refreshRate = 1; return _this; } CustomProceduralTexture.prototype._loadJson = function (jsonUrl) { var _this = this; var noConfigFile = function () { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element"); try { _this.setFragment(_this._texturePath); } catch (ex) { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Error("No json or ShaderStore or DOM element found for CustomProceduralTexture"); } }; var configFileUrl = jsonUrl + "/config.json"; var xhr = new _Misc_webRequest__WEBPACK_IMPORTED_MODULE_5__["WebRequest"](); xhr.open("GET", configFileUrl); xhr.addEventListener("load", function () { if (xhr.status === 200 || (xhr.responseText && xhr.responseText.length > 0)) { try { _this._config = JSON.parse(xhr.response); _this.updateShaderUniforms(); _this.updateTextures(); _this.setFragment(_this._texturePath + "/custom"); _this._animate = _this._config.animate; _this.refreshRate = _this._config.refreshrate; } catch (ex) { noConfigFile(); } } else { noConfigFile(); } }, false); xhr.addEventListener("error", function () { noConfigFile(); }, false); try { xhr.send(); } catch (ex) { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Error("CustomProceduralTexture: Error on XHR send request."); } }; /** * Is the texture ready to be used ? (rendered at least once) * @returns true if ready, otherwise, false. */ CustomProceduralTexture.prototype.isReady = function () { if (!_super.prototype.isReady.call(this)) { return false; } for (var name in this._textures) { var texture = this._textures[name]; if (!texture.isReady()) { return false; } } return true; }; /** * Render the texture to its associated render target. * @param useCameraPostProcess Define if camera post process should be applied to the texture */ CustomProceduralTexture.prototype.render = function (useCameraPostProcess) { var scene = this.getScene(); if (this._animate && scene) { this._time += scene.getAnimationRatio() * 0.03; this.updateShaderUniforms(); } _super.prototype.render.call(this, useCameraPostProcess); }; /** * Update the list of dependant textures samplers in the shader. */ CustomProceduralTexture.prototype.updateTextures = function () { for (var i = 0; i < this._config.sampler2Ds.length; i++) { this.setTexture(this._config.sampler2Ds[i].sample2Dname, new _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__["Texture"](this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene())); } }; /** * Update the uniform values of the procedural texture in the shader. */ CustomProceduralTexture.prototype.updateShaderUniforms = function () { if (this._config) { for (var j = 0; j < this._config.uniforms.length; j++) { var uniform = this._config.uniforms[j]; switch (uniform.type) { case "float": this.setFloat(uniform.name, uniform.value); break; case "color3": this.setColor3(uniform.name, new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"](uniform.r, uniform.g, uniform.b)); break; case "color4": this.setColor4(uniform.name, new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color4"](uniform.r, uniform.g, uniform.b, uniform.a)); break; case "vector2": this.setVector2(uniform.name, new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector2"](uniform.x, uniform.y)); break; case "vector3": this.setVector3(uniform.name, new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Vector3"](uniform.x, uniform.y, uniform.z)); break; } } } this.setFloat("time", this._time); }; Object.defineProperty(CustomProceduralTexture.prototype, "animate", { /** * Define if the texture animates or not. */ get: function () { return this._animate; }, set: function (value) { this._animate = value; }, enumerable: true, configurable: true }); return CustomProceduralTexture; }(_proceduralTexture__WEBPACK_IMPORTED_MODULE_4__["ProceduralTexture"])); /***/ }), /***/ "./Materials/Textures/Procedurals/index.ts": /*!*************************************************!*\ !*** ./Materials/Textures/Procedurals/index.ts ***! \*************************************************/ /*! exports provided: ProceduralTexture, CustomProceduralTexture, NoiseProceduralTexture, ProceduralTextureSceneComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _customProceduralTexture__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./customProceduralTexture */ "./Materials/Textures/Procedurals/customProceduralTexture.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CustomProceduralTexture", function() { return _customProceduralTexture__WEBPACK_IMPORTED_MODULE_0__["CustomProceduralTexture"]; }); /* harmony import */ var _noiseProceduralTexture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./noiseProceduralTexture */ "./Materials/Textures/Procedurals/noiseProceduralTexture.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NoiseProceduralTexture", function() { return _noiseProceduralTexture__WEBPACK_IMPORTED_MODULE_1__["NoiseProceduralTexture"]; }); /* harmony import */ var _proceduralTexture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./proceduralTexture */ "./Materials/Textures/Procedurals/proceduralTexture.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ProceduralTexture", function() { return _proceduralTexture__WEBPACK_IMPORTED_MODULE_2__["ProceduralTexture"]; }); /* harmony import */ var _proceduralTextureSceneComponent__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./proceduralTextureSceneComponent */ "./Materials/Textures/Procedurals/proceduralTextureSceneComponent.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ProceduralTextureSceneComponent", function() { return _proceduralTextureSceneComponent__WEBPACK_IMPORTED_MODULE_3__["ProceduralTextureSceneComponent"]; }); /***/ }), /***/ "./Materials/Textures/Procedurals/noiseProceduralTexture.ts": /*!******************************************************************!*\ !*** ./Materials/Textures/Procedurals/noiseProceduralTexture.ts ***! \******************************************************************/ /*! exports provided: NoiseProceduralTexture */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NoiseProceduralTexture", function() { return NoiseProceduralTexture; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../Engines/engineStore */ "./Engines/engineStore.ts"); /* harmony import */ var _proceduralTexture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./proceduralTexture */ "./Materials/Textures/Procedurals/proceduralTexture.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts"); /* harmony import */ var _Shaders_noise_fragment__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Shaders/noise.fragment */ "./Shaders/noise.fragment.ts"); /** * Class used to generate noise procedural textures */ var NoiseProceduralTexture = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](NoiseProceduralTexture, _super); /** * Creates a new NoiseProceduralTexture * @param name defines the name fo the texture * @param size defines the size of the texture (default is 256) * @param scene defines the hosting scene * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created * @param generateMipMaps defines if mipmaps must be generated (true by default) */ function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) { if (size === void 0) { size = 256; } if (scene === void 0) { scene = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_1__["EngineStore"].LastCreatedScene; } var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this; _this._time = 0; /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */ _this.brightness = 0.2; /** Defines the number of octaves to process */ _this.octaves = 3; /** Defines the level of persistence (0.8 by default) */ _this.persistence = 0.8; /** Gets or sets animation speed factor (default is 1) */ _this.animationSpeedFactor = 1; _this.autoClear = false; _this._updateShaderUniforms(); return _this; } NoiseProceduralTexture.prototype._updateShaderUniforms = function () { var scene = this.getScene(); if (!scene) { return; } this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01; this.setFloat("brightness", this.brightness); this.setFloat("persistence", this.persistence); this.setFloat("timeScale", this._time); }; NoiseProceduralTexture.prototype._getDefines = function () { return "#define OCTAVES " + (this.octaves | 0); }; /** Generate the current state of the procedural texture */ NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) { this._updateShaderUniforms(); _super.prototype.render.call(this, useCameraPostProcess); }; /** * Serializes this noise procedural texture * @returns a serialized noise procedural texture object */ NoiseProceduralTexture.prototype.serialize = function () { var serializationObject = {}; serializationObject.customType = "BABYLON.NoiseProceduralTexture"; serializationObject.brightness = this.brightness; serializationObject.octaves = this.octaves; serializationObject.persistence = this.persistence; serializationObject.animationSpeedFactor = this.animationSpeedFactor; serializationObject.size = this.getSize().width; serializationObject.generateMipMaps = this._generateMipMaps; return serializationObject; }; /** * Creates a NoiseProceduralTexture from parsed noise procedural texture data * @param parsedTexture defines parsed texture data * @param scene defines the current scene * @param rootUrl defines the root URL containing noise procedural texture information * @returns a parsed NoiseProceduralTexture */ NoiseProceduralTexture.Parse = function (parsedTexture, scene) { var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps); texture.brightness = parsedTexture.brightness; texture.octaves = parsedTexture.octaves; texture.persistence = parsedTexture.persistence; texture.animationSpeedFactor = parsedTexture.animationSpeedFactor; return texture; }; return NoiseProceduralTexture; }(_proceduralTexture__WEBPACK_IMPORTED_MODULE_2__["ProceduralTexture"])); _Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__["_TypeStore"].RegisteredTypes["BABYLON.NoiseProceduralTexture"] = NoiseProceduralTexture; /***/ }), /***/ "./Materials/Textures/Procedurals/proceduralTexture.ts": /*!*************************************************************!*\ !*** ./Materials/Textures/Procedurals/proceduralTexture.ts ***! \*************************************************************/ /*! exports provided: ProceduralTexture */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ProceduralTexture", function() { return ProceduralTexture; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../Meshes/buffer */ "./Meshes/buffer.ts"); /* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../sceneComponent */ "./sceneComponent.ts"); /* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../Materials/material */ "./Materials/material.ts"); /* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); /* harmony import */ var _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../../Materials/Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts"); /* harmony import */ var _proceduralTextureSceneComponent__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./proceduralTextureSceneComponent */ "./Materials/Textures/Procedurals/proceduralTextureSceneComponent.ts"); /* harmony import */ var _Shaders_procedural_vertex__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../../Shaders/procedural.vertex */ "./Shaders/procedural.vertex.ts"); /** * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes calmpler' images. * This is the base class of any Procedural texture and contains most of the shareable code. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures */ var ProceduralTexture = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ProceduralTexture, _super); /** * Instantiates a new procedural texture. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images. * This is the base class of any Procedural texture and contains most of the shareable code. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures * @param name Define the name of the texture * @param size Define the size of the texture to create * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later * @param scene Define the scene the texture belongs to * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture * @param generateMipMaps Define if the texture should creates mip maps or not * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube) */ function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) { if (fallbackTexture === void 0) { fallbackTexture = null; } if (generateMipMaps === void 0) { generateMipMaps = true; } if (isCube === void 0) { isCube = false; } var _this = _super.call(this, null, scene, !generateMipMaps) || this; _this.isCube = isCube; /** * Define if the texture is enabled or not (disabled texture will not render) */ _this.isEnabled = true; /** * Define if the texture must be cleared before rendering (default is true) */ _this.autoClear = true; /** * Event raised when the texture is generated */ _this.onGeneratedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** @hidden */ _this._textures = {}; _this._currentRefreshId = -1; _this._refreshRate = 1; _this._vertexBuffers = {}; _this._uniforms = new Array(); _this._samplers = new Array(); _this._floats = {}; _this._ints = {}; _this._floatsArrays = {}; _this._colors3 = {}; _this._colors4 = {}; _this._vectors2 = {}; _this._vectors3 = {}; _this._matrices = {}; _this._fallbackTextureUsed = false; _this._cachedDefines = ""; _this._contentUpdateId = -1; scene = _this.getScene(); var component = scene._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_PROCEDURALTEXTURE); if (!component) { component = new _proceduralTextureSceneComponent__WEBPACK_IMPORTED_MODULE_8__["ProceduralTextureSceneComponent"](scene); scene._addComponent(component); } scene.proceduralTextures.push(_this); _this._engine = scene.getEngine(); _this.name = name; _this.isRenderTarget = true; _this._size = size; _this._generateMipMaps = generateMipMaps; _this.setFragment(fragment); _this._fallbackTexture = fallbackTexture; if (isCube) { _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps, generateDepthBuffer: false, generateStencilBuffer: false }); _this.setFloat("face", 0); } else { _this._texture = _this._engine.createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, generateDepthBuffer: false, generateStencilBuffer: false }); } // VBO var vertices = []; vertices.push(1, 1); vertices.push(-1, 1); vertices.push(-1, -1); vertices.push(1, -1); _this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind] = new _Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"](_this._engine, vertices, _Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind, false, false, 2); _this._createIndexBuffer(); return _this; } /** * The effect that is created when initializing the post process. * @returns The created effect corrisponding the the postprocess. */ ProceduralTexture.prototype.getEffect = function () { return this._effect; }; /** * Gets texture content (Use this function wisely as reading from a texture can be slow) * @returns an ArrayBufferView (Uint8Array or Float32Array) */ ProceduralTexture.prototype.getContent = function () { if (this._contentData && this._currentRefreshId == this._contentUpdateId) { return this._contentData; } this._contentData = this.readPixels(0, 0, this._contentData); this._contentUpdateId = this._currentRefreshId; return this._contentData; }; ProceduralTexture.prototype._createIndexBuffer = function () { var engine = this._engine; // Indices var indices = []; indices.push(0); indices.push(1); indices.push(2); indices.push(0); indices.push(2); indices.push(3); this._indexBuffer = engine.createIndexBuffer(indices); }; /** @hidden */ ProceduralTexture.prototype._rebuild = function () { var vb = this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind]; if (vb) { vb._rebuild(); } this._createIndexBuffer(); if (this.refreshRate === _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_7__["RenderTargetTexture"].REFRESHRATE_RENDER_ONCE) { this.refreshRate = _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_7__["RenderTargetTexture"].REFRESHRATE_RENDER_ONCE; } }; /** * Resets the texture in order to recreate its associated resources. * This can be called in case of context loss */ ProceduralTexture.prototype.reset = function () { if (this._effect === undefined) { return; } var engine = this._engine; engine._releaseEffect(this._effect); }; ProceduralTexture.prototype._getDefines = function () { return ""; }; /** * Is the texture ready to be used ? (rendered at least once) * @returns true if ready, otherwise, false. */ ProceduralTexture.prototype.isReady = function () { var _this = this; var engine = this._engine; var shaders; if (!this._fragment) { return false; } if (this._fallbackTextureUsed) { return true; } var defines = this._getDefines(); if (this._effect && defines === this._cachedDefines && this._effect.isReady()) { return true; } if (this._fragment.fragmentElement !== undefined) { shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement }; } else { shaders = { vertex: "procedural", fragment: this._fragment }; } this._cachedDefines = defines; this._effect = engine.createEffect(shaders, [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () { _this.releaseInternalTexture(); if (_this._fallbackTexture) { _this._texture = _this._fallbackTexture._texture; if (_this._texture) { _this._texture.incrementReferences(); } } _this._fallbackTextureUsed = true; }); return this._effect.isReady(); }; /** * 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. */ ProceduralTexture.prototype.resetRefreshCounter = function () { this._currentRefreshId = -1; }; /** * Set the fragment shader to use in order to render the texture. * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property. */ ProceduralTexture.prototype.setFragment = function (fragment) { this._fragment = fragment; }; Object.defineProperty(ProceduralTexture.prototype, "refreshRate", { /** * 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: function () { return this._refreshRate; }, set: function (value) { this._refreshRate = value; this.resetRefreshCounter(); }, enumerable: true, configurable: true }); /** @hidden */ ProceduralTexture.prototype._shouldRender = function () { if (!this.isEnabled || !this.isReady() || !this._texture) { if (this._texture) { this._texture.isReady = false; } return false; } if (this._fallbackTextureUsed) { return false; } if (this._currentRefreshId === -1) { // At least render once this._currentRefreshId = 1; return true; } if (this.refreshRate === this._currentRefreshId) { this._currentRefreshId = 1; return true; } this._currentRefreshId++; return false; }; /** * Get the size the texture is rendering at. * @returns the size (texture is always squared) */ ProceduralTexture.prototype.getRenderSize = function () { return this._size; }; /** * Resize the texture to new value. * @param size Define the new size the texture should have * @param generateMipMaps Define whether the new texture should create mip maps */ ProceduralTexture.prototype.resize = function (size, generateMipMaps) { if (this._fallbackTextureUsed) { return; } this.releaseInternalTexture(); this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps); // Update properties this._size = size; this._generateMipMaps = generateMipMaps; }; ProceduralTexture.prototype._checkUniform = function (uniformName) { if (this._uniforms.indexOf(uniformName) === -1) { this._uniforms.push(uniformName); } }; /** * Set a texture in the shader program used to render. * @param name Define the name of the uniform samplers as defined in the shader * @param texture Define the texture to bind to this sampler * @return the texture itself allowing "fluent" like uniform updates */ ProceduralTexture.prototype.setTexture = function (name, texture) { if (this._samplers.indexOf(name) === -1) { this._samplers.push(name); } this._textures[name] = texture; return this; }; /** * Set a float in the shader. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @return the texture itself allowing "fluent" like uniform updates */ ProceduralTexture.prototype.setFloat = function (name, value) { this._checkUniform(name); this._floats[name] = value; return this; }; /** * Set a int in the shader. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @return the texture itself allowing "fluent" like uniform updates */ ProceduralTexture.prototype.setInt = function (name, value) { this._checkUniform(name); this._ints[name] = value; return this; }; /** * Set an array of floats in the shader. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @return the texture itself allowing "fluent" like uniform updates */ ProceduralTexture.prototype.setFloats = function (name, value) { this._checkUniform(name); this._floatsArrays[name] = value; return this; }; /** * Set a vec3 in the shader from a Color3. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @return the texture itself allowing "fluent" like uniform updates */ ProceduralTexture.prototype.setColor3 = function (name, value) { this._checkUniform(name); this._colors3[name] = value; return this; }; /** * Set a vec4 in the shader from a Color4. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @return the texture itself allowing "fluent" like uniform updates */ ProceduralTexture.prototype.setColor4 = function (name, value) { this._checkUniform(name); this._colors4[name] = value; return this; }; /** * Set a vec2 in the shader from a Vector2. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @return the texture itself allowing "fluent" like uniform updates */ ProceduralTexture.prototype.setVector2 = function (name, value) { this._checkUniform(name); this._vectors2[name] = value; return this; }; /** * Set a vec3 in the shader from a Vector3. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @return the texture itself allowing "fluent" like uniform updates */ ProceduralTexture.prototype.setVector3 = function (name, value) { this._checkUniform(name); this._vectors3[name] = value; return this; }; /** * Set a mat4 in the shader from a MAtrix. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @return the texture itself allowing "fluent" like uniform updates */ ProceduralTexture.prototype.setMatrix = function (name, value) { this._checkUniform(name); this._matrices[name] = value; return this; }; /** * Render the texture to its associated render target. * @param useCameraPostProcess Define if camera post process should be applied to the texture */ ProceduralTexture.prototype.render = function (useCameraPostProcess) { var scene = this.getScene(); if (!scene) { return; } var engine = this._engine; // Render engine.enableEffect(this._effect); engine.setState(false); // Texture for (var name in this._textures) { this._effect.setTexture(name, this._textures[name]); } // Float for (name in this._ints) { this._effect.setInt(name, this._ints[name]); } // Float for (name in this._floats) { this._effect.setFloat(name, this._floats[name]); } // Floats for (name in this._floatsArrays) { this._effect.setArray(name, this._floatsArrays[name]); } // Color3 for (name in this._colors3) { this._effect.setColor3(name, this._colors3[name]); } // Color4 for (name in this._colors4) { var color = this._colors4[name]; this._effect.setFloat4(name, color.r, color.g, color.b, color.a); } // Vector2 for (name in this._vectors2) { this._effect.setVector2(name, this._vectors2[name]); } // Vector3 for (name in this._vectors3) { this._effect.setVector3(name, this._vectors3[name]); } // Matrix for (name in this._matrices) { this._effect.setMatrix(name, this._matrices[name]); } if (!this._texture) { return; } if (this.isCube) { for (var face = 0; face < 6; face++) { engine.bindFramebuffer(this._texture, face, undefined, undefined, true); // VBOs engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect); this._effect.setFloat("face", face); // Clear if (this.autoClear) { engine.clear(scene.clearColor, true, false, false); } // Draw order engine.drawElementsType(_Materials_material__WEBPACK_IMPORTED_MODULE_5__["Material"].TriangleFillMode, 0, 6); // Mipmaps if (face === 5) { engine.generateMipMapsForCubemap(this._texture); } } } else { engine.bindFramebuffer(this._texture, 0, undefined, undefined, true); // VBOs engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect); // Clear if (this.autoClear) { engine.clear(scene.clearColor, true, false, false); } // Draw order engine.drawElementsType(_Materials_material__WEBPACK_IMPORTED_MODULE_5__["Material"].TriangleFillMode, 0, 6); } // Unbind engine.unBindFramebuffer(this._texture, this.isCube); if (this.onGenerated) { this.onGenerated(); } this.onGeneratedObservable.notifyObservers(this); }; /** * Clone the texture. * @returns the cloned texture */ ProceduralTexture.prototype.clone = function () { var textureSize = this.getSize(); var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps); // Base texture newTexture.hasAlpha = this.hasAlpha; newTexture.level = this.level; // RenderTarget Texture newTexture.coordinatesMode = this.coordinatesMode; return newTexture; }; /** * Dispose the texture and release its asoociated resources. */ ProceduralTexture.prototype.dispose = function () { var scene = this.getScene(); if (!scene) { return; } var index = scene.proceduralTextures.indexOf(this); if (index >= 0) { scene.proceduralTextures.splice(index, 1); } var vertexBuffer = this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind]; if (vertexBuffer) { vertexBuffer.dispose(); this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind] = null; } if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) { this._indexBuffer = null; } _super.prototype.dispose.call(this); }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ProceduralTexture.prototype, "isEnabled", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ProceduralTexture.prototype, "autoClear", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ProceduralTexture.prototype, "_generateMipMaps", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ProceduralTexture.prototype, "_size", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ProceduralTexture.prototype, "refreshRate", null); return ProceduralTexture; }(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"])); /***/ }), /***/ "./Materials/Textures/Procedurals/proceduralTextureSceneComponent.ts": /*!***************************************************************************!*\ !*** ./Materials/Textures/Procedurals/proceduralTextureSceneComponent.ts ***! \***************************************************************************/ /*! exports provided: ProceduralTextureSceneComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ProceduralTextureSceneComponent", function() { return ProceduralTextureSceneComponent; }); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../sceneComponent */ "./sceneComponent.ts"); /** * Defines the Procedural Texture scene component responsible to manage any Procedural Texture * in a given scene. */ var ProceduralTextureSceneComponent = /** @class */ (function () { /** * Creates a new instance of the component for the given scene * @param scene Defines the scene to register the component in */ function ProceduralTextureSceneComponent(scene) { /** * The component name helpfull to identify the component in the list of scene components. */ this.name = _sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_PROCEDURALTEXTURE; this.scene = scene; this.scene.proceduralTextures = new Array(); scene.layers = new Array(); } /** * Registers the component in a given scene */ ProceduralTextureSceneComponent.prototype.register = function () { this.scene._beforeClearStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear); }; /** * Rebuilds the elements related to this component in case of * context lost for instance. */ ProceduralTextureSceneComponent.prototype.rebuild = function () { // Nothing to do here. }; /** * Disposes the component and the associated ressources. */ ProceduralTextureSceneComponent.prototype.dispose = function () { // Nothing to do here. }; ProceduralTextureSceneComponent.prototype._beforeClear = function () { if (this.scene.proceduralTexturesEnabled) { _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0); for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) { var proceduralTexture = this.scene.proceduralTextures[proceduralIndex]; if (proceduralTexture._shouldRender()) { proceduralTexture.render(); } } _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0); } }; return ProceduralTextureSceneComponent; }()); /***/ }), /***/ "./Materials/Textures/baseTexture.ts": /*!*******************************************!*\ !*** ./Materials/Textures/baseTexture.ts ***! \*******************************************/ /*! exports provided: BaseTexture */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BaseTexture", function() { return BaseTexture; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _Misc_HighDynamicRange_cubemapToSphericalPolynomial__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Misc/HighDynamicRange/cubemapToSphericalPolynomial */ "./Misc/HighDynamicRange/cubemapToSphericalPolynomial.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Engines/engineStore */ "./Engines/engineStore.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); /** * 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. */ var BaseTexture = /** @class */ (function () { /** * 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 scene Define the scene the texture blongs to */ function BaseTexture(scene) { /** * Gets or sets an object used to store user defined information. */ this.metadata = null; /** * For internal use only. Please do not use. */ this.reservedDataStore = null; this._hasAlpha = false; /** * 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. */ this.getAlphaFromRGB = false; /** * Intensity or strength of the texture. * It is commonly used by materials to fine tune the intensity of the texture */ this.level = 1; /** * Define the UV chanel to use starting from 0 and defaulting to 0. * This is part of the texture as textures usually maps to one uv set. */ this.coordinatesIndex = 0; this._coordinatesMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_EXPLICIT_MODE; /** * | Value | Type | Description | * | ----- | ------------------ | ----------- | * | 0 | CLAMP_ADDRESSMODE | | * | 1 | WRAP_ADDRESSMODE | | * | 2 | MIRROR_ADDRESSMODE | | */ this.wrapU = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_WRAP_ADDRESSMODE; /** * | Value | Type | Description | * | ----- | ------------------ | ----------- | * | 0 | CLAMP_ADDRESSMODE | | * | 1 | WRAP_ADDRESSMODE | | * | 2 | MIRROR_ADDRESSMODE | | */ this.wrapV = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_WRAP_ADDRESSMODE; /** * | Value | Type | Description | * | ----- | ------------------ | ----------- | * | 0 | CLAMP_ADDRESSMODE | | * | 1 | WRAP_ADDRESSMODE | | * | 2 | MIRROR_ADDRESSMODE | | */ this.wrapR = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_WRAP_ADDRESSMODE; /** * With compliant hardware and browser (supporting anisotropic filtering) * this defines the level of anisotropic filtering in the texture. * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff. */ this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL; /** * 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 */ this.gammaSpace = true; /** * Is Z inverted in the texture (useful in a cube texture). */ this.invertZ = false; /** * @hidden */ this.lodLevelInAlpha = false; /** * Define if the texture is a render target. */ this.isRenderTarget = false; /** * Define the list of animation attached to the texture. */ this.animations = new Array(); /** * An event triggered when the texture is disposed. */ this.onDisposeObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Define the current state of the loading sequence when in delayed load mode. */ this.delayLoadState = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].DELAYLOADSTATE_NONE; this._cachedSize = _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Size"].Zero(); this._scene = scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_6__["EngineStore"].LastCreatedScene; if (this._scene) { this.uniqueId = this._scene.getUniqueId(); this._scene.addTexture(this); } this._uid = null; } Object.defineProperty(BaseTexture.prototype, "hasAlpha", { get: function () { return this._hasAlpha; }, /** * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance). */ set: function (value) { if (this._hasAlpha === value) { return; } this._hasAlpha = value; if (this._scene) { this._scene.markAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].MATERIAL_TextureDirtyFlag | _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].MATERIAL_MiscDirtyFlag); } }, enumerable: true, configurable: true }); Object.defineProperty(BaseTexture.prototype, "coordinatesMode", { get: function () { return this._coordinatesMode; }, /** * 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: function (value) { if (this._coordinatesMode === value) { return; } this._coordinatesMode = value; if (this._scene) { this._scene.markAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].MATERIAL_TextureDirtyFlag); } }, enumerable: true, configurable: true }); Object.defineProperty(BaseTexture.prototype, "isCube", { /** * Define if the texture is a cube texture or if false a 2d texture. */ get: function () { if (!this._texture) { return false; } return this._texture.isCube; }, set: function (value) { if (!this._texture) { return; } this._texture.isCube = value; }, enumerable: true, configurable: true }); Object.defineProperty(BaseTexture.prototype, "is3D", { /** * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture. */ get: function () { if (!this._texture) { return false; } return this._texture.is3D; }, set: function (value) { if (!this._texture) { return; } this._texture.is3D = value; }, enumerable: true, configurable: true }); Object.defineProperty(BaseTexture.prototype, "isRGBD", { /** * Gets whether or not the texture contains RGBD data. */ get: function () { return this._texture != null && this._texture._isRGBD; }, enumerable: true, configurable: true }); Object.defineProperty(BaseTexture.prototype, "noMipmap", { /** * Are mip maps generated for this texture or not. */ get: function () { return false; }, enumerable: true, configurable: true }); Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", { /** * With prefiltered texture, defined the offset used during the prefiltering steps. */ get: function () { if (this._texture) { return this._texture._lodGenerationOffset; } return 0.0; }, set: function (value) { if (this._texture) { this._texture._lodGenerationOffset = value; } }, enumerable: true, configurable: true }); Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", { /** * With prefiltered texture, defined the scale used during the prefiltering steps. */ get: function () { if (this._texture) { return this._texture._lodGenerationScale; } return 0.0; }, set: function (value) { if (this._texture) { this._texture._lodGenerationScale = value; } }, enumerable: true, configurable: true }); Object.defineProperty(BaseTexture.prototype, "uid", { /** * Define the unique id of the texture in the scene. */ get: function () { if (!this._uid) { this._uid = _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].RandomId(); } return this._uid; }, enumerable: true, configurable: true }); /** * Return a string representation of the texture. * @returns the texture as a string */ BaseTexture.prototype.toString = function () { return this.name; }; /** * Get the class name of the texture. * @returns "BaseTexture" */ BaseTexture.prototype.getClassName = function () { return "BaseTexture"; }; Object.defineProperty(BaseTexture.prototype, "onDispose", { /** * Callback triggered when the texture has been disposed. * Kept for back compatibility, you can use the onDisposeObservable instead. */ set: function (callback) { if (this._onDisposeObserver) { this.onDisposeObservable.remove(this._onDisposeObserver); } this._onDisposeObserver = this.onDisposeObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(BaseTexture.prototype, "isBlocking", { /** * Define if the texture is preventinga material to render or not. * If not and the texture is not ready, the engine will use a default black texture instead. */ get: function () { return true; }, enumerable: true, configurable: true }); /** * Get the scene the texture belongs to. * @returns the scene or null if undefined */ BaseTexture.prototype.getScene = function () { return this._scene; }; /** * Get the texture transform matrix used to offset tile the texture for istance. * @returns the transformation matrix */ BaseTexture.prototype.getTextureMatrix = function () { return _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].IdentityReadOnly; }; /** * Get the texture reflection matrix used to rotate/transform the reflection. * @returns the reflection matrix */ BaseTexture.prototype.getReflectionTextureMatrix = function () { return _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Matrix"].IdentityReadOnly; }; /** * Get the underlying lower level texture from Babylon. * @returns the insternal texture */ BaseTexture.prototype.getInternalTexture = function () { return this._texture; }; /** * Get if the texture is ready to be consumed (either it is ready or it is not blocking) * @returns true if ready or not blocking */ BaseTexture.prototype.isReadyOrNotBlocking = function () { return !this.isBlocking || this.isReady(); }; /** * Get if the texture is ready to be used (downloaded, converted, mip mapped...). * @returns true if fully ready */ BaseTexture.prototype.isReady = function () { if (this.delayLoadState === _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].DELAYLOADSTATE_NOTLOADED) { this.delayLoad(); return false; } if (this._texture) { return this._texture.isReady; } return false; }; /** * Get the size of the texture. * @returns the texture size. */ BaseTexture.prototype.getSize = function () { 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 */ BaseTexture.prototype.getBaseSize = function () { if (!this.isReady() || !this._texture) { return _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Size"].Zero(); } if (this._texture._size) { return new _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Size"](this._texture._size, this._texture._size); } return new _Maths_math__WEBPACK_IMPORTED_MODULE_5__["Size"](this._texture.baseWidth, this._texture.baseHeight); }; /** * 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 */ BaseTexture.prototype.updateSamplingMode = function (samplingMode) { if (!this._texture) { return; } var scene = this.getScene(); if (!scene) { return; } scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture); }; /** * Scales the texture if is `canRescale()` * @param ratio the resize factor we want to use to rescale */ BaseTexture.prototype.scale = function (ratio) { }; Object.defineProperty(BaseTexture.prototype, "canRescale", { /** * Get if the texture can rescale. */ get: function () { return false; }, enumerable: true, configurable: true }); /** @hidden */ BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling, invertY) { if (!this._scene) { return null; } var texturesCache = this._scene.getEngine().getLoadedTexturesCache(); for (var index = 0; index < texturesCache.length; index++) { var texturesCacheEntry = texturesCache[index]; if (invertY === undefined || invertY === texturesCacheEntry.invertY) { if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) { if (!sampling || sampling === texturesCacheEntry.samplingMode) { texturesCacheEntry.incrementReferences(); return texturesCacheEntry; } } } } return null; }; /** @hidden */ BaseTexture.prototype._rebuild = function () { }; /** * Triggers the load sequence in delayed load mode. */ BaseTexture.prototype.delayLoad = function () { }; /** * Clones the texture. * @returns the cloned texture */ BaseTexture.prototype.clone = function () { return null; }; Object.defineProperty(BaseTexture.prototype, "textureType", { /** * Get the texture underlying type (INT, FLOAT...) */ get: function () { if (!this._texture) { return _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_INT; } return (this._texture.type !== undefined) ? this._texture.type : _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_INT; }, enumerable: true, configurable: true }); Object.defineProperty(BaseTexture.prototype, "textureFormat", { /** * Get the texture underlying format (RGB, RGBA...) */ get: function () { if (!this._texture) { return _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGBA; } return (this._texture.format !== undefined) ? this._texture.format : _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGBA; }, enumerable: true, configurable: true }); /** * 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) * @returns The Array buffer containing the pixels data. */ BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) { if (faceIndex === void 0) { faceIndex = 0; } if (level === void 0) { level = 0; } if (buffer === void 0) { buffer = null; } if (!this._texture) { return null; } var size = this.getSize(); var width = size.width; var height = size.height; var scene = this.getScene(); if (!scene) { return null; } var engine = scene.getEngine(); if (level != 0) { width = width / Math.pow(2, level); height = height / Math.pow(2, level); width = Math.round(width); height = Math.round(height); } if (this._texture.isCube) { return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer); } return engine._readTexturePixels(this._texture, width, height, -1, level, buffer); }; /** * Release and destroy the underlying lower level texture aka internalTexture. */ BaseTexture.prototype.releaseInternalTexture = function () { if (this._texture) { this._texture.dispose(); this._texture = null; } }; Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", { /** * Get the polynomial representation of the texture data. * This is mainly use as a fast way to recover IBL Diffuse irradiance data. * @see https://learnopengl.com/PBR/IBL/Diffuse-irradiance */ get: function () { if (!this._texture || !_Misc_HighDynamicRange_cubemapToSphericalPolynomial__WEBPACK_IMPORTED_MODULE_4__["CubeMapToSphericalPolynomialTools"] || !this.isReady()) { return null; } if (!this._texture._sphericalPolynomial) { this._texture._sphericalPolynomial = _Misc_HighDynamicRange_cubemapToSphericalPolynomial__WEBPACK_IMPORTED_MODULE_4__["CubeMapToSphericalPolynomialTools"].ConvertCubeMapTextureToSphericalPolynomial(this); } return this._texture._sphericalPolynomial; }, set: function (value) { if (this._texture) { this._texture._sphericalPolynomial = value; } }, enumerable: true, configurable: true }); Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", { /** @hidden */ get: function () { if (this._texture) { return this._texture._lodTextureHigh; } return null; }, enumerable: true, configurable: true }); Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", { /** @hidden */ get: function () { if (this._texture) { return this._texture._lodTextureMid; } return null; }, enumerable: true, configurable: true }); Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", { /** @hidden */ get: function () { if (this._texture) { return this._texture._lodTextureLow; } return null; }, enumerable: true, configurable: true }); /** * Dispose the texture and release its associated resources. */ BaseTexture.prototype.dispose = function () { if (!this._scene) { return; } // Animations this._scene.stopAnimation(this); // Remove from scene this._scene._removePendingData(this); var index = this._scene.textures.indexOf(this); if (index >= 0) { this._scene.textures.splice(index, 1); } this._scene.onTextureRemovedObservable.notifyObservers(this); if (this._texture === undefined) { return; } // Release this.releaseInternalTexture(); // Callback this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); }; /** * Serialize the texture into a JSON representation that can be parsed later on. * @returns the JSON representation of the texture */ BaseTexture.prototype.serialize = function () { if (!this.name) { return null; } var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); // Animations _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["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 */ BaseTexture.WhenAllReady = function (textures, callback) { var numRemaining = textures.length; if (numRemaining === 0) { callback(); return; } var _loop_1 = function () { texture = textures[i]; if (texture.isReady()) { if (--numRemaining === 0) { callback(); } } else { onLoadObservable = texture.onLoadObservable; var onLoadCallback_1 = function () { onLoadObservable.removeCallback(onLoadCallback_1); if (--numRemaining === 0) { callback(); } }; onLoadObservable.add(onLoadCallback_1); } }; var texture, onLoadObservable; for (var i = 0; i < textures.length; i++) { _loop_1(); } }; /** * Default anisotropic filtering level for the application. * It is set to 4 as a good tradeoff between perf and quality. */ BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BaseTexture.prototype, "uniqueId", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BaseTexture.prototype, "name", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BaseTexture.prototype, "metadata", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("hasAlpha") ], BaseTexture.prototype, "_hasAlpha", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BaseTexture.prototype, "getAlphaFromRGB", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BaseTexture.prototype, "level", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BaseTexture.prototype, "coordinatesIndex", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("coordinatesMode") ], BaseTexture.prototype, "_coordinatesMode", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BaseTexture.prototype, "wrapU", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BaseTexture.prototype, "wrapV", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BaseTexture.prototype, "wrapR", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BaseTexture.prototype, "isCube", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BaseTexture.prototype, "is3D", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BaseTexture.prototype, "gammaSpace", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BaseTexture.prototype, "invertZ", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BaseTexture.prototype, "lodLevelInAlpha", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BaseTexture.prototype, "lodGenerationOffset", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BaseTexture.prototype, "lodGenerationScale", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BaseTexture.prototype, "isRenderTarget", void 0); return BaseTexture; }()); /***/ }), /***/ "./Materials/Textures/colorGradingTexture.ts": /*!***************************************************!*\ !*** ./Materials/Textures/colorGradingTexture.ts ***! \***************************************************/ /*! exports provided: ColorGradingTexture */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorGradingTexture", function() { return ColorGradingTexture; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Materials/Textures/baseTexture */ "./Materials/Textures/baseTexture.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts"); /** * This represents a color grading texture. This acts as a lookup table LUT, useful during post process * It can help converting any input color in a desired output one. This can then be used to create effects * from sepia, black and white to sixties or futuristic rendering... * * The only supported format is currently 3dl. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table */ var ColorGradingTexture = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ColorGradingTexture, _super); /** * Instantiates a ColorGradingTexture from the following parameters. * * @param url The location of the color gradind data (currently only supporting 3dl) * @param scene The scene the texture will be used in */ function ColorGradingTexture(url, scene) { var _this = _super.call(this, scene) || this; if (!url) { return _this; } _this._engine = scene.getEngine(); _this._textureMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(); _this.name = url; _this.url = url; _this.hasAlpha = false; _this.isCube = false; _this.is3D = _this._engine.webGLVersion > 1; _this.wrapU = _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURE_CLAMP_ADDRESSMODE; _this.wrapV = _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURE_CLAMP_ADDRESSMODE; _this.wrapR = _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURE_CLAMP_ADDRESSMODE; _this.anisotropicFilteringLevel = 1; _this._texture = _this._getFromCache(url, true); if (!_this._texture) { if (!scene.useDelayedTextureLoading) { _this.loadTexture(); } else { _this.delayLoadState = _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].DELAYLOADSTATE_NOTLOADED; } } return _this; } /** * Returns the texture matrix used in most of the material. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in). */ ColorGradingTexture.prototype.getTextureMatrix = function () { return this._textureMatrix; }; /** * Occurs when the file being loaded is a .3dl LUT file. */ ColorGradingTexture.prototype.load3dlTexture = function () { var engine = this._engine; var texture; if (engine.webGLVersion === 1) { texture = engine.createRawTexture(null, 1, 1, _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTUREFORMAT_RGBA, false, false, _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURE_BILINEAR_SAMPLINGMODE); } else { texture = engine.createRawTexture3D(null, 1, 1, 1, _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTUREFORMAT_RGBA, false, false, _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURE_BILINEAR_SAMPLINGMODE); } this._texture = texture; var callback = function (text) { if (typeof text !== "string") { return; } var data = null; var tempData = null; var line; var lines = text.split('\n'); var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0; var maxColor = 0; for (var i = 0; i < lines.length; i++) { line = lines[i]; if (!ColorGradingTexture._noneEmptyLineRegex.test(line)) { continue; } if (line.indexOf('#') === 0) { continue; } var words = line.split(" "); if (size === 0) { // Number of space + one size = words.length; data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8 tempData = new Float32Array(size * size * size * 4); continue; } if (size != 0) { var r = Math.max(parseInt(words[0]), 0); var g = Math.max(parseInt(words[1]), 0); var b = Math.max(parseInt(words[2]), 0); maxColor = Math.max(r, maxColor); maxColor = Math.max(g, maxColor); maxColor = Math.max(b, maxColor); var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4; if (tempData) { tempData[pixelStorageIndex + 0] = r; tempData[pixelStorageIndex + 1] = g; tempData[pixelStorageIndex + 2] = b; } // Keep for reference in case of back compat problems. // pixelIndexSlice++; // if (pixelIndexSlice % size == 0) { // pixelIndexH++; // pixelIndexSlice = 0; // if (pixelIndexH % size == 0) { // pixelIndexW++; // pixelIndexH = 0; // } // } pixelIndexH++; if (pixelIndexH % size == 0) { pixelIndexSlice++; pixelIndexH = 0; if (pixelIndexSlice % size == 0) { pixelIndexW++; pixelIndexSlice = 0; } } } } if (tempData && data) { for (var i = 0; i < tempData.length; i++) { if (i > 0 && (i + 1) % 4 === 0) { data[i] = 255; } else { var value = tempData[i]; data[i] = (value / maxColor * 255); } } } if (texture.is3D) { texture.updateSize(size, size, size); engine.updateRawTexture3D(texture, data, _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTUREFORMAT_RGBA, false); } else { texture.updateSize(size * size, size); engine.updateRawTexture(texture, data, _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTUREFORMAT_RGBA, false); } }; var scene = this.getScene(); if (scene) { scene._loadFile(this.url, callback); } else { this._engine._loadFile(this.url, callback); } return this._texture; }; /** * Starts the loading process of the texture. */ ColorGradingTexture.prototype.loadTexture = function () { if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) { this.load3dlTexture(); } }; /** * Clones the color gradind texture. */ ColorGradingTexture.prototype.clone = function () { var newTexture = new ColorGradingTexture(this.url, this.getScene()); // Base texture newTexture.level = this.level; return newTexture; }; /** * Called during delayed load for textures. */ ColorGradingTexture.prototype.delayLoad = function () { if (this.delayLoadState !== _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].DELAYLOADSTATE_NOTLOADED) { return; } this.delayLoadState = _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].DELAYLOADSTATE_LOADED; this._texture = this._getFromCache(this.url, true); if (!this._texture) { this.loadTexture(); } }; /** * Parses a color grading texture serialized by Babylon. * @param parsedTexture The texture information being parsedTexture * @param scene The scene to load the texture in * @param rootUrl The root url of the data assets to load * @return A color gradind texture */ ColorGradingTexture.Parse = function (parsedTexture, scene) { var texture = null; if (parsedTexture.name && !parsedTexture.isRenderTarget) { texture = new ColorGradingTexture(parsedTexture.name, scene); texture.name = parsedTexture.name; texture.level = parsedTexture.level; } return texture; }; /** * Serializes the LUT texture to json format. */ ColorGradingTexture.prototype.serialize = function () { if (!this.name) { return null; } var serializationObject = {}; serializationObject.name = this.name; serializationObject.level = this.level; serializationObject.customType = "BABYLON.ColorGradingTexture"; return serializationObject; }; /** * Empty line regex stored for GC. */ ColorGradingTexture._noneEmptyLineRegex = /\S+/; return ColorGradingTexture; }(_Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_2__["BaseTexture"])); _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.ColorGradingTexture"] = ColorGradingTexture; /***/ }), /***/ "./Materials/Textures/cubeTexture.ts": /*!*******************************************!*\ !*** ./Materials/Textures/cubeTexture.ts ***! \*******************************************/ /*! exports provided: CubeTexture */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CubeTexture", function() { return CubeTexture; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/Textures/baseTexture */ "./Materials/Textures/baseTexture.ts"); /* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts"); /** * Class for creating a cube texture */ var CubeTexture = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](CubeTexture, _super); /** * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well * as prefiltered data. * @param rootUrl defines the url of the texture or the root name of the six images * @param scene defines the scene the texture is attached to * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg... * @param noMipmap defines if mipmaps should be created or not * @param files defines the six files to load for the different faces in that order: px, py, pz, nx, ny, nz * @param onLoad defines a callback triggered at the end of the file load if no errors occured * @param onError defines a callback triggered in case of error during load * @param format defines the internal format to use for the texture once loaded * @param prefiltered defines whether or not the texture is created from prefiltered data * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness * @return the cube texture */ function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) { if (extensions === void 0) { extensions = null; } if (noMipmap === void 0) { noMipmap = false; } if (files === void 0) { files = null; } if (onLoad === void 0) { onLoad = null; } if (onError === void 0) { onError = null; } if (format === void 0) { format = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTUREFORMAT_RGBA; } if (prefiltered === void 0) { prefiltered = false; } if (forcedExtension === void 0) { forcedExtension = null; } if (createPolynomials === void 0) { createPolynomials = false; } if (lodScale === void 0) { lodScale = 0.8; } if (lodOffset === void 0) { lodOffset = 0; } var _this = _super.call(this, scene) || this; /** * Gets or sets the center of the bounding box associated with the cube texture. * It must define where the camera used to render the texture was set * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode */ _this.boundingBoxPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); _this._rotationY = 0; /** @hidden */ _this._prefiltered = false; _this.name = rootUrl; _this.url = rootUrl; _this._noMipmap = noMipmap; _this.hasAlpha = false; _this._format = format; _this.isCube = true; _this._textureMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Identity(); _this._createPolynomials = createPolynomials; _this.coordinatesMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"].CUBIC_MODE; if (!rootUrl && !files) { return _this; } var lastDot = rootUrl.lastIndexOf("."); var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : ""); var isDDS = (extension === ".dds"); var isEnv = (extension === ".env"); if (isEnv) { _this.gammaSpace = false; _this._prefiltered = false; } else { _this._prefiltered = prefiltered; if (prefiltered) { _this.gammaSpace = false; } } _this._texture = _this._getFromCache(rootUrl, noMipmap); if (!files) { if (!isEnv && !isDDS && !extensions) { extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"]; } files = []; if (extensions) { for (var index = 0; index < extensions.length; index++) { files.push(rootUrl + extensions[index]); } } } _this._files = files; if (!_this._texture) { if (!scene.useDelayedTextureLoading) { if (prefiltered) { _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials); } else { _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset); } } else { _this.delayLoadState = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].DELAYLOADSTATE_NOTLOADED; } } else if (onLoad) { if (_this._texture.isReady) { _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].SetImmediate(function () { return onLoad(); }); } else { _this._texture.onLoadedObservable.add(onLoad); } } return _this; } Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", { /** * Returns the bounding box size * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode */ get: function () { return this._boundingBoxSize; }, /** * Gets or sets the size of the bounding box associated with the cube texture * When defined, the cubemap will switch to local mode * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity * @example https://www.babylonjs-playground.com/#RNASML */ set: function (value) { if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) { return; } this._boundingBoxSize = value; var scene = this.getScene(); if (scene) { scene.markAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].MATERIAL_TextureDirtyFlag); } }, enumerable: true, configurable: true }); Object.defineProperty(CubeTexture.prototype, "rotationY", { /** * Gets texture matrix rotation angle around Y axis radians. */ get: function () { return this._rotationY; }, /** * Sets texture matrix rotation angle around Y axis in radians. */ set: function (value) { this._rotationY = value; this.setReflectionTextureMatrix(_Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].RotationY(this._rotationY)); }, enumerable: true, configurable: true }); Object.defineProperty(CubeTexture.prototype, "noMipmap", { /** * Are mip maps generated for this texture or not. */ get: function () { return this._noMipmap; }, enumerable: true, configurable: true }); /** * Creates a cube texture from an array of image urls * @param files defines an array of image urls * @param scene defines the hosting scene * @param noMipmap specifies if mip maps are not used * @returns a cube texture */ CubeTexture.CreateFromImages = function (files, scene, noMipmap) { var rootUrlKey = ""; files.forEach(function (url) { return rootUrlKey += url; }); return new CubeTexture(rootUrlKey, scene, null, noMipmap, files); }; /** * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys. * @param url defines the url of the prefiltered texture * @param scene defines the scene the texture is attached to * @param forcedExtension defines the extension of the file if different from the url * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary * @return the prefiltered texture */ CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) { if (forcedExtension === void 0) { forcedExtension = null; } if (createPolynomials === void 0) { createPolynomials = true; } return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials); }; /** * Get the current class name of the texture useful for serialization or dynamic coding. * @returns "CubeTexture" */ CubeTexture.prototype.getClassName = function () { return "CubeTexture"; }; /** * Update the url (and optional buffer) of this texture if url was null during construction. * @param url the url of the texture * @param forcedExtension defines the extension to use * @param onLoad callback called when the texture is loaded (defaults to null) */ CubeTexture.prototype.updateURL = function (url, forcedExtension, onLoad) { if (this.url) { this.releaseInternalTexture(); this.getScene().markAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].MATERIAL_TextureDirtyFlag); } this.url = url; this.delayLoadState = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].DELAYLOADSTATE_NOTLOADED; this._prefiltered = false; if (onLoad) { this._delayedOnLoad = onLoad; } this.delayLoad(forcedExtension); }; /** * Delays loading of the cube texture * @param forcedExtension defines the extension to use */ CubeTexture.prototype.delayLoad = function (forcedExtension) { if (this.delayLoadState !== _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].DELAYLOADSTATE_NOTLOADED) { return; } var scene = this.getScene(); if (!scene) { return; } this.delayLoadState = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].DELAYLOADSTATE_LOADED; this._texture = this._getFromCache(this.url, this._noMipmap); if (!this._texture) { if (this._prefiltered) { this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, this._delayedOnLoad, undefined, this._format, undefined, this._createPolynomials); } else { this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, this._delayedOnLoad, undefined, this._format, forcedExtension); } } }; /** * Returns the reflection texture matrix * @returns the reflection texture matrix */ CubeTexture.prototype.getReflectionTextureMatrix = function () { return this._textureMatrix; }; /** * Sets the reflection texture matrix * @param value Reflection texture matrix */ CubeTexture.prototype.setReflectionTextureMatrix = function (value) { var _this = this; if (value.updateFlag === this._textureMatrix.updateFlag) { return; } if (value.isIdentity() !== this._textureMatrix.isIdentity()) { this.getScene().markAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].MATERIAL_TextureDirtyFlag, function (mat) { return mat.getActiveTextures().indexOf(_this) !== -1; }); } this._textureMatrix = value; }; /** * Parses text to create a cube texture * @param parsedTexture define the serialized text to read from * @param scene defines the hosting scene * @param rootUrl defines the root url of the cube texture * @returns a cube texture */ CubeTexture.Parse = function (parsedTexture, scene, rootUrl) { var texture = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { var prefiltered = false; if (parsedTexture.prefiltered) { prefiltered = parsedTexture.prefiltered; } return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered); }, parsedTexture, scene); // Local Cubemaps if (parsedTexture.boundingBoxPosition) { texture.boundingBoxPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].FromArray(parsedTexture.boundingBoxPosition); } if (parsedTexture.boundingBoxSize) { texture.boundingBoxSize = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].FromArray(parsedTexture.boundingBoxSize); } // Animations if (parsedTexture.animations) { for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) { var parsedAnimation = parsedTexture.animations[animationIndex]; var internalClass = _Misc_typeStore__WEBPACK_IMPORTED_MODULE_7__["_TypeStore"].GetClass("BABYLON.Animation"); if (internalClass) { texture.animations.push(internalClass.Parse(parsedAnimation)); } } } return texture; }; /** * Makes a clone, or deep copy, of the cube texture * @returns a new cube texture */ CubeTexture.prototype.clone = function () { var _this = this; var scene = this.getScene(); var uniqueId = 0; var newCubeTexture = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { if (!scene) { return _this; } var cubeTexture = new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files); uniqueId = cubeTexture.uniqueId; return cubeTexture; }, this); newCubeTexture.uniqueId = uniqueId; return newCubeTexture; }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("rotationY") ], CubeTexture.prototype, "rotationY", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsMatrix"])("textureMatrix") ], CubeTexture.prototype, "_textureMatrix", void 0); return CubeTexture; }(_Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_4__["BaseTexture"])); _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"]._CubeTextureParser = CubeTexture.Parse; // Some exporters relies on Tools.Instantiate _Misc_typeStore__WEBPACK_IMPORTED_MODULE_7__["_TypeStore"].RegisteredTypes["BABYLON.CubeTexture"] = CubeTexture; /***/ }), /***/ "./Materials/Textures/dynamicTexture.ts": /*!**********************************************!*\ !*** ./Materials/Textures/dynamicTexture.ts ***! \**********************************************/ /*! exports provided: DynamicTexture */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DynamicTexture", function() { return DynamicTexture; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); /** * A class extending Texture allowing drawing on a texture * @see http://doc.babylonjs.com/how_to/dynamictexture */ var DynamicTexture = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](DynamicTexture, _super); /** * Creates a DynamicTexture * @param name defines the name of the texture * @param options provides 3 alternatives for width and height of texture, a canvas, object with width and height properties, number for both width and height * @param scene defines the scene where you want the texture * @param generateMipMaps defines the use of MinMaps or not (default is false) * @param samplingMode defines the sampling mode to use (default is Texture.TRILINEAR_SAMPLINGMODE) * @param format defines the texture format to use (default is Engine.TEXTUREFORMAT_RGBA) */ function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) { if (scene === void 0) { scene = null; } if (samplingMode === void 0) { samplingMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; } if (format === void 0) { format = _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTUREFORMAT_RGBA; } var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this; _this.name = name; _this._engine = _this.getScene().getEngine(); _this.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_2__["Texture"].CLAMP_ADDRESSMODE; _this.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_2__["Texture"].CLAMP_ADDRESSMODE; _this._generateMipMaps = generateMipMaps; if (options.getContext) { _this._canvas = options; _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode); } else { _this._canvas = document.createElement("canvas"); if (options.width || options.width === 0) { _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode); } else { _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode); } } var textureSize = _this.getSize(); _this._canvas.width = textureSize.width; _this._canvas.height = textureSize.height; _this._context = _this._canvas.getContext("2d"); return _this; } /** * Get the current class name of the texture useful for serialization or dynamic coding. * @returns "DynamicTexture" */ DynamicTexture.prototype.getClassName = function () { return "DynamicTexture"; }; Object.defineProperty(DynamicTexture.prototype, "canRescale", { /** * Gets the current state of canRescale */ get: function () { return true; }, enumerable: true, configurable: true }); DynamicTexture.prototype._recreate = function (textureSize) { this._canvas.width = textureSize.width; this._canvas.height = textureSize.height; this.releaseInternalTexture(); this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this.samplingMode); }; /** * Scales the texture * @param ratio the scale factor to apply to both width and height */ DynamicTexture.prototype.scale = function (ratio) { var textureSize = this.getSize(); textureSize.width *= ratio; textureSize.height *= ratio; this._recreate(textureSize); }; /** * Resizes the texture * @param width the new width * @param height the new height */ DynamicTexture.prototype.scaleTo = function (width, height) { var textureSize = this.getSize(); textureSize.width = width; textureSize.height = height; this._recreate(textureSize); }; /** * Gets the context of the canvas used by the texture * @returns the canvas context of the dynamic texture */ DynamicTexture.prototype.getContext = function () { return this._context; }; /** * Clears the texture */ DynamicTexture.prototype.clear = function () { var size = this.getSize(); this._context.fillRect(0, 0, size.width, size.height); }; /** * Updates the texture * @param invertY defines the direction for the Y axis (default is true - y increases downwards) * @param premulAlpha defines if alpha is stored as premultiplied (default is false) */ DynamicTexture.prototype.update = function (invertY, premulAlpha) { if (premulAlpha === void 0) { premulAlpha = false; } this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined); }; /** * Draws text onto the texture * @param text defines the text to be drawn * @param x defines the placement of the text from the left * @param y defines the placement of the text from the top when invertY is true and from the bottom when false * @param font defines the font to be used with font-style, font-size, font-name * @param color defines the color used for the text * @param clearColor defines the color for the canvas, use null to not overwrite canvas * @param invertY defines the direction for the Y axis (default is true - y increases downwards) * @param update defines whether texture is immediately update (default is true) */ DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) { if (update === void 0) { update = true; } var size = this.getSize(); if (clearColor) { this._context.fillStyle = clearColor; this._context.fillRect(0, 0, size.width, size.height); } this._context.font = font; if (x === null || x === undefined) { var textSize = this._context.measureText(text); x = (size.width - textSize.width) / 2; } if (y === null || y === undefined) { var fontSize = parseInt((font.replace(/\D/g, ''))); y = (size.height / 2) + (fontSize / 3.65); } this._context.fillStyle = color; this._context.fillText(text, x, y); if (update) { this.update(invertY); } }; /** * Clones the texture * @returns the clone of the texture. */ DynamicTexture.prototype.clone = function () { var scene = this.getScene(); if (!scene) { return this; } var textureSize = this.getSize(); var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps); // Base texture newTexture.hasAlpha = this.hasAlpha; newTexture.level = this.level; // Dynamic Texture newTexture.wrapU = this.wrapU; newTexture.wrapV = this.wrapV; return newTexture; }; /** * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized * @returns a serialized dynamic texture object */ DynamicTexture.prototype.serialize = function () { var scene = this.getScene(); if (scene && !scene.isReady()) { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("The scene must be ready before serializing the dynamic texture"); } var serializationObject = _super.prototype.serialize.call(this); serializationObject.base64String = this._canvas.toDataURL(); serializationObject.invertY = this._invertY; serializationObject.samplingMode = this.samplingMode; return serializationObject; }; /** @hidden */ DynamicTexture.prototype._rebuild = function () { this.update(); }; return DynamicTexture; }(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_2__["Texture"])); /***/ }), /***/ "./Materials/Textures/equiRectangularCubeTexture.ts": /*!**********************************************************!*\ !*** ./Materials/Textures/equiRectangularCubeTexture.ts ***! \**********************************************************/ /*! exports provided: EquiRectangularCubeTexture */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EquiRectangularCubeTexture", function() { return EquiRectangularCubeTexture; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_HighDynamicRange_panoramaToCubemap__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/HighDynamicRange/panoramaToCubemap */ "./Misc/HighDynamicRange/panoramaToCubemap.ts"); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Engines/engine */ "./Engines/engine.ts"); /* harmony import */ var _baseTexture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./baseTexture */ "./Materials/Textures/baseTexture.ts"); /* harmony import */ var _texture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./texture */ "./Materials/Textures/texture.ts"); /** * This represents a texture coming from an equirectangular image supported by the web browser canvas. */ var EquiRectangularCubeTexture = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](EquiRectangularCubeTexture, _super); /** * Instantiates an EquiRectangularCubeTexture from the following parameters. * @param url The location of the image * @param scene The scene the texture will be used in * @param size The cubemap desired size (the more it increases the longer the generation will be) * @param noMipmap Forces to not generate the mipmap if true * @param gammaSpace Specifies if the texture will be used in gamma or linear space * (the PBR material requires those textures in linear space, but the standard material would require them in Gamma space) * @param onLoad — defines a callback called when texture is loaded * @param onError — defines a callback called if there is an error */ function EquiRectangularCubeTexture(url, scene, size, noMipmap, gammaSpace, onLoad, onError) { if (noMipmap === void 0) { noMipmap = false; } if (gammaSpace === void 0) { gammaSpace = true; } if (onLoad === void 0) { onLoad = null; } if (onError === void 0) { onError = null; } var _this = _super.call(this, scene) || this; _this._onLoad = null; _this._onError = null; /** The texture coordinates mode. As this texture is stored in a cube format, please modify carefully. */ _this.coordinatesMode = _texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].CUBIC_MODE; if (!url) { throw new Error('Image url is not set'); } _this.name = url; _this.url = url; _this._size = size; _this._noMipmap = noMipmap; _this.gammaSpace = gammaSpace; _this._onLoad = onLoad; _this._onError = onError; _this.hasAlpha = false; _this.isCube = true; _this._texture = _this._getFromCache(url, _this._noMipmap); if (!_this._texture) { if (!scene.useDelayedTextureLoading) { _this.loadImage(_this.loadTexture.bind(_this)); } else { _this.delayLoadState = _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].DELAYLOADSTATE_NOTLOADED; } } return _this; } /** * Load the image data, by putting the image on a canvas and extracting its buffer. */ EquiRectangularCubeTexture.prototype.loadImage = function (loadTextureCallback) { var _this = this; var canvas = document.createElement('canvas'); var image = new Image(); image.addEventListener('load', function () { _this._width = image.width; _this._height = image.height; canvas.width = _this._width; canvas.height = _this._height; var ctx = canvas.getContext('2d'); ctx.drawImage(image, 0, 0); var imageData = ctx.getImageData(0, 0, image.width, image.height); _this._buffer = imageData.data.buffer; canvas.remove(); loadTextureCallback(); }); image.src = this.url; }; /** * Convert the image buffer into a cubemap and create a CubeTexture. */ EquiRectangularCubeTexture.prototype.loadTexture = function () { var _this = this; var scene = this.getScene(); var callback = function () { var imageData = _this.getFloat32ArrayFromArrayBuffer(_this._buffer); // Extract the raw linear data. var data = _Misc_HighDynamicRange_panoramaToCubemap__WEBPACK_IMPORTED_MODULE_1__["PanoramaToCubeMapTools"].ConvertPanoramaToCubemap(imageData, _this._width, _this._height, _this._size); var results = []; // Push each faces. for (var i = 0; i < 6; i++) { var dataFace = data[EquiRectangularCubeTexture._FacesMapping[i]]; results.push(dataFace); } return results; }; if (!scene) { return; } this._texture = scene .getEngine() .createRawCubeTextureFromUrl(this.url, scene, this._size, _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].TEXTURETYPE_FLOAT : _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].TEXTURETYPE_UNSIGNED_INTEGER, this._noMipmap, callback, null, this._onLoad, this._onError); }; /** * Convert the ArrayBuffer into a Float32Array and drop the transparency channel. * @param buffer The ArrayBuffer that should be converted. * @returns The buffer as Float32Array. */ EquiRectangularCubeTexture.prototype.getFloat32ArrayFromArrayBuffer = function (buffer) { var dataView = new DataView(buffer); var floatImageData = new Float32Array((buffer.byteLength * 3) / 4); var k = 0; for (var i = 0; i < buffer.byteLength; i++) { // We drop the transparency channel, because we do not need/want it if ((i + 1) % 4 !== 0) { floatImageData[k++] = dataView.getUint8(i) / 255; } } return floatImageData; }; /** * Get the current class name of the texture useful for serialization or dynamic coding. * @returns "EquiRectangularCubeTexture" */ EquiRectangularCubeTexture.prototype.getClassName = function () { return "EquiRectangularCubeTexture"; }; /** * Create a clone of the current EquiRectangularCubeTexture and return it. * @returns A clone of the current EquiRectangularCubeTexture. */ EquiRectangularCubeTexture.prototype.clone = function () { var scene = this.getScene(); if (!scene) { return this; } var newTexture = new EquiRectangularCubeTexture(this.url, scene, this._size, this._noMipmap, this.gammaSpace); // Base texture newTexture.level = this.level; newTexture.wrapU = this.wrapU; newTexture.wrapV = this.wrapV; newTexture.coordinatesIndex = this.coordinatesIndex; newTexture.coordinatesMode = this.coordinatesMode; return newTexture; }; /** The six faces of the cube. */ EquiRectangularCubeTexture._FacesMapping = ['right', 'left', 'up', 'down', 'front', 'back']; return EquiRectangularCubeTexture; }(_baseTexture__WEBPACK_IMPORTED_MODULE_3__["BaseTexture"])); /***/ }), /***/ "./Materials/Textures/hdrCubeTexture.ts": /*!**********************************************!*\ !*** ./Materials/Textures/hdrCubeTexture.ts ***! \**********************************************/ /*! exports provided: HDRCubeTexture */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HDRCubeTexture", function() { return HDRCubeTexture; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Engines/engine */ "./Engines/engine.ts"); /* harmony import */ var _Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Materials/Textures/baseTexture */ "./Materials/Textures/baseTexture.ts"); /* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); /* harmony import */ var _Misc_HighDynamicRange_hdr__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Misc/HighDynamicRange/hdr */ "./Misc/HighDynamicRange/hdr.ts"); /* harmony import */ var _Misc_HighDynamicRange_cubemapToSphericalPolynomial__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Misc/HighDynamicRange/cubemapToSphericalPolynomial */ "./Misc/HighDynamicRange/cubemapToSphericalPolynomial.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts"); /** * This represents a texture coming from an HDR input. * * The only supported format is currently panorama picture stored in RGBE format. * Example of such files can be found on HDRLib: http://hdrlib.com/ */ var HDRCubeTexture = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](HDRCubeTexture, _super); /** * Instantiates an HDRTexture from the following parameters. * * @param url The location of the HDR raw data (Panorama stored in RGBE format) * @param scene The scene the texture will be used in * @param size The cubemap desired size (the more it increases the longer the generation will be) * @param noMipmap Forces to not generate the mipmap if true * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process * @param gammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) * @param reserved Reserved flag for internal use. */ function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) { if (noMipmap === void 0) { noMipmap = false; } if (generateHarmonics === void 0) { generateHarmonics = true; } if (gammaSpace === void 0) { gammaSpace = false; } if (reserved === void 0) { reserved = false; } if (onLoad === void 0) { onLoad = null; } if (onError === void 0) { onError = null; } var _this = _super.call(this, scene) || this; _this._generateHarmonics = true; _this._onLoad = null; _this._onError = null; /** * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully. */ _this.coordinatesMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].CUBIC_MODE; _this._isBlocking = true; _this._rotationY = 0; /** * Gets or sets the center of the bounding box associated with the cube texture * It must define where the camera used to render the texture was set */ _this.boundingBoxPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); if (!url) { return _this; } _this.name = url; _this.url = url; _this.hasAlpha = false; _this.isCube = true; _this._textureMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(); _this._onLoad = onLoad; _this._onError = onError; _this.gammaSpace = gammaSpace; _this._noMipmap = noMipmap; _this._size = size; _this._texture = _this._getFromCache(url, _this._noMipmap); if (!_this._texture) { if (!scene.useDelayedTextureLoading) { _this.loadTexture(); } else { _this.delayLoadState = _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].DELAYLOADSTATE_NOTLOADED; } } return _this; } Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", { /** * Gets wether or not the texture is blocking during loading. */ get: function () { return this._isBlocking; }, /** * Sets wether or not the texture is blocking during loading. */ set: function (value) { this._isBlocking = value; }, enumerable: true, configurable: true }); Object.defineProperty(HDRCubeTexture.prototype, "rotationY", { /** * Gets texture matrix rotation angle around Y axis radians. */ get: function () { return this._rotationY; }, /** * Sets texture matrix rotation angle around Y axis in radians. */ set: function (value) { this._rotationY = value; this.setReflectionTextureMatrix(_Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].RotationY(this._rotationY)); }, enumerable: true, configurable: true }); Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", { get: function () { return this._boundingBoxSize; }, /** * Gets or sets the size of the bounding box associated with the cube texture * When defined, the cubemap will switch to local mode * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity * @example https://www.babylonjs-playground.com/#RNASML */ set: function (value) { if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) { return; } this._boundingBoxSize = value; var scene = this.getScene(); if (scene) { scene.markAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].MATERIAL_TextureDirtyFlag); } }, enumerable: true, configurable: true }); /** * Get the current class name of the texture useful for serialization or dynamic coding. * @returns "HDRCubeTexture" */ HDRCubeTexture.prototype.getClassName = function () { return "HDRCubeTexture"; }; /** * Occurs when the file is raw .hdr file. */ HDRCubeTexture.prototype.loadTexture = function () { var _this = this; var callback = function (buffer) { _this.lodGenerationOffset = 0.0; _this.lodGenerationScale = 0.8; var scene = _this.getScene(); if (!scene) { return null; } // Extract the raw linear data. var data = _Misc_HighDynamicRange_hdr__WEBPACK_IMPORTED_MODULE_6__["HDRTools"].GetCubeMapTextureData(buffer, _this._size); // Generate harmonics if needed. if (_this._generateHarmonics) { var sphericalPolynomial = _Misc_HighDynamicRange_cubemapToSphericalPolynomial__WEBPACK_IMPORTED_MODULE_7__["CubeMapToSphericalPolynomialTools"].ConvertCubeMapToSphericalPolynomial(data); _this.sphericalPolynomial = sphericalPolynomial; } var results = []; var byteArray = null; // Push each faces. for (var j = 0; j < 6; j++) { // Create uintarray fallback. if (!scene.getEngine().getCaps().textureFloat) { // 3 channels of 1 bytes per pixel in bytes. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3); byteArray = new Uint8Array(byteBuffer); } var dataFace = (data[HDRCubeTexture._facesMapping[j]]); // If special cases. if (_this.gammaSpace || byteArray) { for (var i = 0; i < _this._size * _this._size; i++) { // Put in gamma space if requested. if (_this.gammaSpace) { dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], _Maths_math__WEBPACK_IMPORTED_MODULE_1__["ToGammaSpace"]); dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], _Maths_math__WEBPACK_IMPORTED_MODULE_1__["ToGammaSpace"]); dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], _Maths_math__WEBPACK_IMPORTED_MODULE_1__["ToGammaSpace"]); } // Convert to int texture for fallback. if (byteArray) { var r = Math.max(dataFace[(i * 3) + 0] * 255, 0); var g = Math.max(dataFace[(i * 3) + 1] * 255, 0); var b = Math.max(dataFace[(i * 3) + 2] * 255, 0); // May use luminance instead if the result is not accurate. var max = Math.max(Math.max(r, g), b); if (max > 255) { var scale = 255 / max; r *= scale; g *= scale; b *= scale; } byteArray[(i * 3) + 0] = r; byteArray[(i * 3) + 1] = g; byteArray[(i * 3) + 2] = b; } } } if (byteArray) { results.push(byteArray); } else { results.push(dataFace); } } return results; }; var scene = this.getScene(); if (scene) { this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].TEXTURETYPE_FLOAT : _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, null, this._onLoad, this._onError); } }; HDRCubeTexture.prototype.clone = function () { var scene = this.getScene(); if (!scene) { return this; } var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace); // Base texture newTexture.level = this.level; newTexture.wrapU = this.wrapU; newTexture.wrapV = this.wrapV; newTexture.coordinatesIndex = this.coordinatesIndex; newTexture.coordinatesMode = this.coordinatesMode; return newTexture; }; // Methods HDRCubeTexture.prototype.delayLoad = function () { if (this.delayLoadState !== _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].DELAYLOADSTATE_NOTLOADED) { return; } this.delayLoadState = _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].DELAYLOADSTATE_LOADED; this._texture = this._getFromCache(this.url, this._noMipmap); if (!this._texture) { this.loadTexture(); } }; /** * Get the texture reflection matrix used to rotate/transform the reflection. * @returns the reflection matrix */ HDRCubeTexture.prototype.getReflectionTextureMatrix = function () { return this._textureMatrix; }; /** * Set the texture reflection matrix used to rotate/transform the reflection. * @param value Define the reflection matrix to set */ HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) { var _this = this; this._textureMatrix = value; if (value.updateFlag === this._textureMatrix.updateFlag) { return; } if (value.isIdentity() !== this._textureMatrix.isIdentity()) { this.getScene().markAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].MATERIAL_TextureDirtyFlag, function (mat) { return mat.getActiveTextures().indexOf(_this) !== -1; }); } }; /** * Parses a JSON representation of an HDR Texture in order to create the texture * @param parsedTexture Define the JSON representation * @param scene Define the scene the texture should be created in * @param rootUrl Define the root url in case we need to load relative dependencies * @returns the newly created texture after parsing */ HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) { var texture = null; if (parsedTexture.name && !parsedTexture.isRenderTarget) { texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace); texture.name = parsedTexture.name; texture.hasAlpha = parsedTexture.hasAlpha; texture.level = parsedTexture.level; texture.coordinatesMode = parsedTexture.coordinatesMode; texture.isBlocking = parsedTexture.isBlocking; } if (texture) { if (parsedTexture.boundingBoxPosition) { texture.boundingBoxPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].FromArray(parsedTexture.boundingBoxPosition); } if (parsedTexture.boundingBoxSize) { texture.boundingBoxSize = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].FromArray(parsedTexture.boundingBoxSize); } if (parsedTexture.rotationY) { texture.rotationY = parsedTexture.rotationY; } } return texture; }; HDRCubeTexture.prototype.serialize = function () { if (!this.name) { return null; } var serializationObject = {}; serializationObject.name = this.name; serializationObject.hasAlpha = this.hasAlpha; serializationObject.isCube = true; serializationObject.level = this.level; serializationObject.size = this._size; serializationObject.coordinatesMode = this.coordinatesMode; serializationObject.useInGammaSpace = this.gammaSpace; serializationObject.generateHarmonics = this._generateHarmonics; serializationObject.customType = "BABYLON.HDRCubeTexture"; serializationObject.noMipmap = this._noMipmap; serializationObject.isBlocking = this._isBlocking; serializationObject.rotationY = this._rotationY; return serializationObject; }; HDRCubeTexture._facesMapping = [ "right", "left", "up", "down", "front", "back" ]; return HDRCubeTexture; }(_Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_3__["BaseTexture"])); _Misc_typeStore__WEBPACK_IMPORTED_MODULE_8__["_TypeStore"].RegisteredTypes["BABYLON.HDRCubeTexture"] = HDRCubeTexture; /***/ }), /***/ "./Materials/Textures/index.ts": /*!*************************************!*\ !*** ./Materials/Textures/index.ts ***! \*************************************/ /*! exports provided: BaseTexture, CubeTexture, EquiRectangularCubeTexture, HDRCubeTexture, InternalTexture, MirrorTexture, MultiRenderTarget, RawTexture, RenderTargetTexture, Texture, ColorGradingTexture, DynamicTexture, ProceduralTexture, RawCubeTexture, RawTexture3D, RefractionTexture, VideoTexture, _DDSTextureLoader, _ENVTextureLoader, _KTXTextureLoader, _TGATextureLoader, CustomProceduralTexture, NoiseProceduralTexture, ProceduralTextureSceneComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _baseTexture__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./baseTexture */ "./Materials/Textures/baseTexture.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BaseTexture", function() { return _baseTexture__WEBPACK_IMPORTED_MODULE_0__["BaseTexture"]; }); /* harmony import */ var _colorGradingTexture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./colorGradingTexture */ "./Materials/Textures/colorGradingTexture.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorGradingTexture", function() { return _colorGradingTexture__WEBPACK_IMPORTED_MODULE_1__["ColorGradingTexture"]; }); /* harmony import */ var _cubeTexture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./cubeTexture */ "./Materials/Textures/cubeTexture.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CubeTexture", function() { return _cubeTexture__WEBPACK_IMPORTED_MODULE_2__["CubeTexture"]; }); /* harmony import */ var _dynamicTexture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./dynamicTexture */ "./Materials/Textures/dynamicTexture.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DynamicTexture", function() { return _dynamicTexture__WEBPACK_IMPORTED_MODULE_3__["DynamicTexture"]; }); /* harmony import */ var _equiRectangularCubeTexture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./equiRectangularCubeTexture */ "./Materials/Textures/equiRectangularCubeTexture.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EquiRectangularCubeTexture", function() { return _equiRectangularCubeTexture__WEBPACK_IMPORTED_MODULE_4__["EquiRectangularCubeTexture"]; }); /* harmony import */ var _hdrCubeTexture__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./hdrCubeTexture */ "./Materials/Textures/hdrCubeTexture.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HDRCubeTexture", function() { return _hdrCubeTexture__WEBPACK_IMPORTED_MODULE_5__["HDRCubeTexture"]; }); /* harmony import */ var _internalTexture__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./internalTexture */ "./Materials/Textures/internalTexture.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InternalTexture", function() { return _internalTexture__WEBPACK_IMPORTED_MODULE_6__["InternalTexture"]; }); /* harmony import */ var _Loaders_index__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Loaders/index */ "./Materials/Textures/Loaders/index.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_DDSTextureLoader", function() { return _Loaders_index__WEBPACK_IMPORTED_MODULE_7__["_DDSTextureLoader"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_ENVTextureLoader", function() { return _Loaders_index__WEBPACK_IMPORTED_MODULE_7__["_ENVTextureLoader"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_KTXTextureLoader", function() { return _Loaders_index__WEBPACK_IMPORTED_MODULE_7__["_KTXTextureLoader"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_TGATextureLoader", function() { return _Loaders_index__WEBPACK_IMPORTED_MODULE_7__["_TGATextureLoader"]; }); /* harmony import */ var _mirrorTexture__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./mirrorTexture */ "./Materials/Textures/mirrorTexture.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MirrorTexture", function() { return _mirrorTexture__WEBPACK_IMPORTED_MODULE_8__["MirrorTexture"]; }); /* harmony import */ var _multiRenderTarget__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./multiRenderTarget */ "./Materials/Textures/multiRenderTarget.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiRenderTarget", function() { return _multiRenderTarget__WEBPACK_IMPORTED_MODULE_9__["MultiRenderTarget"]; }); /* harmony import */ var _Procedurals_index__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Procedurals/index */ "./Materials/Textures/Procedurals/index.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ProceduralTexture", function() { return _Procedurals_index__WEBPACK_IMPORTED_MODULE_10__["ProceduralTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CustomProceduralTexture", function() { return _Procedurals_index__WEBPACK_IMPORTED_MODULE_10__["CustomProceduralTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NoiseProceduralTexture", function() { return _Procedurals_index__WEBPACK_IMPORTED_MODULE_10__["NoiseProceduralTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ProceduralTextureSceneComponent", function() { return _Procedurals_index__WEBPACK_IMPORTED_MODULE_10__["ProceduralTextureSceneComponent"]; }); /* harmony import */ var _rawCubeTexture__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./rawCubeTexture */ "./Materials/Textures/rawCubeTexture.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RawCubeTexture", function() { return _rawCubeTexture__WEBPACK_IMPORTED_MODULE_11__["RawCubeTexture"]; }); /* harmony import */ var _rawTexture__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./rawTexture */ "./Materials/Textures/rawTexture.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RawTexture", function() { return _rawTexture__WEBPACK_IMPORTED_MODULE_12__["RawTexture"]; }); /* harmony import */ var _rawTexture3D__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./rawTexture3D */ "./Materials/Textures/rawTexture3D.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RawTexture3D", function() { return _rawTexture3D__WEBPACK_IMPORTED_MODULE_13__["RawTexture3D"]; }); /* harmony import */ var _refractionTexture__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./refractionTexture */ "./Materials/Textures/refractionTexture.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RefractionTexture", function() { return _refractionTexture__WEBPACK_IMPORTED_MODULE_14__["RefractionTexture"]; }); /* harmony import */ var _renderTargetTexture__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RenderTargetTexture", function() { return _renderTargetTexture__WEBPACK_IMPORTED_MODULE_15__["RenderTargetTexture"]; }); /* harmony import */ var _texture__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./texture */ "./Materials/Textures/texture.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Texture", function() { return _texture__WEBPACK_IMPORTED_MODULE_16__["Texture"]; }); /* harmony import */ var _videoTexture__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./videoTexture */ "./Materials/Textures/videoTexture.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VideoTexture", function() { return _videoTexture__WEBPACK_IMPORTED_MODULE_17__["VideoTexture"]; }); /***/ }), /***/ "./Materials/Textures/internalTexture.ts": /*!***********************************************!*\ !*** ./Materials/Textures/internalTexture.ts ***! \***********************************************/ /*! exports provided: InternalTexture */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InternalTexture", function() { return InternalTexture; }); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Materials_Textures_renderTargetCreationOptions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Materials/Textures/renderTargetCreationOptions */ "./Materials/Textures/renderTargetCreationOptions.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); /* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/devTools */ "./Misc/devTools.ts"); /** * Class used to store data associated with WebGL texture data for the engine * This class should not be used directly */ var InternalTexture = /** @class */ (function () { /** * Creates a new InternalTexture * @param engine defines the engine to use * @param dataSource defines the type of data that will be used * @param delayAllocation if the texture allocation should be delayed (default: false) */ function InternalTexture(engine, dataSource, delayAllocation) { if (delayAllocation === void 0) { delayAllocation = false; } /** * Observable called when the texture is loaded */ this.onLoadedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); // Private /** @hidden */ this._invertVScale = false; /** @hidden */ this._associatedChannel = -1; /** @hidden */ this._dataSource = InternalTexture.DATASOURCE_UNKNOWN; /** @hidden */ this._comparisonFunction = 0; /** @hidden */ this._sphericalPolynomial = null; /** @hidden */ this._lodGenerationScale = 0; /** @hidden */ this._lodGenerationOffset = 0; /** @hidden */ this._isRGBD = false; /** @hidden */ this._references = 1; this._engine = engine; this._dataSource = dataSource; if (!delayAllocation) { this._webGLTexture = engine._createTexture(); } } /** * Gets the Engine the texture belongs to. * @returns The babylon engine */ InternalTexture.prototype.getEngine = function () { return this._engine; }; Object.defineProperty(InternalTexture.prototype, "dataSource", { /** * Gets the data source type of the texture (can be one of the InternalTexture.DATASOURCE_XXXX) */ get: function () { return this._dataSource; }, enumerable: true, configurable: true }); /** * Increments the number of references (ie. the number of Texture that point to it) */ InternalTexture.prototype.incrementReferences = function () { 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) */ InternalTexture.prototype.updateSize = function (width, height, depth) { if (depth === void 0) { depth = 1; } this.width = width; this.height = height; this.depth = depth; this.baseWidth = width; this.baseHeight = height; this.baseDepth = depth; this._size = width * height * depth; }; /** @hidden */ InternalTexture.prototype._rebuild = function () { var _this = this; var proxy; this.isReady = false; this._cachedCoordinatesMode = null; this._cachedWrapU = null; this._cachedWrapV = null; this._cachedAnisotropicFilteringLevel = null; switch (this._dataSource) { case InternalTexture.DATASOURCE_TEMP: return; case InternalTexture.DATASOURCE_URL: proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () { proxy._swapAndDie(_this); _this.isReady = true; }, null, this._buffer, undefined, this.format); return; case InternalTexture.DATASOURCE_RAW: proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression); proxy._swapAndDie(this); this.isReady = true; return; case InternalTexture.DATASOURCE_RAW3D: proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression); proxy._swapAndDie(this); this.isReady = true; return; case InternalTexture.DATASOURCE_DYNAMIC: proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode); proxy._swapAndDie(this); this._engine.updateDynamicTexture(this, this._engine.getRenderingCanvas(), this.invertY, undefined, undefined, true); // The engine will make sure to update content so no need to flag it as isReady = true return; case InternalTexture.DATASOURCE_RENDERTARGET: var options = new _Materials_Textures_renderTargetCreationOptions__WEBPACK_IMPORTED_MODULE_1__["RenderTargetCreationOptions"](); options.generateDepthBuffer = this._generateDepthBuffer; options.generateMipMaps = this.generateMipMaps; options.generateStencilBuffer = this._generateStencilBuffer; options.samplingMode = this.samplingMode; options.type = this.type; if (this.isCube) { proxy = this._engine.createRenderTargetCubeTexture(this.width, options); } else { var size = { width: this.width, height: this.height }; proxy = this._engine.createRenderTargetTexture(size, options); } proxy._swapAndDie(this); this.isReady = true; return; case InternalTexture.DATASOURCE_DEPTHTEXTURE: var depthTextureOptions = { bilinearFiltering: this.samplingMode !== _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_BILINEAR_SAMPLINGMODE, comparisonFunction: this._comparisonFunction, generateStencil: this._generateStencilBuffer, isCube: this.isCube }; proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions); proxy._swapAndDie(this); this.isReady = true; return; case InternalTexture.DATASOURCE_CUBE: proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () { proxy._swapAndDie(_this); _this.isReady = true; }, null, this.format, this._extension); return; case InternalTexture.DATASOURCE_CUBERAW: proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression); proxy._swapAndDie(this); this.isReady = true; return; case InternalTexture.DATASOURCE_CUBERAW_RGBD: proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression); InternalTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () { proxy._swapAndDie(_this); _this.isReady = true; }); return; case InternalTexture.DATASOURCE_CUBEPREFILTERED: proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) { if (proxy) { proxy._swapAndDie(_this); } _this.isReady = true; }, null, this.format, this._extension); proxy._sphericalPolynomial = this._sphericalPolynomial; return; } }; /** @hidden */ InternalTexture.prototype._swapAndDie = function (target) { target._webGLTexture = this._webGLTexture; target._isRGBD = this._isRGBD; if (this._framebuffer) { target._framebuffer = this._framebuffer; } if (this._depthStencilBuffer) { target._depthStencilBuffer = this._depthStencilBuffer; } 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; } var cache = this._engine.getLoadedTexturesCache(); var index = cache.indexOf(this); if (index !== -1) { cache.splice(index, 1); } }; /** * Dispose the current allocated resources */ InternalTexture.prototype.dispose = function () { if (!this._webGLTexture) { return; } this._references--; if (this._references === 0) { this._engine._releaseTexture(this); this._webGLTexture = null; } }; /** hidden */ InternalTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) { throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_3__["_DevTools"].WarnImport("environmentTextureTools"); }; /** * The source of the texture data is unknown */ InternalTexture.DATASOURCE_UNKNOWN = 0; /** * Texture data comes from an URL */ InternalTexture.DATASOURCE_URL = 1; /** * Texture data is only used for temporary storage */ InternalTexture.DATASOURCE_TEMP = 2; /** * Texture data comes from raw data (ArrayBuffer) */ InternalTexture.DATASOURCE_RAW = 3; /** * Texture content is dynamic (video or dynamic texture) */ InternalTexture.DATASOURCE_DYNAMIC = 4; /** * Texture content is generated by rendering to it */ InternalTexture.DATASOURCE_RENDERTARGET = 5; /** * Texture content is part of a multi render target process */ InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6; /** * Texture data comes from a cube data file */ InternalTexture.DATASOURCE_CUBE = 7; /** * Texture data comes from a raw cube data */ InternalTexture.DATASOURCE_CUBERAW = 8; /** * Texture data come from a prefiltered cube data file */ InternalTexture.DATASOURCE_CUBEPREFILTERED = 9; /** * Texture content is raw 3D data */ InternalTexture.DATASOURCE_RAW3D = 10; /** * Texture content is a depth texture */ InternalTexture.DATASOURCE_DEPTHTEXTURE = 11; /** * Texture data comes from a raw cube data encoded with RGBD */ InternalTexture.DATASOURCE_CUBERAW_RGBD = 12; return InternalTexture; }()); /***/ }), /***/ "./Materials/Textures/mirrorTexture.ts": /*!*********************************************!*\ !*** ./Materials/Textures/mirrorTexture.ts ***! \*********************************************/ /*! exports provided: MirrorTexture */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MirrorTexture", function() { return MirrorTexture; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); /* harmony import */ var _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Materials/Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts"); /* harmony import */ var _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../PostProcesses/blurPostProcess */ "./PostProcesses/blurPostProcess.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); /** * Mirror texture can be used to simulate the view from a mirror in a scene. * It will dynamically be rendered every frame to adapt to the camera point of view. * You can then easily use it as a reflectionTexture on a flat surface. * In case the surface is not a plane, please consider relying on reflection probes. * @see https://doc.babylonjs.com/how_to/reflect#mirrors */ var MirrorTexture = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MirrorTexture, _super); /** * Instantiates a Mirror Texture. * Mirror texture can be used to simulate the view from a mirror in a scene. * It will dynamically be rendered every frame to adapt to the camera point of view. * You can then easily use it as a reflectionTexture on a flat surface. * In case the surface is not a plane, please consider relying on reflection probes. * @see https://doc.babylonjs.com/how_to/reflect#mirrors * @param name * @param size * @param scene * @param generateMipMaps * @param type * @param samplingMode * @param generateDepthBuffer */ function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) { if (type === void 0) { type = _Engines_constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURETYPE_UNSIGNED_INT; } if (samplingMode === void 0) { samplingMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_2__["Texture"].BILINEAR_SAMPLINGMODE; } if (generateDepthBuffer === void 0) { generateDepthBuffer = true; } var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this; _this.scene = scene; /** * Define the reflection plane we want to use. The mirrorPlane is usually set to the constructed reflector. * It is possible to directly set the mirrorPlane by directly using a Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the mirrorPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the reflector as stated in the doc. * @see https://doc.babylonjs.com/how_to/reflect#mirrors */ _this.mirrorPlane = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Plane"](0, 1, 0, 1); _this._transformMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Zero(); _this._mirrorMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Zero(); _this._adaptiveBlurKernel = 0; _this._blurKernelX = 0; _this._blurKernelY = 0; _this._blurRatio = 1.0; _this.ignoreCameraViewport = true; _this._updateGammaSpace(); _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () { _this._updateGammaSpace; }); _this.onBeforeRenderObservable.add(function () { _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"].ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix); _this._savedViewMatrix = scene.getViewMatrix(); _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix); scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix()); scene.clipPlane = _this.mirrorPlane; scene.getEngine().cullBackFaces = false; scene._mirroredCameraPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix); }); _this.onAfterRenderObservable.add(function () { scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix()); scene.getEngine().cullBackFaces = true; scene._mirroredCameraPosition = null; delete scene.clipPlane; }); return _this; } Object.defineProperty(MirrorTexture.prototype, "blurRatio", { get: function () { return this._blurRatio; }, /** * Define the blur ratio used to blur the reflection if needed. */ set: function (value) { if (this._blurRatio === value) { return; } this._blurRatio = value; this._preparePostProcesses(); }, enumerable: true, configurable: true }); Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", { /** * Define the adaptive blur kernel used to blur the reflection if needed. * This will autocompute the closest best match for the `blurKernel` */ set: function (value) { this._adaptiveBlurKernel = value; this._autoComputeBlurKernel(); }, enumerable: true, configurable: true }); Object.defineProperty(MirrorTexture.prototype, "blurKernel", { /** * Define the blur kernel used to blur the reflection if needed. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you. */ set: function (value) { this.blurKernelX = value; this.blurKernelY = value; }, enumerable: true, configurable: true }); Object.defineProperty(MirrorTexture.prototype, "blurKernelX", { get: function () { return this._blurKernelX; }, /** * Define the blur kernel on the X Axis used to blur the reflection if needed. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you. */ set: function (value) { if (this._blurKernelX === value) { return; } this._blurKernelX = value; this._preparePostProcesses(); }, enumerable: true, configurable: true }); Object.defineProperty(MirrorTexture.prototype, "blurKernelY", { get: function () { return this._blurKernelY; }, /** * Define the blur kernel on the Y Axis used to blur the reflection if needed. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you. */ set: function (value) { if (this._blurKernelY === value) { return; } this._blurKernelY = value; this._preparePostProcesses(); }, enumerable: true, configurable: true }); MirrorTexture.prototype._autoComputeBlurKernel = function () { var engine = this.getScene().getEngine(); var dw = this.getRenderWidth() / engine.getRenderWidth(); var dh = this.getRenderHeight() / engine.getRenderHeight(); this.blurKernelX = this._adaptiveBlurKernel * dw; this.blurKernelY = this._adaptiveBlurKernel * dh; }; MirrorTexture.prototype._onRatioRescale = function () { if (this._sizeRatio) { this.resize(this._initialSizeParameter); if (!this._adaptiveBlurKernel) { this._preparePostProcesses(); } } if (this._adaptiveBlurKernel) { this._autoComputeBlurKernel(); } }; MirrorTexture.prototype._updateGammaSpace = function () { this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess; }; MirrorTexture.prototype._preparePostProcesses = function () { this.clearPostProcesses(true); if (this._blurKernelX && this._blurKernelY) { var engine = this.getScene().getEngine(); var textureType = engine.getCaps().textureFloatRender ? _Engines_constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURETYPE_FLOAT : _Engines_constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURETYPE_HALF_FLOAT; this._blurX = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_4__["BlurPostProcess"]("horizontal blur", new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector2"](1.0, 0), this._blurKernelX, this._blurRatio, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_2__["Texture"].BILINEAR_SAMPLINGMODE, engine, false, textureType); this._blurX.autoClear = false; if (this._blurRatio === 1 && this.samples < 2 && this._texture) { this._blurX.inputTexture = this._texture; } else { this._blurX.alwaysForcePOT = true; } this._blurY = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_4__["BlurPostProcess"]("vertical blur", new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Vector2"](0, 1.0), this._blurKernelY, this._blurRatio, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_2__["Texture"].BILINEAR_SAMPLINGMODE, engine, false, textureType); this._blurY.autoClear = false; this._blurY.alwaysForcePOT = this._blurRatio !== 1; this.addPostProcess(this._blurX); this.addPostProcess(this._blurY); } else { if (this._blurY) { this.removePostProcess(this._blurY); this._blurY.dispose(); this._blurY = null; } if (this._blurX) { this.removePostProcess(this._blurX); this._blurX.dispose(); this._blurX = null; } } }; /** * Clone the mirror texture. * @returns the cloned texture */ MirrorTexture.prototype.clone = function () { var scene = this.getScene(); if (!scene) { return this; } var textureSize = this.getSize(); var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer); // Base texture newTexture.hasAlpha = this.hasAlpha; newTexture.level = this.level; // Mirror Texture newTexture.mirrorPlane = this.mirrorPlane.clone(); if (this.renderList) { newTexture.renderList = this.renderList.slice(0); } return newTexture; }; /** * Serialize the texture to a JSON representation you could use in Parse later on * @returns the serialized JSON representation */ MirrorTexture.prototype.serialize = function () { if (!this.name) { return null; } var serializationObject = _super.prototype.serialize.call(this); serializationObject.mirrorPlane = this.mirrorPlane.asArray(); return serializationObject; }; /** * Dispose the texture and release its associated resources. */ MirrorTexture.prototype.dispose = function () { _super.prototype.dispose.call(this); this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver); }; return MirrorTexture; }(_Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_3__["RenderTargetTexture"])); _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_2__["Texture"]._CreateMirror = function (name, renderTargetSize, scene, generateMipMaps) { return new MirrorTexture(name, renderTargetSize, scene, generateMipMaps); }; /***/ }), /***/ "./Materials/Textures/multiRenderTarget.ts": /*!*************************************************!*\ !*** ./Materials/Textures/multiRenderTarget.ts ***! \*************************************************/ /*! exports provided: MultiRenderTarget */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MultiRenderTarget", function() { return MultiRenderTarget; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); /* harmony import */ var _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Materials/Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); /** * A multi render target, like a render target provides the ability to render to a texture. * Unlike the render target, it can render to several draw buffers in one draw. * This is specially interesting in deferred rendering or for any effects requiring more than * just one color from a single pass. */ var MultiRenderTarget = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MultiRenderTarget, _super); /** * Instantiate a new multi render target texture. * A multi render target, like a render target provides the ability to render to a texture. * Unlike the render target, it can render to several draw buffers in one draw. * This is specially interesting in deferred rendering or for any effects requiring more than * just one color from a single pass. * @param name Define the name of the texture * @param size Define the size of the buffers to render to * @param count Define the number of target we are rendering into * @param scene Define the scene the texture belongs to * @param options Define the options used to create the multi render target */ function MultiRenderTarget(name, size, count, scene, options) { var _this = this; var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false; var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false; var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio; _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this; _this._engine = scene.getEngine(); if (!_this.isSupported) { _this.dispose(); return; } var types = []; var samplingModes = []; for (var i = 0; i < count; i++) { if (options && options.types && options.types[i] !== undefined) { types.push(options.types[i]); } else { types.push(options && options.defaultType ? options.defaultType : _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURETYPE_UNSIGNED_INT); } if (options && options.samplingModes && options.samplingModes[i] !== undefined) { samplingModes.push(options.samplingModes[i]); } else { samplingModes.push(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_1__["Texture"].BILINEAR_SAMPLINGMODE); } } var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer; var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer; _this._size = size; _this._multiRenderTargetOptions = { samplingModes: samplingModes, generateMipMaps: generateMipMaps, generateDepthBuffer: generateDepthBuffer, generateStencilBuffer: generateStencilBuffer, generateDepthTexture: generateDepthTexture, types: types, textureCount: count }; _this._createInternalTextures(); _this._createTextures(); return _this; } Object.defineProperty(MultiRenderTarget.prototype, "isSupported", { /** * Get if draw buffers are currently supported by the used hardware and browser. */ get: function () { return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension; }, enumerable: true, configurable: true }); Object.defineProperty(MultiRenderTarget.prototype, "textures", { /** * Get the list of textures generated by the multi render target. */ get: function () { return this._textures; }, enumerable: true, configurable: true }); Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", { /** * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set */ get: function () { return this._textures[this._textures.length - 1]; }, enumerable: true, configurable: true }); Object.defineProperty(MultiRenderTarget.prototype, "wrapU", { /** * Set the wrapping mode on U of all the textures we are rendering to. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE) */ set: function (wrap) { if (this._textures) { for (var i = 0; i < this._textures.length; i++) { this._textures[i].wrapU = wrap; } } }, enumerable: true, configurable: true }); Object.defineProperty(MultiRenderTarget.prototype, "wrapV", { /** * Set the wrapping mode on V of all the textures we are rendering to. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE) */ set: function (wrap) { if (this._textures) { for (var i = 0; i < this._textures.length; i++) { this._textures[i].wrapV = wrap; } } }, enumerable: true, configurable: true }); /** @hidden */ MultiRenderTarget.prototype._rebuild = function () { this.releaseInternalTextures(); this._createInternalTextures(); for (var i = 0; i < this._internalTextures.length; i++) { var texture = this._textures[i]; texture._texture = this._internalTextures[i]; } // Keeps references to frame buffer and stencil/depth buffer this._texture = this._internalTextures[0]; }; MultiRenderTarget.prototype._createInternalTextures = function () { this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions); }; MultiRenderTarget.prototype._createTextures = function () { this._textures = []; for (var i = 0; i < this._internalTextures.length; i++) { var texture = new _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_1__["Texture"](null, this.getScene()); texture._texture = this._internalTextures[i]; this._textures.push(texture); } // Keeps references to frame buffer and stencil/depth buffer this._texture = this._internalTextures[0]; }; Object.defineProperty(MultiRenderTarget.prototype, "samples", { /** * Define the number of samples used if MSAA is enabled. */ get: function () { return this._samples; }, set: function (value) { if (this._samples === value) { return; } this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value); }, enumerable: true, configurable: true }); /** * Resize all the textures in the multi render target. * Be carrefull as it will recreate all the data in the new texture. * @param size Define the new size */ MultiRenderTarget.prototype.resize = function (size) { this.releaseInternalTextures(); this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions); this._createInternalTextures(); }; MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) { var _this = this; engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () { _this.onAfterRenderObservable.notifyObservers(faceIndex); }); }; /** * Dispose the render targets and their associated resources */ MultiRenderTarget.prototype.dispose = function () { this.releaseInternalTextures(); _super.prototype.dispose.call(this); }; /** * Release all the underlying texture used as draw buffers. */ MultiRenderTarget.prototype.releaseInternalTextures = function () { if (!this._internalTextures) { return; } for (var i = this._internalTextures.length - 1; i >= 0; i--) { if (this._internalTextures[i] !== undefined) { this._internalTextures[i].dispose(); this._internalTextures.splice(i, 1); } } }; return MultiRenderTarget; }(_Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_2__["RenderTargetTexture"])); /***/ }), /***/ "./Materials/Textures/rawCubeTexture.ts": /*!**********************************************!*\ !*** ./Materials/Textures/rawCubeTexture.ts ***! \**********************************************/ /*! exports provided: RawCubeTexture */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RawCubeTexture", function() { return RawCubeTexture; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Misc_environmentTextureTools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/environmentTextureTools */ "./Misc/environmentTextureTools.ts"); /* harmony import */ var _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Materials/Textures/internalTexture */ "./Materials/Textures/internalTexture.ts"); /* harmony import */ var _Materials_Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/Textures/cubeTexture */ "./Materials/Textures/cubeTexture.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); /** * Raw cube texture where the raw buffers are passed in */ var RawCubeTexture = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RawCubeTexture, _super); /** * Creates a cube texture where the raw buffers are passed in. * @param scene defines the scene the texture is attached to * @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_INT) * @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) */ function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) { if (format === void 0) { format = _Engines_constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTUREFORMAT_RGBA; } if (type === void 0) { type = _Engines_constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURETYPE_UNSIGNED_INT; } if (generateMipMaps === void 0) { generateMipMaps = false; } if (invertY === void 0) { invertY = false; } if (samplingMode === void 0) { samplingMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; } if (compression === void 0) { compression = null; } var _this = _super.call(this, "", scene) || this; _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression); return _this; } /** * Updates the raw cube texture. * @param data defines the data to store * @param format defines the data format * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default) * @param invertY defines if data must be stored with Y axis inverted * @param compression defines the compression used (null by default) * @param level defines which level of the texture to update */ RawCubeTexture.prototype.update = function (data, format, type, invertY, compression) { if (compression === void 0) { compression = null; } this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression); }; /** * Updates a raw cube texture with RGBD encoded data. * @param data defines the array of data [mipmap][face] to use to create each face * @param sphericalPolynomial defines the spherical polynomial for irradiance * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness * @returns a promsie that resolves when the operation is complete */ RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) { if (sphericalPolynomial === void 0) { sphericalPolynomial = null; } if (lodScale === void 0) { lodScale = 0.8; } if (lodOffset === void 0) { lodOffset = 0; } return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset); }; /** * Clones the raw cube texture. * @return a new cube texture */ RawCubeTexture.prototype.clone = function () { var _this = this; return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { var scene = _this.getScene(); var internalTexture = _this._texture; var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression); if (internalTexture.dataSource === _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_3__["InternalTexture"].DATASOURCE_CUBERAW_RGBD) { texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset); } return texture; }, this); }; /** @hidden */ RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) { internalTexture._dataSource = _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_3__["InternalTexture"].DATASOURCE_CUBERAW_RGBD; internalTexture._bufferViewArrayArray = data; internalTexture._lodGenerationScale = lodScale; internalTexture._lodGenerationOffset = lodOffset; internalTexture._sphericalPolynomial = sphericalPolynomial; return _Misc_environmentTextureTools__WEBPACK_IMPORTED_MODULE_2__["EnvironmentTextureTools"].UploadLevelsAsync(internalTexture, data).then(function () { internalTexture.isReady = true; }); }; return RawCubeTexture; }(_Materials_Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_4__["CubeTexture"])); /***/ }), /***/ "./Materials/Textures/rawTexture.ts": /*!******************************************!*\ !*** ./Materials/Textures/rawTexture.ts ***! \******************************************/ /*! exports provided: RawTexture */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RawTexture", function() { return RawTexture; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); /** * Raw texture can help creating a texture directly from an array of data. * This can be super useful if you either get the data from an uncompressed source or * if you wish to create your texture pixel by pixel. */ var RawTexture = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RawTexture, _super); /** * Instantiates a new RawTexture. * Raw texture can help creating a texture directly from an array of data. * This can be super useful if you either get the data from an uncompressed source or * if you wish to create your texture pixel by pixel. * @param data define the array of data to use to create the texture * @param width define the width of the texture * @param height define the height of the texture * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx) * @param scene define the scene the texture belongs to * @param generateMipMaps define whether mip maps should be generated or not * @param invertY define if the data should be flipped on Y when uploaded to the GPU * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) */ function RawTexture(data, width, height, /** * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx) */ format, scene, generateMipMaps, invertY, samplingMode, type) { if (generateMipMaps === void 0) { generateMipMaps = true; } if (invertY === void 0) { invertY = false; } if (samplingMode === void 0) { samplingMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; } if (type === void 0) { type = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURETYPE_UNSIGNED_INT; } var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this; _this.format = format; _this._engine = scene.getEngine(); _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type); _this.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_1__["Texture"].CLAMP_ADDRESSMODE; _this.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_1__["Texture"].CLAMP_ADDRESSMODE; return _this; } /** * Updates the texture underlying data. * @param data Define the new data of the texture */ RawTexture.prototype.update = function (data) { this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type); }; /** * Creates a luminance texture from some data. * @param data Define the texture data * @param width Define the width of the texture * @param height Define the height of the texture * @param scene Define the scene the texture belongs to * @param generateMipMaps Define whether or not to create mip maps for the texture * @param invertY define if the data should be flipped on Y when uploaded to the GPU * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) * @returns the luminance texture */ RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) { if (generateMipMaps === void 0) { generateMipMaps = true; } if (invertY === void 0) { invertY = false; } if (samplingMode === void 0) { samplingMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; } return new RawTexture(data, width, height, _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode); }; /** * Creates a luminance alpha texture from some data. * @param data Define the texture data * @param width Define the width of the texture * @param height Define the height of the texture * @param scene Define the scene the texture belongs to * @param generateMipMaps Define whether or not to create mip maps for the texture * @param invertY define if the data should be flipped on Y when uploaded to the GPU * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) * @returns the luminance alpha texture */ RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) { if (generateMipMaps === void 0) { generateMipMaps = true; } if (invertY === void 0) { invertY = false; } if (samplingMode === void 0) { samplingMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; } return new RawTexture(data, width, height, _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode); }; /** * Creates an alpha texture from some data. * @param data Define the texture data * @param width Define the width of the texture * @param height Define the height of the texture * @param scene Define the scene the texture belongs to * @param generateMipMaps Define whether or not to create mip maps for the texture * @param invertY define if the data should be flipped on Y when uploaded to the GPU * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) * @returns the alpha texture */ RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) { if (generateMipMaps === void 0) { generateMipMaps = true; } if (invertY === void 0) { invertY = false; } if (samplingMode === void 0) { samplingMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; } return new RawTexture(data, width, height, _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode); }; /** * Creates a RGB texture from some data. * @param data Define the texture data * @param width Define the width of the texture * @param height Define the height of the texture * @param scene Define the scene the texture belongs to * @param generateMipMaps Define whether or not to create mip maps for the texture * @param invertY define if the data should be flipped on Y when uploaded to the GPU * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) * @returns the RGB alpha texture */ RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) { if (generateMipMaps === void 0) { generateMipMaps = true; } if (invertY === void 0) { invertY = false; } if (samplingMode === void 0) { samplingMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; } if (type === void 0) { type = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURETYPE_UNSIGNED_INT; } return new RawTexture(data, width, height, _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type); }; /** * Creates a RGBA texture from some data. * @param data Define the texture data * @param width Define the width of the texture * @param height Define the height of the texture * @param scene Define the scene the texture belongs to * @param generateMipMaps Define whether or not to create mip maps for the texture * @param invertY define if the data should be flipped on Y when uploaded to the GPU * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) * @returns the RGBA texture */ RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) { if (generateMipMaps === void 0) { generateMipMaps = true; } if (invertY === void 0) { invertY = false; } if (samplingMode === void 0) { samplingMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; } if (type === void 0) { type = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURETYPE_UNSIGNED_INT; } return new RawTexture(data, width, height, _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type); }; /** * Creates a R texture from some data. * @param data Define the texture data * @param width Define the width of the texture * @param height Define the height of the texture * @param scene Define the scene the texture belongs to * @param generateMipMaps Define whether or not to create mip maps for the texture * @param invertY define if the data should be flipped on Y when uploaded to the GPU * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) * @returns the R texture */ RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) { if (generateMipMaps === void 0) { generateMipMaps = true; } if (invertY === void 0) { invertY = false; } if (samplingMode === void 0) { samplingMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_1__["Texture"].TRILINEAR_SAMPLINGMODE; } if (type === void 0) { type = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURETYPE_FLOAT; } return new RawTexture(data, width, height, _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type); }; return RawTexture; }(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_1__["Texture"])); /***/ }), /***/ "./Materials/Textures/rawTexture3D.ts": /*!********************************************!*\ !*** ./Materials/Textures/rawTexture3D.ts ***! \********************************************/ /*! exports provided: RawTexture3D */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RawTexture3D", function() { return RawTexture3D; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); /** * Class used to store 3D textures containing user data */ var RawTexture3D = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RawTexture3D, _super); /** * Create a new RawTexture3D * @param data defines the data of the texture * @param width defines the width of the texture * @param height defines the height of the texture * @param depth defines the depth of the texture * @param format defines the texture format to use * @param scene defines the hosting scene * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default) * @param invertY defines if texture must be stored with Y axis inverted * @param samplingMode defines the sampling mode to use (Texture.TRILINEAR_SAMPLINGMODE by default) * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...) */ function RawTexture3D(data, width, height, depth, /** Gets or sets the texture format to use */ format, scene, generateMipMaps, invertY, samplingMode, textureType) { if (generateMipMaps === void 0) { generateMipMaps = true; } if (invertY === void 0) { invertY = false; } if (samplingMode === void 0) { samplingMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_1__["Texture"].TRILINEAR_SAMPLINGMODE; } if (textureType === void 0) { textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURETYPE_UNSIGNED_INT; } var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this; _this.format = format; _this._engine = scene.getEngine(); _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType); _this.is3D = true; return _this; } /** * Update the texture with new data * @param data defines the data to store in the texture */ RawTexture3D.prototype.update = function (data) { if (!this._texture) { return; } this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type); }; return RawTexture3D; }(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_1__["Texture"])); /***/ }), /***/ "./Materials/Textures/refractionTexture.ts": /*!*************************************************!*\ !*** ./Materials/Textures/refractionTexture.ts ***! \*************************************************/ /*! exports provided: RefractionTexture */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RefractionTexture", function() { return RefractionTexture; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Materials/Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts"); /** * Creates a refraction texture used by refraction channel of the standard material. * It is like a mirror but to see through a material. * @see https://doc.babylonjs.com/how_to/reflect#refraction */ var RefractionTexture = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RefractionTexture, _super); /** * Creates a refraction texture used by refraction channel of the standard material. * It is like a mirror but to see through a material. * @see https://doc.babylonjs.com/how_to/reflect#refraction * @param name Define the texture name * @param size Define the size of the underlying texture * @param scene Define the scene the refraction belongs to * @param generateMipMaps Define if we need to generate mips level for the refraction */ function RefractionTexture(name, size, scene, generateMipMaps) { var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this; /** * Define the reflection plane we want to use. The refractionPlane is usually set to the constructed refractor. * It is possible to directly set the refractionPlane by directly using a Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the refractionPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the refractor as stated in the doc. * @see https://doc.babylonjs.com/how_to/reflect#refraction */ _this.refractionPlane = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Plane"](0, 1, 0, 1); /** * Define how deep under the surface we should see. */ _this.depth = 2.0; _this.onBeforeRenderObservable.add(function () { scene.clipPlane = _this.refractionPlane; }); _this.onAfterRenderObservable.add(function () { delete scene.clipPlane; }); return _this; } /** * Clone the refraction texture. * @returns the cloned texture */ RefractionTexture.prototype.clone = function () { var scene = this.getScene(); if (!scene) { return this; } var textureSize = this.getSize(); var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps); // Base texture newTexture.hasAlpha = this.hasAlpha; newTexture.level = this.level; // Refraction Texture newTexture.refractionPlane = this.refractionPlane.clone(); if (this.renderList) { newTexture.renderList = this.renderList.slice(0); } newTexture.depth = this.depth; return newTexture; }; /** * Serialize the texture to a JSON representation you could use in Parse later on * @returns the serialized JSON representation */ RefractionTexture.prototype.serialize = function () { if (!this.name) { return null; } var serializationObject = _super.prototype.serialize.call(this); serializationObject.mirrorPlane = this.refractionPlane.asArray(); serializationObject.depth = this.depth; return serializationObject; }; return RefractionTexture; }(_Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_2__["RenderTargetTexture"])); /***/ }), /***/ "./Materials/Textures/renderTargetCreationOptions.ts": /*!***********************************************************!*\ !*** ./Materials/Textures/renderTargetCreationOptions.ts ***! \***********************************************************/ /*! exports provided: RenderTargetCreationOptions */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenderTargetCreationOptions", function() { return RenderTargetCreationOptions; }); /** * Define options used to create a render target texture */ var RenderTargetCreationOptions = /** @class */ (function () { function RenderTargetCreationOptions() { } return RenderTargetCreationOptions; }()); /***/ }), /***/ "./Materials/Textures/renderTargetTexture.ts": /*!***************************************************!*\ !*** ./Materials/Textures/renderTargetTexture.ts ***! \***************************************************/ /*! exports provided: RenderTargetTexture */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RenderTargetTexture", function() { return RenderTargetTexture; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); /* harmony import */ var _PostProcesses_postProcessManager__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../PostProcesses/postProcessManager */ "./PostProcesses/postProcessManager.ts"); /* harmony import */ var _Rendering_renderingManager__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Rendering/renderingManager */ "./Rendering/renderingManager.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); /** * This Helps creating a texture that will be created from a camera in your scene. * It is basically a dynamic texture that could be used to create special effects for instance. * Actually, It is the base of lot of effects in the framework like post process, shadows, effect layers and rendering pipelines... */ var RenderTargetTexture = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](RenderTargetTexture, _super); /** * Instantiate a render target texture. This is mainly used to render of screen the scene to for instance apply post processse * or used a shadow, depth texture... * @param name The friendly name of the texture * @param size The size of the RTT (number if square, or {width: number, height:number} or {ratio:} to define a ratio from the main scene) * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised. * @param generateMipMaps True if mip maps need to be generated after render. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT * @param type The type of the buffer in the RTT (int, half float, float...) * @param isCube True if a cube texture needs to be created * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...) * @param generateDepthBuffer True to generate a depth buffer * @param generateStencilBuffer True to generate a stencil buffer * @param isMulti True if multiple textures need to be created (Draw Buffers) * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...) * @param delayAllocation if the texture allocation should be delayed (default: false) */ function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format, delayAllocation) { if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; } if (type === void 0) { type = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_INT; } if (isCube === void 0) { isCube = false; } if (samplingMode === void 0) { samplingMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].TRILINEAR_SAMPLINGMODE; } if (generateDepthBuffer === void 0) { generateDepthBuffer = true; } if (generateStencilBuffer === void 0) { generateStencilBuffer = false; } if (isMulti === void 0) { isMulti = false; } if (format === void 0) { format = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGBA; } if (delayAllocation === void 0) { delayAllocation = false; } var _this = _super.call(this, null, scene, !generateMipMaps) || this; _this.isCube = isCube; /** * Define if particles should be rendered in your texture. */ _this.renderParticles = true; /** * Define if sprites should be rendered in your texture. */ _this.renderSprites = false; /** * Override the default coordinates mode to projection for RTT as it is the most common case for rendered textures. */ _this.coordinatesMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].PROJECTION_MODE; /** * Define if the camera viewport should be respected while rendering the texture or if the render should be done to the entire texture. */ _this.ignoreCameraViewport = false; /** * An event triggered when the texture is unbind. */ _this.onBeforeBindObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * An event triggered when the texture is unbind. */ _this.onAfterUnbindObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * An event triggered before rendering the texture */ _this.onBeforeRenderObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * An event triggered after rendering the texture */ _this.onAfterRenderObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * An event triggered after the texture clear */ _this.onClearObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); _this._currentRefreshId = -1; _this._refreshRate = 1; _this._samples = 1; /** * Gets or sets the center of the bounding box associated with the texture (when in cube mode) * It must define where the camera used to render the texture is set */ _this.boundingBoxPosition = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); scene = _this.getScene(); if (!scene) { return _this; } _this.renderList = new Array(); _this._engine = scene.getEngine(); _this.name = name; _this.isRenderTarget = true; _this._initialSizeParameter = size; _this._processSizeParameter(size); _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () { }); _this._generateMipMaps = generateMipMaps ? true : false; _this._doNotChangeAspectRatio = doNotChangeAspectRatio; // Rendering groups _this._renderingManager = new _Rendering_renderingManager__WEBPACK_IMPORTED_MODULE_6__["RenderingManager"](scene); _this._renderingManager._useSceneAutoClearSetup = true; if (isMulti) { return _this; } _this._renderTargetOptions = { generateMipMaps: generateMipMaps, type: type, format: format, samplingMode: samplingMode, generateDepthBuffer: generateDepthBuffer, generateStencilBuffer: generateStencilBuffer }; if (samplingMode === _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].NEAREST_SAMPLINGMODE) { _this.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].CLAMP_ADDRESSMODE; _this.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].CLAMP_ADDRESSMODE; } if (!delayAllocation) { if (isCube) { _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions); _this.coordinatesMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].INVCUBIC_MODE; _this._textureMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Identity(); } else { _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions); } } return _this; } Object.defineProperty(RenderTargetTexture.prototype, "renderList", { /** * Use this list to define the list of mesh you want to render. */ get: function () { return this._renderList; }, set: function (value) { this._renderList = value; if (this._renderList) { this._hookArray(this._renderList); } }, enumerable: true, configurable: true }); RenderTargetTexture.prototype._hookArray = function (array) { var _this = this; var oldPush = array.push; array.push = function () { var items = []; for (var _i = 0; _i < arguments.length; _i++) { items[_i] = arguments[_i]; } var wasEmpty = array.length === 0; var result = oldPush.apply(array, items); if (wasEmpty) { _this.getScene().meshes.forEach(function (mesh) { mesh._markSubMeshesAsLightDirty(); }); } return result; }; var oldSplice = array.splice; array.splice = function (index, deleteCount) { var deleted = oldSplice.apply(array, [index, deleteCount]); if (array.length === 0) { _this.getScene().meshes.forEach(function (mesh) { mesh._markSubMeshesAsLightDirty(); }); } return deleted; }; }; Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", { /** * Set a after unbind callback in the texture. * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended. */ set: function (callback) { if (this._onAfterUnbindObserver) { this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver); } this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", { /** * Set a before render callback in the texture. * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended. */ set: function (callback) { if (this._onBeforeRenderObserver) { this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver); } this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", { /** * Set a after render callback in the texture. * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended. */ set: function (callback) { if (this._onAfterRenderObserver) { this.onAfterRenderObservable.remove(this._onAfterRenderObserver); } this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(RenderTargetTexture.prototype, "onClear", { /** * Set a clear callback in the texture. * This has been kept for backward compatibility and use of onClearObservable is recommended. */ set: function (callback) { if (this._onClearObserver) { this.onClearObservable.remove(this._onClearObserver); } this._onClearObserver = this.onClearObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", { /** * Gets render target creation options that were used. */ get: function () { return this._renderTargetOptions; }, enumerable: true, configurable: true }); RenderTargetTexture.prototype._onRatioRescale = function () { if (this._sizeRatio) { this.resize(this._initialSizeParameter); } }; Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", { get: function () { return this._boundingBoxSize; }, /** * 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: function (value) { if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) { return; } this._boundingBoxSize = value; var scene = this.getScene(); if (scene) { scene.markAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].MATERIAL_TextureDirtyFlag); } }, enumerable: true, configurable: true }); /** * 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 * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture * @param generateStencil Specifies whether or not a stencil should be allocated in the texture */ RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) { if (comparisonFunction === void 0) { comparisonFunction = 0; } if (bilinearFiltering === void 0) { bilinearFiltering = true; } if (generateStencil === void 0) { generateStencil = false; } if (!this.getScene()) { return; } var engine = this.getScene().getEngine(); this.depthStencilTexture = engine.createDepthStencilTexture(this._size, { bilinearFiltering: bilinearFiltering, comparisonFunction: comparisonFunction, generateStencil: generateStencil, isCube: this.isCube }); engine.setFrameBufferDepthStencilTexture(this); }; RenderTargetTexture.prototype._processSizeParameter = function (size) { if (size.ratio) { this._sizeRatio = size.ratio; this._size = { width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio), height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio) }; } else { this._size = size; } }; Object.defineProperty(RenderTargetTexture.prototype, "samples", { /** * Define the number of samples to use in case of MSAA. * It defaults to one meaning no MSAA has been enabled. */ get: function () { return this._samples; }, set: function (value) { if (this._samples === value) { return; } var scene = this.getScene(); if (!scene) { return; } this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value); }, enumerable: true, configurable: true }); /** * 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. */ RenderTargetTexture.prototype.resetRefreshCounter = function () { this._currentRefreshId = -1; }; Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", { /** * 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: function () { return this._refreshRate; }, set: function (value) { this._refreshRate = value; this.resetRefreshCounter(); }, enumerable: true, configurable: true }); /** * Adds a post process to the render target rendering passes. * @param postProcess define the post process to add */ RenderTargetTexture.prototype.addPostProcess = function (postProcess) { if (!this._postProcessManager) { var scene = this.getScene(); if (!scene) { return; } this._postProcessManager = new _PostProcesses_postProcessManager__WEBPACK_IMPORTED_MODULE_5__["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 processesshould also be disposed (false by default) */ RenderTargetTexture.prototype.clearPostProcesses = function (dispose) { if (dispose === void 0) { dispose = false; } if (!this._postProcesses) { return; } if (dispose) { for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) { var postProcess = _a[_i]; 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 */ RenderTargetTexture.prototype.removePostProcess = function (postProcess) { if (!this._postProcesses) { return; } var index = this._postProcesses.indexOf(postProcess); if (index === -1) { return; } this._postProcesses.splice(index, 1); if (this._postProcesses.length > 0) { this._postProcesses[0].autoClear = false; } }; /** @hidden */ RenderTargetTexture.prototype._shouldRender = function () { if (this._currentRefreshId === -1) { // At least render once this._currentRefreshId = 1; return true; } if (this.refreshRate === this._currentRefreshId) { this._currentRefreshId = 1; return true; } this._currentRefreshId++; return false; }; /** * Gets the actual render size of the texture. * @returns the width of the render size */ RenderTargetTexture.prototype.getRenderSize = function () { return this.getRenderWidth(); }; /** * Gets the actual render width of the texture. * @returns the width of the render size */ RenderTargetTexture.prototype.getRenderWidth = function () { 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 */ RenderTargetTexture.prototype.getRenderHeight = function () { if (this._size.width) { return this._size.height; } return this._size; }; Object.defineProperty(RenderTargetTexture.prototype, "canRescale", { /** * Get if the texture can be rescaled or not. */ get: function () { return true; }, enumerable: true, configurable: true }); /** * Resize the texture using a ratio. * @param ratio the ratio to apply to the texture size in order to compute the new target size */ RenderTargetTexture.prototype.scale = function (ratio) { var newSize = this.getRenderSize() * ratio; this.resize(newSize); }; /** * Get the texture reflection matrix used to rotate/transform the reflection. * @returns the reflection matrix */ RenderTargetTexture.prototype.getReflectionTextureMatrix = function () { if (this.isCube) { return this._textureMatrix; } return _super.prototype.getReflectionTextureMatrix.call(this); }; /** * Resize the texture to a new desired size. * Be carrefull 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 } */ RenderTargetTexture.prototype.resize = function (size) { var wasCube = this.isCube; this.releaseInternalTexture(); var scene = this.getScene(); if (!scene) { return; } this._processSizeParameter(size); if (wasCube) { this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions); } else { this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions); } }; /** * 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 */ RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) { if (useCameraPostProcess === void 0) { useCameraPostProcess = false; } if (dumpForDebug === void 0) { dumpForDebug = false; } var scene = this.getScene(); if (!scene) { return; } var engine = scene.getEngine(); if (this.useCameraPostProcesses !== undefined) { useCameraPostProcess = this.useCameraPostProcesses; } if (this._waitingRenderList) { this.renderList = []; for (var index = 0; index < this._waitingRenderList.length; index++) { var id = this._waitingRenderList[index]; var mesh_1 = scene.getMeshByID(id); if (mesh_1) { this.renderList.push(mesh_1); } } delete this._waitingRenderList; } // Is predicate defined? if (this.renderListPredicate) { if (this.renderList) { this.renderList.length = 0; // Clear previous renderList } else { this.renderList = []; } var scene = this.getScene(); if (!scene) { return; } var sceneMeshes = scene.meshes; for (var index = 0; index < sceneMeshes.length; index++) { var mesh = sceneMeshes[index]; if (this.renderListPredicate(mesh)) { this.renderList.push(mesh); } } } this.onBeforeBindObservable.notifyObservers(this); // Set custom projection. // Needs to be before binding to prevent changing the aspect ratio. var camera; if (this.activeCamera) { camera = this.activeCamera; engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight()); if (this.activeCamera !== scene.activeCamera) { scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true)); } } else { camera = scene.activeCamera; if (camera) { engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight()); } } // Prepare renderingManager this._renderingManager.reset(); var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data; var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length; var sceneRenderId = scene.getRenderId(); for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) { var mesh = currentRenderList[meshIndex]; if (mesh) { if (!mesh.isReady(this.refreshRate === 0)) { this.resetRefreshCounter(); continue; } mesh._preActivateForIntermediateRendering(sceneRenderId); var isMasked = void 0; if (!this.renderList && camera) { isMasked = ((mesh.layerMask & camera.layerMask) === 0); } else { isMasked = false; } if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) { mesh._activate(sceneRenderId); for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) { var subMesh = mesh.subMeshes[subIndex]; scene._activeIndices.addCount(subMesh.indexCount, false); this._renderingManager.dispatch(subMesh, mesh); } } } } for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) { var particleSystem = scene.particleSystems[particleIndex]; var emitter = particleSystem.emitter; if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) { continue; } if (currentRenderList.indexOf(emitter) >= 0) { this._renderingManager.dispatchParticles(particleSystem); } } if (this.isCube) { for (var face = 0; face < 6; face++) { this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug); scene.incrementRenderId(); scene.resetCachedMaterial(); } } else { this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug); } this.onAfterUnbindObservable.notifyObservers(this); if (scene.activeCamera) { if (this.activeCamera && this.activeCamera !== scene.activeCamera) { scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true)); } engine.setViewport(scene.activeCamera.viewport); } scene.resetCachedMaterial(); }; RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) { var minimum = 128; var x = renderDimension * scale; var curved = _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].NearestPOT(x + (minimum * minimum / (minimum + x))); // Ensure we don't exceed the render dimension (while staying POT) return Math.min(_Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].FloorPOT(renderDimension), curved); }; /** * @hidden * @param faceIndex face index to bind to if this is a cubetexture */ RenderTargetTexture.prototype._bindFrameBuffer = function (faceIndex) { if (faceIndex === void 0) { faceIndex = 0; } var scene = this.getScene(); if (!scene) { return; } var engine = scene.getEngine(); if (this._texture) { engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined); } }; RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) { var _this = this; if (!this._texture) { return; } engine.unBindFramebuffer(this._texture, this.isCube, function () { _this.onAfterRenderObservable.notifyObservers(faceIndex); }); }; RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) { var scene = this.getScene(); if (!scene) { return; } var engine = scene.getEngine(); if (!this._texture) { return; } // Bind if (this._postProcessManager) { this._postProcessManager._prepareFrame(this._texture, this._postProcesses); } else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) { this._bindFrameBuffer(faceIndex); } this.onBeforeRenderObservable.notifyObservers(faceIndex); // Clear if (this.onClearObservable.hasObservers()) { this.onClearObservable.notifyObservers(engine); } else { engine.clear(this.clearColor || scene.clearColor, true, true, true); } if (!this._doNotChangeAspectRatio) { scene.updateTransformMatrix(true); } // Before Camera Draw for (var _i = 0, _a = scene._beforeRenderTargetDrawStage; _i < _a.length; _i++) { var step = _a[_i]; step.action(this); } // Render this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites); // After Camera Draw for (var _b = 0, _c = scene._afterRenderTargetDrawStage; _b < _c.length; _b++) { var step = _c[_b]; step.action(this); } if (this._postProcessManager) { this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport); } else if (useCameraPostProcess) { scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex); } if (!this._doNotChangeAspectRatio) { scene.updateTransformMatrix(true); } // Dump ? if (dumpForDebug) { _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine); } // Unbind if (!this.isCube || faceIndex === 5) { if (this.isCube) { if (faceIndex === 5) { engine.generateMipMapsForCubemap(this._texture); } } this.unbindFrameBuffer(engine, faceIndex); } else { this.onAfterRenderObservable.notifyObservers(faceIndex); } }; /** * Overrides the default sort function applied in the renderging 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. */ RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) { if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; } if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; } if (transparentSortCompareFn === void 0) { 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. */ RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) { this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil); this._renderingManager._useSceneAutoClearSetup = false; }; /** * Clones the texture. * @returns the cloned texture */ RenderTargetTexture.prototype.clone = function () { var textureSize = this.getSize(); var 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); // Base texture newTexture.hasAlpha = this.hasAlpha; newTexture.level = this.level; // RenderTarget Texture newTexture.coordinatesMode = this.coordinatesMode; if (this.renderList) { newTexture.renderList = this.renderList.slice(0); } return newTexture; }; /** * Serialize the texture to a JSON representation we can easily use in the resepective Parse function. * @returns The JSON representation of the texture */ RenderTargetTexture.prototype.serialize = function () { if (!this.name) { return null; } var serializationObject = _super.prototype.serialize.call(this); serializationObject.renderTargetSize = this.getRenderSize(); serializationObject.renderList = []; if (this.renderList) { for (var 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 */ RenderTargetTexture.prototype.disposeFramebufferObjects = function () { var objBuffer = this.getInternalTexture(); var scene = this.getScene(); if (objBuffer && scene) { scene.getEngine()._releaseFramebufferObjects(objBuffer); } }; /** * Dispose the texture and release its associated resources. */ RenderTargetTexture.prototype.dispose = function () { if (this._postProcessManager) { this._postProcessManager.dispose(); this._postProcessManager = null; } this.clearPostProcesses(true); if (this._resizeObserver) { this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver); this._resizeObserver = null; } this.renderList = null; // Remove from custom render targets var scene = this.getScene(); if (!scene) { return; } var index = scene.customRenderTargets.indexOf(this); if (index >= 0) { scene.customRenderTargets.splice(index, 1); } for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) { var camera = _a[_i]; index = camera.customRenderTargets.indexOf(this); if (index >= 0) { camera.customRenderTargets.splice(index, 1); } } _super.prototype.dispose.call(this); }; /** @hidden */ RenderTargetTexture.prototype._rebuild = function () { if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) { this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE; } if (this._postProcessManager) { this._postProcessManager._rebuild(); } }; /** * Clear the info related to rendering groups preventing retention point in material dispose. */ RenderTargetTexture.prototype.freeRenderingGroups = function () { if (this._renderingManager) { this._renderingManager.freeRenderingGroups(); } }; /** * Gets the number of views the corresponding to the texture (eg. a MultiviewRenderTarget will have > 1) * @returns the view count */ RenderTargetTexture.prototype.getViewCount = function () { return 1; }; /** * The texture will only be rendered once which can be useful to improve performance if everything in your render is static for instance. */ RenderTargetTexture.REFRESHRATE_RENDER_ONCE = 0; /** * The texture will only be rendered rendered every frame and is recomended for dynamic contents. */ RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = 1; /** * The texture will be rendered every 2 frames which could be enough if your dynamic objects are not * the central point of your effect and can save a lot of performances. */ RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2; return RenderTargetTexture; }(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"])); _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"]._CreateRenderTargetTexture = function (name, renderTargetSize, scene, generateMipMaps) { return new RenderTargetTexture(name, renderTargetSize, scene, generateMipMaps); }; /***/ }), /***/ "./Materials/Textures/texture.ts": /*!***************************************!*\ !*** ./Materials/Textures/texture.ts ***! \***************************************/ /*! exports provided: Texture */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Texture", function() { return Texture; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Materials/Textures/baseTexture */ "./Materials/Textures/baseTexture.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts"); /* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../Misc/devTools */ "./Misc/devTools.ts"); /** * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input. * @see http://doc.babylonjs.com/babylon101/materials#texture */ var Texture = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](Texture, _super); /** * Instantiates a new texture. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input. * @see http://doc.babylonjs.com/babylon101/materials#texture * @param url define the url of the picture to load as a texture * @param scene define the scene the texture will belong to * @param noMipmap define if the texture will require mip maps or not * @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 fectching 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 buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...) */ function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) { if (noMipmap === void 0) { noMipmap = false; } if (invertY === void 0) { invertY = true; } if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; } if (onLoad === void 0) { onLoad = null; } if (onError === void 0) { onError = null; } if (buffer === void 0) { buffer = null; } if (deleteBuffer === void 0) { deleteBuffer = false; } var _this = _super.call(this, scene) || this; /** * Define an offset on the texture to offset the u coordinates of the UVs * @see http://doc.babylonjs.com/how_to/more_materials#offsetting */ _this.uOffset = 0; /** * Define an offset on the texture to offset the v coordinates of the UVs * @see http://doc.babylonjs.com/how_to/more_materials#offsetting */ _this.vOffset = 0; /** * Define an offset on the texture to scale the u coordinates of the UVs * @see http://doc.babylonjs.com/how_to/more_materials#tiling */ _this.uScale = 1.0; /** * Define an offset on the texture to scale the v coordinates of the UVs * @see http://doc.babylonjs.com/how_to/more_materials#tiling */ _this.vScale = 1.0; /** * Define an offset on the texture to rotate around the u coordinates of the UVs * @see http://doc.babylonjs.com/how_to/more_materials */ _this.uAng = 0; /** * Define an offset on the texture to rotate around the v coordinates of the UVs * @see http://doc.babylonjs.com/how_to/more_materials */ _this.vAng = 0; /** * Define an offset on the texture to rotate around the w coordinates of the UVs (in case of 3d texture) * @see http://doc.babylonjs.com/how_to/more_materials */ _this.wAng = 0; /** * Defines the center of rotation (U) */ _this.uRotationCenter = 0.5; /** * Defines the center of rotation (V) */ _this.vRotationCenter = 0.5; /** * Defines the center of rotation (W) */ _this.wRotationCenter = 0.5; /** @hidden */ _this._initialSamplingMode = Texture.BILINEAR_SAMPLINGMODE; /** * Observable triggered once the texture has been loaded. */ _this.onLoadObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); _this._isBlocking = true; _this.name = url || ""; _this.url = url; _this._noMipmap = noMipmap; _this._invertY = invertY; _this._initialSamplingMode = samplingMode; _this._buffer = buffer; _this._deleteBuffer = deleteBuffer; if (format) { _this._format = format; } scene = _this.getScene(); if (!scene) { return _this; } scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this); var load = function () { if (_this._texture && _this._texture._invertVScale) { _this.vScale = -1; } if (_this.onLoadObservable.hasObservers()) { _this.onLoadObservable.notifyObservers(_this); } if (onLoad) { onLoad(); } if (!_this.isBlocking && scene) { scene.resetCachedMaterial(); } }; if (!_this.url) { _this._delayedOnLoad = load; _this._delayedOnError = onError; return _this; } _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode, invertY); if (!_this._texture) { if (!scene.useDelayedTextureLoading) { _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, samplingMode, load, onError, _this._buffer, undefined, _this._format); if (deleteBuffer) { delete _this._buffer; } } else { _this.delayLoadState = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].DELAYLOADSTATE_NOTLOADED; _this._delayedOnLoad = load; _this._delayedOnError = onError; } } else { if (_this._texture.isReady) { _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].SetImmediate(function () { return load(); }); } else { _this._texture.onLoadedObservable.add(load); } } return _this; } Object.defineProperty(Texture.prototype, "noMipmap", { /** * Are mip maps generated for this texture or not. */ get: function () { return this._noMipmap; }, enumerable: true, configurable: true }); Object.defineProperty(Texture.prototype, "isBlocking", { get: function () { return this._isBlocking; }, /** * 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: function (value) { this._isBlocking = value; }, enumerable: true, configurable: true }); Object.defineProperty(Texture.prototype, "samplingMode", { /** * Get the current sampling mode associated with the texture. */ get: function () { if (!this._texture) { return this._initialSamplingMode; } return this._texture.samplingMode; }, enumerable: true, configurable: true }); Object.defineProperty(Texture.prototype, "invertY", { /** * Gets a boolean indicating if the texture needs to be inverted on the y axis during loading */ get: function () { return this._invertY; }, enumerable: true, configurable: true }); /** * 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) */ Texture.prototype.updateURL = function (url, buffer, onLoad) { if (buffer === void 0) { buffer = null; } if (this.url) { this.releaseInternalTexture(); this.getScene().markAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].MATERIAL_TextureDirtyFlag); } this.url = url; this._buffer = buffer; this.delayLoadState = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].DELAYLOADSTATE_NOTLOADED; if (onLoad) { this._delayedOnLoad = onLoad; } this.delayLoad(); }; /** * Finish the loading sequence of a texture flagged as delayed load. * @hidden */ Texture.prototype.delayLoad = function () { if (this.delayLoadState !== _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].DELAYLOADSTATE_NOTLOADED) { return; } var scene = this.getScene(); if (!scene) { return; } this.delayLoadState = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].DELAYLOADSTATE_LOADED; this._texture = this._getFromCache(this.url, this._noMipmap, this.samplingMode, this._invertY); if (!this._texture) { this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this.samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format); if (this._deleteBuffer) { delete this._buffer; } } else { if (this._delayedOnLoad) { if (this._texture.isReady) { _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].SetImmediate(this._delayedOnLoad); } else { this._texture.onLoadedObservable.add(this._delayedOnLoad); } } } this._delayedOnLoad = null; this._delayedOnError = null; }; Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) { x *= this.uScale; y *= this.vScale; x -= this.uRotationCenter * this.uScale; y -= this.vRotationCenter * this.vScale; z -= this.wRotationCenter; _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t); t.x += this.uRotationCenter * this.uScale + this.uOffset; t.y += this.vRotationCenter * this.vScale + this.vOffset; t.z += this.wRotationCenter; }; /** * Get the current texture matrix which includes the requested offsetting, tiling and rotation components. * @returns the transform matrix of the texture. */ Texture.prototype.getTextureMatrix = function () { var _this = this; if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.uAng === this._cachedUAng && this.vAng === this._cachedVAng && this.wAng === this._cachedWAng) { return this._cachedTextureMatrix; } this._cachedUOffset = this.uOffset; this._cachedVOffset = this.vOffset; this._cachedUScale = this.uScale; this._cachedVScale = this.vScale; this._cachedUAng = this.uAng; this._cachedVAng = this.vAng; this._cachedWAng = this.wAng; if (!this._cachedTextureMatrix) { this._cachedTextureMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].Zero(); this._rowGenerationMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"](); this._t0 = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(); this._t1 = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(); this._t2 = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(); } _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix); this._prepareRowForTextureGeneration(0, 0, 0, this._t0); this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1); this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2); this._t1.subtractInPlace(this._t0); this._t2.subtractInPlace(this._t0); _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].FromValuesToRef(this._t1.x, this._t1.y, this._t1.z, 0.0, this._t2.x, this._t2.y, this._t2.z, 0.0, this._t0.x, this._t0.y, this._t0.z, 0.0, 0.0, 0.0, 0.0, 1.0, this._cachedTextureMatrix); var scene = this.getScene(); if (!scene) { return this._cachedTextureMatrix; } scene.markAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].MATERIAL_TextureDirtyFlag, function (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 */ Texture.prototype.getReflectionTextureMatrix = function () { var _this = this; var scene = this.getScene(); if (!scene) { return this._cachedTextureMatrix; } if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) { if (this.coordinatesMode === Texture.PROJECTION_MODE) { if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) { return this._cachedTextureMatrix; } } else { return this._cachedTextureMatrix; } } if (!this._cachedTextureMatrix) { this._cachedTextureMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].Zero(); } if (!this._projectionModeMatrix) { this._projectionModeMatrix = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].Zero(); } this._cachedUOffset = this.uOffset; this._cachedVOffset = this.vOffset; this._cachedUScale = this.uScale; this._cachedVScale = this.vScale; this._cachedCoordinatesMode = this.coordinatesMode; switch (this.coordinatesMode) { case Texture.PLANAR_MODE: _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].IdentityToRef(this._cachedTextureMatrix); this._cachedTextureMatrix[0] = this.uScale; this._cachedTextureMatrix[5] = this.vScale; this._cachedTextureMatrix[12] = this.uOffset; this._cachedTextureMatrix[13] = this.vOffset; break; case Texture.PROJECTION_MODE: _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].FromValuesToRef(0.5, 0.0, 0.0, 0.0, 0.0, -0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5, 1.0, 1.0, this._projectionModeMatrix); var projectionMatrix = scene.getProjectionMatrix(); this._cachedProjectionMatrixId = projectionMatrix.updateFlag; projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix); break; default: _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Matrix"].IdentityToRef(this._cachedTextureMatrix); break; } scene.markAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].MATERIAL_TextureDirtyFlag, function (mat) { return (mat.getActiveTextures().indexOf(_this) !== -1); }); return this._cachedTextureMatrix; }; /** * Clones the texture. * @returns the cloned texture */ Texture.prototype.clone = function () { var _this = this; return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this.samplingMode, undefined, undefined, _this._texture ? _this._texture._buffer : undefined); }, this); }; /** * Serialize the texture to a JSON representation we can easily use in the resepective Parse function. * @returns The JSON representation of the texture */ Texture.prototype.serialize = function () { var serializationObject = _super.prototype.serialize.call(this); if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") { serializationObject.base64String = this._buffer; serializationObject.name = serializationObject.name.replace("data:", ""); } serializationObject.invertY = this._invertY; serializationObject.samplingMode = this.samplingMode; return serializationObject; }; /** * Get the current class name of the texture useful for serialization or dynamic coding. * @returns "Texture" */ Texture.prototype.getClassName = function () { return "Texture"; }; /** * Dispose the texture and release its associated resources. */ Texture.prototype.dispose = function () { _super.prototype.dispose.call(this); this.onLoadObservable.clear(); this._delayedOnLoad = null; this._delayedOnError = 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 */ Texture.Parse = function (parsedTexture, scene, rootUrl) { if (parsedTexture.customType) { var customTexture = _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].Instantiate(parsedTexture.customType); // Update Sampling Mode var 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); } if (!parsedTexture.name && !parsedTexture.isRenderTarget) { return null; } var texture = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { var generateMipMaps = true; if (parsedTexture.noMipmap) { generateMipMaps = false; } if (parsedTexture.mirrorPlane) { var mirrorTexture = Texture._CreateMirror(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps); mirrorTexture._waitingRenderList = parsedTexture.renderList; mirrorTexture.mirrorPlane = _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Plane"].FromArray(parsedTexture.mirrorPlane); return mirrorTexture; } else if (parsedTexture.isRenderTarget) { var renderTargetTexture = null; if (parsedTexture.isCube) { // Search for an existing reflection probe (which contains a cube render target texture) if (scene.reflectionProbes) { for (var index = 0; index < scene.reflectionProbes.length; index++) { var probe = scene.reflectionProbes[index]; if (probe.name === parsedTexture.name) { return probe.cubeTexture; } } } } else { renderTargetTexture = Texture._CreateRenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps); renderTargetTexture._waitingRenderList = parsedTexture.renderList; } return renderTargetTexture; } else { var texture; if (parsedTexture.base64String) { texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps); } else { var url = rootUrl + parsedTexture.name; if (Texture.UseSerializedUrlIfAny && parsedTexture.url) { url = parsedTexture.url; } texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY); } return texture; } }, parsedTexture, scene); // Update Sampling Mode if (parsedTexture.samplingMode) { var sampling = parsedTexture.samplingMode; if (texture && texture.samplingMode !== sampling) { texture.updateSamplingMode(sampling); } } // Animations if (texture && parsedTexture.animations) { for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) { var parsedAnimation = parsedTexture.animations[animationIndex]; var internalClass = _Misc_typeStore__WEBPACK_IMPORTED_MODULE_7__["_TypeStore"].GetClass("BABYLON.Animation"); if (internalClass) { texture.animations.push(internalClass.Parse(parsedAnimation)); } } } 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 noMipmap Forces the texture to not create mip map information if true * @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 fectching 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...) * @returns the created texture */ Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) { if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; } if (onLoad === void 0) { onLoad = null; } if (onError === void 0) { onError = null; } if (format === void 0) { format = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTUREFORMAT_RGBA; } return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format); }; /** * Creates a texture from its data: representation. (data: will be added in case only the payload has been passed in) * @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 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 noMipmap Forces the texture to not create mip map information if true * @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 fectching 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...) * @returns the created texture */ Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) { if (deleteBuffer === void 0) { deleteBuffer = false; } if (noMipmap === void 0) { noMipmap = false; } if (invertY === void 0) { invertY = true; } if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; } if (onLoad === void 0) { onLoad = null; } if (onError === void 0) { onError = null; } if (format === void 0) { format = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTUREFORMAT_RGBA; } if (name.substr(0, 5) !== "data:") { name = "data:" + name; } return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format); }; /** @hidden */ Texture._CubeTextureParser = function (jsonTexture, scene, rootUrl) { throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_8__["_DevTools"].WarnImport("CubeTexture"); }; /** @hidden */ Texture._CreateMirror = function (name, renderTargetSize, scene, generateMipMaps) { throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_8__["_DevTools"].WarnImport("MirrorTexture"); }; /** @hidden */ Texture._CreateRenderTargetTexture = function (name, renderTargetSize, scene, generateMipMaps) { throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_8__["_DevTools"].WarnImport("RenderTargetTexture"); }; /** nearest is mag = nearest and min = nearest and mip = linear */ Texture.NEAREST_SAMPLINGMODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE; /** nearest is mag = nearest and min = nearest and mip = linear */ Texture.NEAREST_NEAREST_MIPLINEAR = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear /** Bilinear is mag = linear and min = linear and mip = nearest */ Texture.BILINEAR_SAMPLINGMODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_BILINEAR_SAMPLINGMODE; /** Bilinear is mag = linear and min = linear and mip = nearest */ Texture.LINEAR_LINEAR_MIPNEAREST = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest /** Trilinear is mag = linear and min = linear and mip = linear */ Texture.TRILINEAR_SAMPLINGMODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; /** Trilinear is mag = linear and min = linear and mip = linear */ Texture.LINEAR_LINEAR_MIPLINEAR = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear /** mag = nearest and min = nearest and mip = nearest */ Texture.NEAREST_NEAREST_MIPNEAREST = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_NEAREST_NEAREST_MIPNEAREST; /** mag = nearest and min = linear and mip = nearest */ Texture.NEAREST_LINEAR_MIPNEAREST = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_NEAREST_LINEAR_MIPNEAREST; /** mag = nearest and min = linear and mip = linear */ Texture.NEAREST_LINEAR_MIPLINEAR = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_NEAREST_LINEAR_MIPLINEAR; /** mag = nearest and min = linear and mip = none */ Texture.NEAREST_LINEAR = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_NEAREST_LINEAR; /** mag = nearest and min = nearest and mip = none */ Texture.NEAREST_NEAREST = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_NEAREST_NEAREST; /** mag = linear and min = nearest and mip = nearest */ Texture.LINEAR_NEAREST_MIPNEAREST = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_LINEAR_NEAREST_MIPNEAREST; /** mag = linear and min = nearest and mip = linear */ Texture.LINEAR_NEAREST_MIPLINEAR = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_LINEAR_NEAREST_MIPLINEAR; /** mag = linear and min = linear and mip = none */ Texture.LINEAR_LINEAR = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_LINEAR_LINEAR; /** mag = linear and min = nearest and mip = none */ Texture.LINEAR_NEAREST = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_LINEAR_NEAREST; /** Explicit coordinates mode */ Texture.EXPLICIT_MODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_EXPLICIT_MODE; /** Spherical coordinates mode */ Texture.SPHERICAL_MODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_SPHERICAL_MODE; /** Planar coordinates mode */ Texture.PLANAR_MODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_PLANAR_MODE; /** Cubic coordinates mode */ Texture.CUBIC_MODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_CUBIC_MODE; /** Projection coordinates mode */ Texture.PROJECTION_MODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_PROJECTION_MODE; /** Inverse Cubic coordinates mode */ Texture.SKYBOX_MODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_SKYBOX_MODE; /** Inverse Cubic coordinates mode */ Texture.INVCUBIC_MODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_INVCUBIC_MODE; /** Equirectangular coordinates mode */ Texture.EQUIRECTANGULAR_MODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_EQUIRECTANGULAR_MODE; /** Equirectangular Fixed coordinates mode */ Texture.FIXED_EQUIRECTANGULAR_MODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_FIXED_EQUIRECTANGULAR_MODE; /** Equirectangular Fixed Mirrored coordinates mode */ Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE; /** Texture is not repeating outside of 0..1 UVs */ Texture.CLAMP_ADDRESSMODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_CLAMP_ADDRESSMODE; /** Texture is repeating outside of 0..1 UVs */ Texture.WRAP_ADDRESSMODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_WRAP_ADDRESSMODE; /** Texture is repeating and mirrored */ Texture.MIRROR_ADDRESSMODE = _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_MIRROR_ADDRESSMODE; /** * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file */ Texture.UseSerializedUrlIfAny = false; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Texture.prototype, "url", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Texture.prototype, "uOffset", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Texture.prototype, "vOffset", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Texture.prototype, "uScale", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Texture.prototype, "vScale", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Texture.prototype, "uAng", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Texture.prototype, "vAng", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Texture.prototype, "wAng", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Texture.prototype, "uRotationCenter", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Texture.prototype, "vRotationCenter", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Texture.prototype, "wRotationCenter", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Texture.prototype, "isBlocking", null); return Texture; }(_Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_5__["BaseTexture"])); // References the dependencies. _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"]._TextureParser = Texture.Parse; /***/ }), /***/ "./Materials/Textures/videoTexture.ts": /*!********************************************!*\ !*** ./Materials/Textures/videoTexture.ts ***! \********************************************/ /*! exports provided: VideoTexture */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VideoTexture", function() { return VideoTexture; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); /** * If you want to display a video in your scene, this is the special texture for that. * This special texture works similar to other textures, with the exception of a few parameters. * @see https://doc.babylonjs.com/how_to/video_texture */ var VideoTexture = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](VideoTexture, _super); /** * Creates a video texture. * If you want to display a video in your scene, this is the special texture for that. * This special texture works similar to other textures, with the exception of a few parameters. * @see https://doc.babylonjs.com/how_to/video_texture * @param name optional name, will detect from video source, if not defined * @param src can be used to provide an url, array of urls or an already setup HTML video element. * @param scene is obviously the current scene. * @param generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated). * @param invertY is false by default but can be used to invert video on Y axis * @param samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default * @param settings allows finer control over video usage */ function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) { if (generateMipMaps === void 0) { generateMipMaps = false; } if (invertY === void 0) { invertY = false; } if (samplingMode === void 0) { samplingMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].TRILINEAR_SAMPLINGMODE; } if (settings === void 0) { settings = { autoPlay: true, loop: true, autoUpdateTexture: true, }; } var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this; _this._onUserActionRequestedObservable = null; _this._stillImageCaptured = false; _this._displayingPosterTexture = false; _this._createInternalTexture = function () { if (_this._texture != null) { if (_this._displayingPosterTexture) { _this._texture.dispose(); _this._displayingPosterTexture = false; } else { return; } } if (!_this._engine.needPOTTextures || (_Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].IsExponentOfTwo(_this.video.videoWidth) && _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].IsExponentOfTwo(_this.video.videoHeight))) { _this.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].WRAP_ADDRESSMODE; _this.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].WRAP_ADDRESSMODE; } else { _this.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].CLAMP_ADDRESSMODE; _this.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].CLAMP_ADDRESSMODE; _this._generateMipMaps = false; } _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this.samplingMode); if (!_this.video.autoplay && !_this._settings.poster) { var oldHandler_1 = _this.video.onplaying; var error_1 = false; var oldMuted_1 = _this.video.muted; _this.video.muted = true; _this.video.onplaying = function () { _this.video.muted = oldMuted_1; _this.video.onplaying = oldHandler_1; _this._texture.isReady = true; _this._updateInternalTexture(); if (!error_1) { _this.video.pause(); } if (_this.onLoadObservable.hasObservers()) { _this.onLoadObservable.notifyObservers(_this); } }; var playing = _this.video.play(); if (playing) { playing.then(function () { // Everything is good. }) .catch(function () { error_1 = true; // On Chrome for instance, new policies might prevent playing without user interaction. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) { _this._onUserActionRequestedObservable.notifyObservers(_this); } }); } else { _this.video.onplaying = oldHandler_1; _this._texture.isReady = true; _this._updateInternalTexture(); if (_this.onLoadObservable.hasObservers()) { _this.onLoadObservable.notifyObservers(_this); } } } else { _this._texture.isReady = true; _this._updateInternalTexture(); if (_this.onLoadObservable.hasObservers()) { _this.onLoadObservable.notifyObservers(_this); } } }; _this.reset = function () { if (_this._texture == null) { return; } if (!_this._displayingPosterTexture) { _this._texture.dispose(); _this._texture = null; } }; _this._updateInternalTexture = function () { if (_this._texture == null || !_this._texture.isReady) { return; } if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) { return; } if (_this._displayingPosterTexture) { return; } _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY); }; _this._engine = _this.getScene().getEngine(); _this._generateMipMaps = generateMipMaps; _this._initialSamplingMode = samplingMode; _this.autoUpdateTexture = settings.autoUpdateTexture; _this.name = name || _this._getName(src); _this.video = _this._getVideo(src); _this._settings = settings; if (settings.poster) { _this.video.poster = settings.poster; } if (settings.autoPlay !== undefined) { _this.video.autoplay = settings.autoPlay; } if (settings.loop !== undefined) { _this.video.loop = settings.loop; } _this.video.setAttribute("playsinline", ""); _this.video.addEventListener("paused", _this._updateInternalTexture); _this.video.addEventListener("seeked", _this._updateInternalTexture); _this.video.addEventListener("emptied", _this.reset); _this._createInternalTextureOnEvent = (settings.poster && !settings.autoPlay) ? "play" : "canplay"; _this.video.addEventListener(_this._createInternalTextureOnEvent, _this._createInternalTexture); var videoHasEnoughData = (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA); if (settings.poster && (!settings.autoPlay || !videoHasEnoughData)) { _this._texture = _this._engine.createTexture(settings.poster, false, true, scene); _this._displayingPosterTexture = true; } else if (videoHasEnoughData) { _this._createInternalTexture(); } return _this; } Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", { /** * Event triggerd when a dom action is required by the user to play the video. * This happens due to recent changes in browser policies preventing video to auto start. */ get: function () { if (!this._onUserActionRequestedObservable) { this._onUserActionRequestedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); } return this._onUserActionRequestedObservable; }, enumerable: true, configurable: true }); VideoTexture.prototype._getName = function (src) { if (src instanceof HTMLVideoElement) { return src.currentSrc; } if (typeof src === "object") { return src.toString(); } return src; }; VideoTexture.prototype._getVideo = function (src) { if (src instanceof HTMLVideoElement) { _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].SetCorsBehavior(src.currentSrc, src); return src; } var video = document.createElement("video"); if (typeof src === "string") { _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].SetCorsBehavior(src, video); video.src = src; } else { _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].SetCorsBehavior(src[0], video); src.forEach(function (url) { var source = document.createElement("source"); source.src = url; video.appendChild(source); }); } return video; }; /** * @hidden Internal method to initiate `update`. */ VideoTexture.prototype._rebuild = function () { this.update(); }; /** * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false. */ VideoTexture.prototype.update = function () { if (!this.autoUpdateTexture) { // Expecting user to call `updateTexture` manually return; } this.updateTexture(true); }; /** * Update Texture in `manual` mode. Does not do anything if not visible or paused. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise. */ VideoTexture.prototype.updateTexture = function (isVisible) { if (!isVisible) { return; } if (this.video.paused && this._stillImageCaptured) { return; } this._stillImageCaptured = true; this._updateInternalTexture(); }; /** * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported. * @param url New url. */ VideoTexture.prototype.updateURL = function (url) { this.video.src = url; }; /** * Dispose the texture and release its associated resources. */ VideoTexture.prototype.dispose = function () { _super.prototype.dispose.call(this); if (this._onUserActionRequestedObservable) { this._onUserActionRequestedObservable.clear(); this._onUserActionRequestedObservable = null; } this.video.removeEventListener(this._createInternalTextureOnEvent, this._createInternalTexture); this.video.removeEventListener("paused", this._updateInternalTexture); this.video.removeEventListener("seeked", this._updateInternalTexture); this.video.removeEventListener("emptied", this.reset); this.video.pause(); }; /** * Creates a video texture straight from a stream. * @param scene Define the scene the texture should be created in * @param stream Define the stream the texture should be created from * @returns The created video texture as a promise */ VideoTexture.CreateFromStreamAsync = function (scene, stream) { var video = document.createElement("video"); video.setAttribute('autoplay', ''); video.setAttribute('muted', 'true'); video.setAttribute('playsinline', ''); video.muted = true; if (video.mozSrcObject !== undefined) { // hack for Firefox < 19 video.mozSrcObject = stream; } else { if (typeof video.srcObject == "object") { video.srcObject = stream; } else { window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL; video.src = (window.URL && window.URL.createObjectURL(stream)); } } return new Promise(function (resolve) { var onPlaying = function () { resolve(new VideoTexture("video", video, scene, true, true)); video.removeEventListener("playing", onPlaying); }; video.addEventListener("playing", onPlaying); video.play(); }); }; /** * Creates a video texture straight from your WebCam video feed. * @param scene Define the scene the texture should be created in * @param constraints Define the constraints to use to create the web cam feed from WebRTC * @param audioConstaints Define the audio constraints to use to create the web cam feed from WebRTC * @returns The created video texture as a promise */ VideoTexture.CreateFromWebCamAsync = function (scene, constraints, audioConstaints) { var _this = this; if (audioConstaints === void 0) { audioConstaints = false; } var constraintsDeviceId; if (constraints && constraints.deviceId) { constraintsDeviceId = { exact: constraints.deviceId, }; } if (navigator.mediaDevices) { return navigator.mediaDevices.getUserMedia({ video: constraints, audio: audioConstaints }) .then(function (stream) { return _this.CreateFromStreamAsync(scene, stream); }); } else { navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; if (navigator.getUserMedia) { navigator.getUserMedia({ video: { deviceId: constraintsDeviceId, width: { min: (constraints && constraints.minWidth) || 256, max: (constraints && constraints.maxWidth) || 640, }, height: { min: (constraints && constraints.minHeight) || 256, max: (constraints && constraints.maxHeight) || 480, }, }, audio: audioConstaints }, function (stream) { return _this.CreateFromStreamAsync(scene, stream); }, function (e) { _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error(e.name); }); } } return Promise.reject("No support for userMedia on this device"); }; /** * Creates a video texture straight from your WebCam video feed. * @param scene Define the scene the texture should be created in * @param onReady Define a callback to triggered once the texture will be ready * @param constraints Define the constraints to use to create the web cam feed from WebRTC * @param audioConstaints Define the audio constraints to use to create the web cam feed from WebRTC */ VideoTexture.CreateFromWebCam = function (scene, onReady, constraints, audioConstaints) { if (audioConstaints === void 0) { audioConstaints = false; } this.CreateFromWebCamAsync(scene, constraints, audioConstaints) .then(function (videoTexture) { if (onReady) { onReady(videoTexture); } }) .catch(function (err) { _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error(err.name); }); }; return VideoTexture; }(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"])); /***/ }), /***/ "./Materials/colorCurves.ts": /*!**********************************!*\ !*** ./Materials/colorCurves.ts ***! \**********************************/ /*! exports provided: ColorCurves */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorCurves", function() { return ColorCurves; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /** * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; * corresponding to low luminance, medium luminance, and high luminance areas respectively. */ var ColorCurves = /** @class */ (function () { function ColorCurves() { this._dirty = true; this._tempColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color4"](0, 0, 0, 0); this._globalCurve = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color4"](0, 0, 0, 0); this._highlightsCurve = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color4"](0, 0, 0, 0); this._midtonesCurve = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color4"](0, 0, 0, 0); this._shadowsCurve = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color4"](0, 0, 0, 0); this._positiveCurve = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color4"](0, 0, 0, 0); this._negativeCurve = new _Maths_math__WEBPACK_IMPORTED_MODULE_2__["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; } Object.defineProperty(ColorCurves.prototype, "globalHue", { /** * 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: function () { 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: function (value) { this._globalHue = value; this._dirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(ColorCurves.prototype, "globalDensity", { /** * 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: function () { 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: function (value) { this._globalDensity = value; this._dirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(ColorCurves.prototype, "globalSaturation", { /** * 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: function () { 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: function (value) { this._globalSaturation = value; this._dirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(ColorCurves.prototype, "globalExposure", { /** * 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: function () { 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: function (value) { this._globalExposure = value; this._dirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(ColorCurves.prototype, "highlightsHue", { /** * 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: function () { 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: function (value) { this._highlightsHue = value; this._dirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(ColorCurves.prototype, "highlightsDensity", { /** * 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: function () { 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: function (value) { this._highlightsDensity = value; this._dirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", { /** * 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: function () { 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: function (value) { this._highlightsSaturation = value; this._dirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(ColorCurves.prototype, "highlightsExposure", { /** * 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: function () { 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: function (value) { this._highlightsExposure = value; this._dirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(ColorCurves.prototype, "midtonesHue", { /** * 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: function () { 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: function (value) { this._midtonesHue = value; this._dirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(ColorCurves.prototype, "midtonesDensity", { /** * 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: function () { 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: function (value) { this._midtonesDensity = value; this._dirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", { /** * 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: function () { 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: function (value) { this._midtonesSaturation = value; this._dirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(ColorCurves.prototype, "midtonesExposure", { /** * 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: function () { 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: function (value) { this._midtonesExposure = value; this._dirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(ColorCurves.prototype, "shadowsHue", { /** * 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: function () { 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: function (value) { this._shadowsHue = value; this._dirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(ColorCurves.prototype, "shadowsDensity", { /** * 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: function () { 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: function (value) { this._shadowsDensity = value; this._dirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", { /** * 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: function () { 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: function (value) { this._shadowsSaturation = value; this._dirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(ColorCurves.prototype, "shadowsExposure", { /** * 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: function () { 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: function (value) { this._shadowsExposure = value; this._dirty = true; }, enumerable: true, configurable: true }); /** * Returns the class name * @returns The class name */ ColorCurves.prototype.getClassName = function () { 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 */ ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) { if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; } if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; } if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; } if (colorCurves._dirty) { colorCurves._dirty = false; // Fill in global info. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve); // Compute highlights info. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor); colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve); // Compute midtones info. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor); colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve); // Compute shadows info. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor); colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve); // Compute deltas (neutral is midtones). colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve); colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve); } if (effect) { effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a); effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a); effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a); } }; /** * Prepare the list of uniforms associated with the ColorCurves effects. * @param uniformsList The list of uniforms used in the effect */ ColorCurves.PrepareUniforms = function (uniformsList) { uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative"); }; /** * Returns color grading data based on a hue, density, saturation and exposure value. * @param filterHue The hue of the color filter. * @param filterDensity The density of the color filter. * @param saturation The saturation. * @param exposure The exposure. * @param result The result data container. */ ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) { if (hue == null) { return; } hue = ColorCurves.clamp(hue, 0, 360); density = ColorCurves.clamp(density, -100, 100); saturation = ColorCurves.clamp(saturation, -100, 100); exposure = ColorCurves.clamp(exposure, -100, 100); // Remap the slider/config filter density with non-linear mapping and also scale by half // so that the maximum filter density is only 50% control. This provides fine control // for small values and reasonable range. density = ColorCurves.applyColorGradingSliderNonlinear(density); density *= 0.5; exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure); if (density < 0) { density *= -1; hue = (hue + 180) % 360; } ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result); result.scaleToRef(2, result); result.a = 1 + 0.01 * saturation; }; /** * Takes an input slider value and returns an adjusted value that provides extra control near the centre. * @param value The input slider value in range [-100,100]. * @returns Adjusted value. */ ColorCurves.applyColorGradingSliderNonlinear = function (value) { value /= 100; var 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. * @result An RGBA color represented as Vector4. */ ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) { var h = ColorCurves.clamp(hue, 0, 360); var s = ColorCurves.clamp(saturation / 100, 0, 1); var v = ColorCurves.clamp(brightness / 100, 0, 1); if (s === 0) { result.r = v; result.g = v; result.b = v; } else { // sector 0 to 5 h /= 60; var i = Math.floor(h); // fractional part of h var f = h - i; var p = v * (1 - s); var q = v * (1 - s * f); var t = v * (1 - s * (1 - f)); switch (i) { case 0: result.r = v; result.g = t; result.b = p; break; case 1: result.r = q; result.g = v; result.b = p; break; case 2: result.r = p; result.g = v; result.b = t; break; case 3: result.r = p; result.g = q; result.b = v; break; case 4: result.r = t; result.g = p; result.b = v; break; default: // case 5: result.r = v; result.g = p; result.b = q; break; } } result.a = 1; }; /** * Returns a value clamped between min and max * @param value The value to clamp * @param min The minimum of value * @param max The maximum of value * @returns The clamped value. */ ColorCurves.clamp = function (value, min, max) { return Math.min(Math.max(value, min), max); }; /** * Clones the current color curve instance. * @return The cloned curves */ ColorCurves.prototype.clone = function () { return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return new ColorCurves(); }, this); }; /** * Serializes the current color curve instance to a json representation. * @return a JSON representation */ ColorCurves.prototype.serialize = function () { return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); }; /** * Parses the color curve from a json representation. * @param source the JSON source to parse * @return The parsed curves */ ColorCurves.Parse = function (source) { return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new ColorCurves(); }, source, null, null); }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ColorCurves.prototype, "_globalHue", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ColorCurves.prototype, "_globalDensity", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ColorCurves.prototype, "_globalSaturation", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ColorCurves.prototype, "_globalExposure", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ColorCurves.prototype, "_highlightsHue", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ColorCurves.prototype, "_highlightsDensity", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ColorCurves.prototype, "_highlightsSaturation", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ColorCurves.prototype, "_highlightsExposure", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ColorCurves.prototype, "_midtonesHue", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ColorCurves.prototype, "_midtonesDensity", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ColorCurves.prototype, "_midtonesSaturation", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ColorCurves.prototype, "_midtonesExposure", void 0); return ColorCurves; }()); // References the dependencies. _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"]._ColorCurvesParser = ColorCurves.Parse; /***/ }), /***/ "./Materials/effect.ts": /*!*****************************!*\ !*** ./Materials/effect.ts ***! \*****************************/ /*! exports provided: EffectFallbacks, EffectCreationOptions, Effect */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EffectFallbacks", function() { return EffectFallbacks; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EffectCreationOptions", function() { return EffectCreationOptions; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Effect", function() { return Effect; }); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); /* harmony import */ var _Misc_domManagement__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/domManagement */ "./Misc/domManagement.ts"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /** * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog) */ var EffectFallbacks = /** @class */ (function () { function EffectFallbacks() { this._defines = {}; this._currentRank = 32; this._maxRank = -1; } /** * Removes the fallback from the bound mesh. */ EffectFallbacks.prototype.unBindMesh = function () { 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 */ EffectFallbacks.prototype.addFallback = function (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. */ EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) { this._mesh = mesh; if (rank < this._currentRank) { this._currentRank = rank; } if (rank > this._maxRank) { this._maxRank = rank; } }; Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", { /** * Checks to see if more fallbacks are still availible. */ get: function () { return this._currentRank <= this._maxRank; }, enumerable: true, configurable: true }); /** * Removes the defines that shoould 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. */ EffectFallbacks.prototype.reduce = function (currentDefines, effect) { // First we try to switch to CPU skinning if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) { this._mesh.computeBonesUsingShaders = false; currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0"); effect._bonesComputationForcedToCPU = true; var scene = this._mesh.getScene(); for (var index = 0; index < scene.meshes.length; index++) { var otherMesh = scene.meshes[index]; if (!otherMesh.material) { continue; } if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) { continue; } if (otherMesh.material.getEffect() === effect) { otherMesh.computeBonesUsingShaders = false; } else if (otherMesh.subMeshes) { for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) { var subMesh = _a[_i]; var subMeshEffect = subMesh.effect; if (subMeshEffect === effect) { otherMesh.computeBonesUsingShaders = false; break; } } } } } else { var currentFallbacks = this._defines[this._currentRank]; if (currentFallbacks) { for (var index = 0; index < currentFallbacks.length; index++) { currentDefines = currentDefines.replace("#define " + currentFallbacks[index], ""); } } this._currentRank++; } return currentDefines; }; return EffectFallbacks; }()); /** * Options to be used when creating an effect. */ var EffectCreationOptions = /** @class */ (function () { function EffectCreationOptions() { } return EffectCreationOptions; }()); /** * Effect containing vertex and fragment shader that can be executed on an object. */ var Effect = /** @class */ (function () { /** * 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}) */ function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) { if (samplers === void 0) { samplers = null; } if (defines === void 0) { defines = null; } if (fallbacks === void 0) { fallbacks = null; } if (onCompiled === void 0) { onCompiled = null; } if (onError === void 0) { onError = null; } var _this = this; /** * Unique ID of the effect. */ this.uniqueId = 0; /** * Observable that will be called when the shader is compiled. * It is recommended to use executeWhenCompile() or to make sure that scene.isReady() is called to get this observable raised. */ this.onCompileObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); /** * Observable that will be called if an error occurs during shader compilation. */ this.onErrorObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); /** @hidden */ this._bonesComputationForcedToCPU = false; this._uniformBuffersNames = {}; this._isReady = false; this._compilationError = ""; this.name = baseName; if (attributesNamesOrOptions.attributes) { var options = attributesNamesOrOptions; this._engine = uniformsNamesOrEngine; this._attributesNames = options.attributes; this._uniformsNames = options.uniformsNames.concat(options.samplers); this._samplers = 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; if (options.uniformBuffersNames) { for (var i = 0; i < options.uniformBuffersNames.length; i++) { this._uniformBuffersNames[options.uniformBuffersNames[i]] = i; } } } else { this._engine = engine; this.defines = (defines == null ? "" : defines); this._uniformsNames = uniformsNamesOrEngine.concat(samplers); this._samplers = samplers ? samplers.slice() : []; this._attributesNames = attributesNamesOrOptions; this.onError = onError; this.onCompiled = onCompiled; this._indexParameters = indexParameters; this._fallbacks = fallbacks; } this.uniqueId = Effect._uniqueIdSeed++; var vertexSource; var fragmentSource; if (baseName.vertexElement) { vertexSource = document.getElementById(baseName.vertexElement); if (!vertexSource) { vertexSource = baseName.vertexElement; } } else { vertexSource = baseName.vertex || baseName; } if (baseName.fragmentElement) { fragmentSource = document.getElementById(baseName.fragmentElement); if (!fragmentSource) { fragmentSource = baseName.fragmentElement; } } else { fragmentSource = baseName.fragment || baseName; } this._loadVertexShader(vertexSource, function (vertexCode) { _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) { _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) { _this._loadFragmentShader(fragmentSource, function (fragmentCode) { _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) { _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) { if (baseName) { var vertex = baseName.vertexElement || baseName.vertex || baseName; var fragment = baseName.fragmentElement || baseName.fragment || baseName; _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode; _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode; } else { _this._vertexSourceCode = migratedVertexCode; _this._fragmentSourceCode = migratedFragmentCode; } _this._prepareEffect(); }); }); }); }); }); }); } Object.defineProperty(Effect.prototype, "onBindObservable", { /** * Observable that will be called when effect is bound. */ get: function () { if (!this._onBindObservable) { this._onBindObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); } return this._onBindObservable; }, enumerable: true, configurable: true }); Object.defineProperty(Effect.prototype, "key", { /** * Unique key for this effect */ get: function () { return this._key; }, enumerable: true, configurable: true }); /** * If the effect has been compiled and prepared. * @returns if the effect is compiled and prepared. */ Effect.prototype.isReady = function () { if (!this._isReady && this._program && this._program.isParallelCompiled) { return this._engine._isProgramCompiled(this._program); } return this._isReady; }; /** * The engine the effect was initialized with. * @returns the engine. */ Effect.prototype.getEngine = function () { return this._engine; }; /** * The compiled webGL program for the effect * @returns the webGL program. */ Effect.prototype.getProgram = function () { return this._program; }; /** * The set of names of attribute variables for the shader. * @returns An array of attribute names. */ Effect.prototype.getAttributesNames = function () { return this._attributesNames; }; /** * Returns the attribute at the given index. * @param index The index of the attribute. * @returns The location of the attribute. */ Effect.prototype.getAttributeLocation = function (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. */ Effect.prototype.getAttributeLocationByName = function (name) { var index = this._attributesNames.indexOf(name); return this._attributes[index]; }; /** * The number of attributes. * @returns the numnber of attributes. */ Effect.prototype.getAttributesCount = function () { return this._attributes.length; }; /** * Gets the index of a uniform variable. * @param uniformName of the uniform to look up. * @returns the index. */ Effect.prototype.getUniformIndex = function (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. */ Effect.prototype.getUniform = function (uniformName) { return this._uniforms[this._uniformsNames.indexOf(uniformName)]; }; /** * Returns an array of sampler variable names * @returns The array of sampler variable neames. */ Effect.prototype.getSamplers = function () { return this._samplers; }; /** * The error from the last compilation. * @returns the error string. */ Effect.prototype.getCompilationError = function () { return this._compilationError; }; /** * Adds a callback to the onCompiled observable and call the callback imediatly if already ready. * @param func The callback to be used. */ Effect.prototype.executeWhenCompiled = function (func) { var _this = this; if (this.isReady()) { func(this); return; } this.onCompileObservable.add(function (effect) { func(effect); }); if (!this._program || this._program.isParallelCompiled) { setTimeout(function () { _this._checkIsReady(); }, 16); } }; Effect.prototype._checkIsReady = function () { var _this = this; if (this.isReady()) { return; } setTimeout(function () { _this._checkIsReady(); }, 16); }; /** @hidden */ Effect.prototype._loadVertexShader = function (vertex, callback) { if (_Misc_domManagement__WEBPACK_IMPORTED_MODULE_2__["DomManagement"].IsWindowObjectExist()) { // DOM element ? if (vertex instanceof HTMLElement) { var vertexCode = _Misc_domManagement__WEBPACK_IMPORTED_MODULE_2__["DomManagement"].GetDOMTextContent(vertex); callback(vertexCode); return; } } // Base64 encoded ? if (vertex.substr(0, 7) === "base64:") { var vertexBinary = window.atob(vertex.substr(7)); callback(vertexBinary); return; } // Is in local store ? if (Effect.ShadersStore[vertex + "VertexShader"]) { callback(Effect.ShadersStore[vertex + "VertexShader"]); return; } var vertexShaderUrl; if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) { vertexShaderUrl = vertex; } else { vertexShaderUrl = Effect.ShadersRepository + vertex; } // Vertex shader this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback); }; /** @hidden */ Effect.prototype._loadFragmentShader = function (fragment, callback) { if (_Misc_domManagement__WEBPACK_IMPORTED_MODULE_2__["DomManagement"].IsWindowObjectExist()) { // DOM element ? if (fragment instanceof HTMLElement) { var fragmentCode = _Misc_domManagement__WEBPACK_IMPORTED_MODULE_2__["DomManagement"].GetDOMTextContent(fragment); callback(fragmentCode); return; } } // Base64 encoded ? if (fragment.substr(0, 7) === "base64:") { var fragmentBinary = window.atob(fragment.substr(7)); callback(fragmentBinary); return; } // Is in local store ? if (Effect.ShadersStore[fragment + "PixelShader"]) { callback(Effect.ShadersStore[fragment + "PixelShader"]); return; } if (Effect.ShadersStore[fragment + "FragmentShader"]) { callback(Effect.ShadersStore[fragment + "FragmentShader"]); return; } var fragmentShaderUrl; if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) { fragmentShaderUrl = fragment; } else { fragmentShaderUrl = Effect.ShadersRepository + fragment; } // Fragment shader this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback); }; /** @hidden */ Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) { // Rebuild shaders source code var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : ""; var prefix = shaderVersion + (defines ? defines + "\n" : ""); vertexCode = prefix + vertexCode; fragmentCode = prefix + fragmentCode; // Number lines of shaders source code var i = 2; var regex = /\n/gm; var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; }); i = 2; var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; }); // Dump shaders name and formatted source code if (this.name.vertexElement) { _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode); _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode); } else if (this.name.vertex) { _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error("Vertex shader: " + this.name.vertex + formattedVertexCode); _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error("Fragment shader: " + this.name.fragment + formattedFragmentCode); } else { _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error("Vertex shader: " + this.name + formattedVertexCode); _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error("Fragment shader: " + this.name + formattedFragmentCode); } }; Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) { var preparedSourceCode = this._processPrecision(sourceCode); if (this._engine.webGLVersion == 1) { callback(preparedSourceCode); return; } // Already converted if (preparedSourceCode.indexOf("#version 3") !== -1) { callback(preparedSourceCode.replace("#version 300 es", "")); return; } var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1; // Remove extensions // #extension GL_OES_standard_derivatives : enable // #extension GL_EXT_shader_texture_lod : enable // #extension GL_EXT_frag_depth : enable // #extension GL_EXT_draw_buffers : require var regex = /#extension.+(GL_OVR_multiview|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g; var result = preparedSourceCode.replace(regex, ""); // Migrate to GLSL v300 result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out "); result = result.replace(/attribute[ \t]/g, "in "); result = result.replace(/[ \t]attribute/g, " in"); result = result.replace(/texture2D\s*\(/g, "texture("); if (isFragment) { result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod("); result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod("); result = result.replace(/textureCube\s*\(/g, "texture("); result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth"); result = result.replace(/gl_FragColor/g, "glFragColor"); result = result.replace(/gl_FragData/g, "glFragData"); result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main("); } // Add multiview setup to top of file when defined var hasMultiviewExtension = this.defines.indexOf("#define MULTIVIEW\n") !== -1; if (hasMultiviewExtension && !isFragment) { result = "#extension GL_OVR_multiview : require\nlayout (num_views = 2) in;\n" + result; } callback(result); }; Effect.prototype._processIncludes = function (sourceCode, callback) { var _this = this; var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g; var match = regex.exec(sourceCode); var returnValue = new String(sourceCode); while (match != null) { var includeFile = match[1]; // Uniform declaration if (includeFile.indexOf("__decl__") !== -1) { includeFile = includeFile.replace(/__decl__/, ""); if (this._engine.supportsUniformBuffers) { includeFile = includeFile.replace(/Vertex/, "Ubo"); includeFile = includeFile.replace(/Fragment/, "Ubo"); } includeFile = includeFile + "Declaration"; } if (Effect.IncludesShadersStore[includeFile]) { // Substitution var includeContent = Effect.IncludesShadersStore[includeFile]; if (match[2]) { var splits = match[3].split(","); for (var index = 0; index < splits.length; index += 2) { var source = new RegExp(splits[index], "g"); var dest = splits[index + 1]; includeContent = includeContent.replace(source, dest); } } if (match[4]) { var indexString = match[5]; if (indexString.indexOf("..") !== -1) { var indexSplits = indexString.split(".."); var minIndex = parseInt(indexSplits[0]); var maxIndex = parseInt(indexSplits[1]); var sourceIncludeContent = includeContent.slice(0); includeContent = ""; if (isNaN(maxIndex)) { maxIndex = this._indexParameters[indexSplits[1]]; } for (var i = minIndex; i < maxIndex; i++) { if (!this._engine.supportsUniformBuffers) { // Ubo replacement sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) { return p1 + "{X}"; }); } includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n"; } } else { if (!this._engine.supportsUniformBuffers) { // Ubo replacement includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) { return p1 + "{X}"; }); } includeContent = includeContent.replace(/\{X\}/g, indexString); } } // Replace returnValue = returnValue.replace(match[0], includeContent); } else { var includeShaderUrl = Effect.ShadersRepository + "ShadersInclude/" + includeFile + ".fx"; this._engine._loadFile(includeShaderUrl, function (fileContent) { Effect.IncludesShadersStore[includeFile] = fileContent; _this._processIncludes(returnValue, callback); }); return; } match = regex.exec(sourceCode); } callback(returnValue); }; Effect.prototype._processPrecision = function (source) { var shouldUseHighPrecisionShader = this._engine._shouldUseHighPrecisionShader; if (source.indexOf("precision highp float") === -1) { if (!shouldUseHighPrecisionShader) { source = "precision mediump float;\n" + source; } else { source = "precision highp float;\n" + source; } } else { if (!shouldUseHighPrecisionShader) { // Moving highp to mediump source = source.replace("precision highp float", "precision mediump float"); } } return source; }; /** * 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. * @hidden */ Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) { var _this = this; this._isReady = false; this._vertexSourceCodeOverride = vertexSourceCode; this._fragmentSourceCodeOverride = fragmentSourceCode; this.onError = function (effect, error) { if (onError) { onError(error); } }; this.onCompiled = function () { var scenes = _this.getEngine().scenes; for (var i = 0; i < scenes.length; i++) { scenes[i].markAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_AllDirtyFlag); } if (onCompiled) { onCompiled(_this._program); } }; this._fallbacks = null; this._prepareEffect(); }; /** * Gets the uniform locations of the the specified variable names * @param names THe names of the variables to lookup. * @returns Array of locations in the same order as variable names. */ Effect.prototype.getSpecificUniformLocations = function (names) { var engine = this._engine; return engine.getUniforms(this._program, names); }; /** * Prepares the effect * @hidden */ Effect.prototype._prepareEffect = function () { var _this = this; var attributesNames = this._attributesNames; var defines = this.defines; var fallbacks = this._fallbacks; this._valueCache = {}; var previousProgram = this._program; try { var engine_1 = this._engine; if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) { this._program = engine_1.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings); } else { this._program = engine_1.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings); } this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this); engine_1._executeWhenProgramIsCompiled(this._program, function () { if (engine_1.supportsUniformBuffers) { for (var name in _this._uniformBuffersNames) { _this.bindUniformBlock(name, _this._uniformBuffersNames[name]); } } _this._uniforms = engine_1.getUniforms(_this._program, _this._uniformsNames); _this._attributes = engine_1.getAttributes(_this._program, attributesNames); var index; for (index = 0; index < _this._samplers.length; index++) { var sampler = _this.getUniform(_this._samplers[index]); if (sampler == null) { _this._samplers.splice(index, 1); index--; } } engine_1.bindSamplers(_this); _this._compilationError = ""; _this._isReady = true; if (_this.onCompiled) { _this.onCompiled(_this); } _this.onCompileObservable.notifyObservers(_this); _this.onCompileObservable.clear(); // Unbind mesh reference in fallbacks if (_this._fallbacks) { _this._fallbacks.unBindMesh(); } if (previousProgram) { _this.getEngine()._deleteProgram(previousProgram); } }); if (this._program.isParallelCompiled) { this._checkIsReady(); } } catch (e) { this._compilationError = e.message; // Let's go through fallbacks then _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error("Unable to compile effect:"); _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error("Uniforms: " + this._uniformsNames.map(function (uniform) { return " " + uniform; })); _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error("Attributes: " + attributesNames.map(function (attribute) { return " " + attribute; })); _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error("Error: " + this._compilationError); if (previousProgram) { this._program = previousProgram; this._isReady = true; if (this.onError) { this.onError(this, this._compilationError); } this.onErrorObservable.notifyObservers(this); } if (fallbacks && fallbacks.isMoreFallbacks) { _Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error("Trying next fallback."); this.defines = fallbacks.reduce(this.defines, this); this._prepareEffect(); } else { // Sorry we did everything we can if (this.onError) { this.onError(this, this._compilationError); } this.onErrorObservable.notifyObservers(this); this.onErrorObservable.clear(); // Unbind mesh reference in fallbacks if (this._fallbacks) { this._fallbacks.unBindMesh(); } } } }; Object.defineProperty(Effect.prototype, "isSupported", { /** * Checks if the effect is supported. (Must be called after compilation) */ get: function () { return this._compilationError === ""; }, enumerable: true, configurable: true }); /** * 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. * @hidden */ Effect.prototype._bindTexture = function (channel, texture) { this._engine._bindTexture(this._samplers.indexOf(channel), texture); }; /** * Sets a texture on the engine to be used in the shader. * @param channel Name of the sampler variable. * @param texture Texture to set. */ Effect.prototype.setTexture = function (channel, texture) { this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture); }; /** * Sets a depth stencil texture from a render target on the engine to be used in the shader. * @param channel Name of the sampler variable. * @param texture Texture to set. */ Effect.prototype.setDepthStencilTexture = function (channel, texture) { this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture); }; /** * 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. */ Effect.prototype.setTextureArray = function (channel, textures) { if (this._samplers.indexOf(channel + "Ex") === -1) { var initialPos = this._samplers.indexOf(channel); for (var index = 1; index < textures.length; index++) { this._samplers.splice(initialPos + index, 0, channel + "Ex"); } } this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures); }; /** * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline) * @param channel Name of the sampler variable. * @param postProcess Post process to get the input texture from. */ Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) { this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess); }; /** * (Warning! setTextureFromPostProcessOutput may be desired instead) * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput) * @param channel Name of the sampler variable. * @param postProcess Post process to get the output texture from. */ Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) { this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess); }; /** @hidden */ Effect.prototype._cacheMatrix = function (uniformName, matrix) { var cache = this._valueCache[uniformName]; var flag = matrix.updateFlag; if (cache !== undefined && cache === flag) { return false; } this._valueCache[uniformName] = flag; return true; }; /** @hidden */ Effect.prototype._cacheFloat2 = function (uniformName, x, y) { var cache = this._valueCache[uniformName]; if (!cache) { cache = [x, y]; this._valueCache[uniformName] = cache; return true; } var changed = false; if (cache[0] !== x) { cache[0] = x; changed = true; } if (cache[1] !== y) { cache[1] = y; changed = true; } return changed; }; /** @hidden */ Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) { var cache = this._valueCache[uniformName]; if (!cache) { cache = [x, y, z]; this._valueCache[uniformName] = cache; return true; } var 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; }; /** @hidden */ Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) { var cache = this._valueCache[uniformName]; if (!cache) { cache = [x, y, z, w]; this._valueCache[uniformName] = cache; return true; } var 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; }; /** * Binds a buffer to a uniform. * @param buffer Buffer to bind. * @param name Name of the uniform variable to bind to. */ Effect.prototype.bindUniformBuffer = function (buffer, name) { var bufferName = this._uniformBuffersNames[name]; if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) { return; } Effect._baseCache[bufferName] = buffer; this._engine.bindUniformBufferBase(buffer, bufferName); }; /** * Binds block to a uniform. * @param blockName Name of the block to bind. * @param index Index to bind. */ Effect.prototype.bindUniformBlock = function (blockName, index) { this._engine.bindUniformBlock(this._program, blockName, index); }; /** * Sets an interger value on a uniform variable. * @param uniformName Name of the variable. * @param value Value to be set. * @returns this effect. */ Effect.prototype.setInt = function (uniformName, value) { var cache = this._valueCache[uniformName]; if (cache !== undefined && cache === value) { return this; } this._valueCache[uniformName] = value; this._engine.setInt(this.getUniform(uniformName), value); 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. */ Effect.prototype.setIntArray = function (uniformName, array) { this._valueCache[uniformName] = null; this._engine.setIntArray(this.getUniform(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. */ Effect.prototype.setIntArray2 = function (uniformName, array) { this._valueCache[uniformName] = null; this._engine.setIntArray2(this.getUniform(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. */ Effect.prototype.setIntArray3 = function (uniformName, array) { this._valueCache[uniformName] = null; this._engine.setIntArray3(this.getUniform(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. */ Effect.prototype.setIntArray4 = function (uniformName, array) { this._valueCache[uniformName] = null; this._engine.setIntArray4(this.getUniform(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. */ Effect.prototype.setFloatArray = function (uniformName, array) { this._valueCache[uniformName] = null; this._engine.setFloatArray(this.getUniform(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. */ Effect.prototype.setFloatArray2 = function (uniformName, array) { this._valueCache[uniformName] = null; this._engine.setFloatArray2(this.getUniform(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. */ Effect.prototype.setFloatArray3 = function (uniformName, array) { this._valueCache[uniformName] = null; this._engine.setFloatArray3(this.getUniform(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. */ Effect.prototype.setFloatArray4 = function (uniformName, array) { this._valueCache[uniformName] = null; this._engine.setFloatArray4(this.getUniform(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. */ Effect.prototype.setArray = function (uniformName, array) { this._valueCache[uniformName] = null; this._engine.setArray(this.getUniform(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. */ Effect.prototype.setArray2 = function (uniformName, array) { this._valueCache[uniformName] = null; this._engine.setArray2(this.getUniform(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. */ Effect.prototype.setArray3 = function (uniformName, array) { this._valueCache[uniformName] = null; this._engine.setArray3(this.getUniform(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. */ Effect.prototype.setArray4 = function (uniformName, array) { this._valueCache[uniformName] = null; this._engine.setArray4(this.getUniform(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. */ Effect.prototype.setMatrices = function (uniformName, matrices) { if (!matrices) { return this; } this._valueCache[uniformName] = null; this._engine.setMatrices(this.getUniform(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. */ Effect.prototype.setMatrix = function (uniformName, matrix) { if (this._cacheMatrix(uniformName, matrix)) { this._engine.setMatrix(this.getUniform(uniformName), matrix); } return this; }; /** * Sets a 3x3 matrix on a uniform variable. (Speicified 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. */ Effect.prototype.setMatrix3x3 = function (uniformName, matrix) { this._valueCache[uniformName] = null; this._engine.setMatrix3x3(this.getUniform(uniformName), matrix); return this; }; /** * Sets a 2x2 matrix on a uniform variable. (Speicified 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. */ Effect.prototype.setMatrix2x2 = function (uniformName, matrix) { this._valueCache[uniformName] = null; this._engine.setMatrix2x2(this.getUniform(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. */ Effect.prototype.setFloat = function (uniformName, value) { var cache = this._valueCache[uniformName]; if (cache !== undefined && cache === value) { return this; } this._valueCache[uniformName] = value; this._engine.setFloat(this.getUniform(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. */ Effect.prototype.setBool = function (uniformName, bool) { var cache = this._valueCache[uniformName]; if (cache !== undefined && cache === bool) { return this; } this._valueCache[uniformName] = bool; this._engine.setBool(this.getUniform(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. */ Effect.prototype.setVector2 = function (uniformName, vector2) { if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) { this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y); } 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. */ Effect.prototype.setFloat2 = function (uniformName, x, y) { if (this._cacheFloat2(uniformName, x, y)) { this._engine.setFloat2(this.getUniform(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. */ Effect.prototype.setVector3 = function (uniformName, vector3) { if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) { this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z); } 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. */ Effect.prototype.setFloat3 = function (uniformName, x, y, z) { if (this._cacheFloat3(uniformName, x, y, z)) { this._engine.setFloat3(this.getUniform(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. */ Effect.prototype.setVector4 = function (uniformName, vector4) { if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) { this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w); } 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. */ Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) { if (this._cacheFloat4(uniformName, x, y, z, w)) { this._engine.setFloat4(this.getUniform(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. */ Effect.prototype.setColor3 = function (uniformName, color3) { if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) { this._engine.setColor3(this.getUniform(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. */ Effect.prototype.setColor4 = function (uniformName, color3, alpha) { if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) { this._engine.setColor4(this.getUniform(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. */ Effect.prototype.setDirectColor4 = function (uniformName, color4) { if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) { this._engine.setDirectColor4(this.getUniform(uniformName), color4); } return this; }; /** * 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 */ Effect.RegisterShader = function (name, pixelShader, vertexShader) { if (pixelShader) { Effect.ShadersStore[name + "PixelShader"] = pixelShader; } if (vertexShader) { Effect.ShadersStore[name + "VertexShader"] = vertexShader; } }; /** * Resets the cache of effects. */ Effect.ResetCache = function () { Effect._baseCache = {}; }; /** * Gets or sets the relative url used to load shaders if using the engine in non-minified mode */ Effect.ShadersRepository = "src/Shaders/"; Effect._uniqueIdSeed = 0; Effect._baseCache = {}; /** * Store of each shader (The can be looked up using effect.key) */ Effect.ShadersStore = {}; /** * Store of each included file for a shader (The can be looked up using effect.key) */ Effect.IncludesShadersStore = {}; return Effect; }()); /***/ }), /***/ "./Materials/fresnelParameters.ts": /*!****************************************!*\ !*** ./Materials/fresnelParameters.ts ***! \****************************************/ /*! exports provided: FresnelParameters */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FresnelParameters", function() { return FresnelParameters; }); /* harmony import */ var _Misc_deepCopier__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/deepCopier */ "./Misc/deepCopier.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); /** * This represents all the required information to add a fresnel effect on a material: * @see http://doc.babylonjs.com/how_to/how_to_use_fresnelparameters */ var FresnelParameters = /** @class */ (function () { function FresnelParameters() { this._isEnabled = true; /** * Define the color used on edges (grazing angle) */ this.leftColor = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color3"].White(); /** * Define the color used on center */ this.rightColor = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color3"].Black(); /** * Define bias applied to computed fresnel term */ this.bias = 0; /** * Defined the power exponent applied to fresnel term */ this.power = 1; } Object.defineProperty(FresnelParameters.prototype, "isEnabled", { /** * Define if the fresnel effect is enable or not. */ get: function () { return this._isEnabled; }, set: function (value) { if (this._isEnabled === value) { return; } this._isEnabled = value; _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_4__["Constants"].MATERIAL_FresnelDirtyFlag | _Engines_constants__WEBPACK_IMPORTED_MODULE_4__["Constants"].MATERIAL_MiscDirtyFlag); }, enumerable: true, configurable: true }); /** * Clones the current fresnel and its valuues * @returns a clone fresnel configuration */ FresnelParameters.prototype.clone = function () { var newFresnelParameters = new FresnelParameters(); _Misc_deepCopier__WEBPACK_IMPORTED_MODULE_0__["DeepCopier"].DeepCopy(this, newFresnelParameters); return newFresnelParameters; }; /** * Serializes the current fresnel parameters to a JSON representation. * @return the JSON serialization */ FresnelParameters.prototype.serialize = function () { var serializationObject = {}; serializationObject.isEnabled = this.isEnabled; serializationObject.leftColor = this.leftColor.asArray(); serializationObject.rightColor = this.rightColor.asArray(); serializationObject.bias = this.bias; serializationObject.power = this.power; return serializationObject; }; /** * Parse a JSON object and deserialize it to a new Fresnel parameter object. * @param parsedFresnelParameters Define the JSON representation * @returns the parsed parameters */ FresnelParameters.Parse = function (parsedFresnelParameters) { var fresnelParameters = new FresnelParameters(); fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled; fresnelParameters.leftColor = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color3"].FromArray(parsedFresnelParameters.leftColor); fresnelParameters.rightColor = _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Color3"].FromArray(parsedFresnelParameters.rightColor); fresnelParameters.bias = parsedFresnelParameters.bias; fresnelParameters.power = parsedFresnelParameters.power || 1.0; return fresnelParameters; }; return FresnelParameters; }()); // References the dependencies. _Misc_decorators__WEBPACK_IMPORTED_MODULE_3__["SerializationHelper"]._FresnelParametersParser = FresnelParameters.Parse; /***/ }), /***/ "./Materials/imageProcessingConfiguration.ts": /*!***************************************************!*\ !*** ./Materials/imageProcessingConfiguration.ts ***! \***************************************************/ /*! exports provided: ImageProcessingConfigurationDefines, ImageProcessingConfiguration */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingConfigurationDefines", function() { return ImageProcessingConfigurationDefines; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingConfiguration", function() { return ImageProcessingConfiguration; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Materials_materialDefines__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Materials/materialDefines */ "./Materials/materialDefines.ts"); /* harmony import */ var _Materials_colorCurves__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Materials/colorCurves */ "./Materials/colorCurves.ts"); /** * @hidden */ var ImageProcessingConfigurationDefines = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ImageProcessingConfigurationDefines, _super); function ImageProcessingConfigurationDefines() { var _this = _super.call(this) || this; _this.IMAGEPROCESSING = false; _this.VIGNETTE = false; _this.VIGNETTEBLENDMODEMULTIPLY = false; _this.VIGNETTEBLENDMODEOPAQUE = false; _this.TONEMAPPING = false; _this.TONEMAPPING_ACES = false; _this.CONTRAST = false; _this.COLORCURVES = false; _this.COLORGRADING = false; _this.COLORGRADING3D = false; _this.SAMPLER3DGREENDEPTH = false; _this.SAMPLER3DBGRMAP = false; _this.IMAGEPROCESSINGPOSTPROCESS = false; _this.EXPOSURE = false; _this.rebuild(); return _this; } return ImageProcessingConfigurationDefines; }(_Materials_materialDefines__WEBPACK_IMPORTED_MODULE_5__["MaterialDefines"])); /** * This groups together the common properties used for image processing either in direct forward pass * or through post processing effect depending on the use of the image processing pipeline in your scene * or not. */ var ImageProcessingConfiguration = /** @class */ (function () { function ImageProcessingConfiguration() { /** * Color curves setup used in the effect if colorCurvesEnabled is set to true */ this.colorCurves = new _Materials_colorCurves__WEBPACK_IMPORTED_MODULE_6__["ColorCurves"](); this._colorCurvesEnabled = false; this._colorGradingEnabled = false; this._colorGradingWithGreenDepth = true; this._colorGradingBGR = true; /** @hidden */ this._exposure = 1.0; this._toneMappingEnabled = false; this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD; this._contrast = 1.0; /** * Vignette stretch size. */ this.vignetteStretch = 0; /** * Vignette centre X Offset. */ this.vignetteCentreX = 0; /** * Vignette centre Y Offset. */ this.vignetteCentreY = 0; /** * Vignette weight or intensity of the vignette effect. */ this.vignetteWeight = 1.5; /** * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode) * if vignetteEnabled is set to true. */ this.vignetteColor = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Color4"](0, 0, 0, 0); /** * Camera field of view used by the Vignette effect. */ this.vignetteCameraFov = 0.5; this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY; this._vignetteEnabled = false; this._applyByPostProcess = false; this._isEnabled = true; /** * An event triggered when the configuration changes and requires Shader to Update some parameters. */ this.onUpdateParameters = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); } Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", { /** * Gets wether the color curves effect is enabled. */ get: function () { return this._colorCurvesEnabled; }, /** * Sets wether the color curves effect is enabled. */ set: function (value) { if (this._colorCurvesEnabled === value) { return; } this._colorCurvesEnabled = value; this._updateParameters(); }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingTexture", { /** * Color grading LUT texture used in the effect if colorGradingEnabled is set to true */ get: function () { return this._colorGradingTexture; }, /** * Color grading LUT texture used in the effect if colorGradingEnabled is set to true */ set: function (value) { if (this._colorGradingTexture === value) { return; } this._colorGradingTexture = value; this._updateParameters(); }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", { /** * Gets wether the color grading effect is enabled. */ get: function () { return this._colorGradingEnabled; }, /** * Sets wether the color grading effect is enabled. */ set: function (value) { if (this._colorGradingEnabled === value) { return; } this._colorGradingEnabled = value; this._updateParameters(); }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", { /** * Gets wether the color grading effect is using a green depth for the 3d Texture. */ get: function () { return this._colorGradingWithGreenDepth; }, /** * Sets wether the color grading effect is using a green depth for the 3d Texture. */ set: function (value) { if (this._colorGradingWithGreenDepth === value) { return; } this._colorGradingWithGreenDepth = value; this._updateParameters(); }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", { /** * Gets wether the color grading texture contains BGR values. */ get: function () { return this._colorGradingBGR; }, /** * Sets wether the color grading texture contains BGR values. */ set: function (value) { if (this._colorGradingBGR === value) { return; } this._colorGradingBGR = value; this._updateParameters(); }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", { /** * Gets the Exposure used in the effect. */ get: function () { return this._exposure; }, /** * Sets the Exposure used in the effect. */ set: function (value) { if (this._exposure === value) { return; } this._exposure = value; this._updateParameters(); }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", { /** * Gets wether the tone mapping effect is enabled. */ get: function () { return this._toneMappingEnabled; }, /** * Sets wether the tone mapping effect is enabled. */ set: function (value) { if (this._toneMappingEnabled === value) { return; } this._toneMappingEnabled = value; this._updateParameters(); }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", { /** * Gets the type of tone mapping effect. */ get: function () { return this._toneMappingType; }, /** * Sets the type of tone mapping effect used in BabylonJS. */ set: function (value) { if (this._toneMappingType === value) { return; } this._toneMappingType = value; this._updateParameters(); }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", { /** * Gets the contrast used in the effect. */ get: function () { return this._contrast; }, /** * Sets the contrast used in the effect. */ set: function (value) { if (this._contrast === value) { return; } this._contrast = value; this._updateParameters(); }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", { /** * Gets the vignette blend mode allowing different kind of effect. */ get: function () { return this._vignetteBlendMode; }, /** * Sets the vignette blend mode allowing different kind of effect. */ set: function (value) { if (this._vignetteBlendMode === value) { return; } this._vignetteBlendMode = value; this._updateParameters(); }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", { /** * Gets wether the vignette effect is enabled. */ get: function () { return this._vignetteEnabled; }, /** * Sets wether the vignette effect is enabled. */ set: function (value) { if (this._vignetteEnabled === value) { return; } this._vignetteEnabled = value; this._updateParameters(); }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", { /** * Gets wether the image processing is applied through a post process or not. */ get: function () { return this._applyByPostProcess; }, /** * Sets wether the image processing is applied through a post process or not. */ set: function (value) { if (this._applyByPostProcess === value) { return; } this._applyByPostProcess = value; this._updateParameters(); }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", { /** * Gets wether the image processing is enabled or not. */ get: function () { return this._isEnabled; }, /** * Sets wether the image processing is enabled or not. */ set: function (value) { if (this._isEnabled === value) { return; } this._isEnabled = value; this._updateParameters(); }, enumerable: true, configurable: true }); /** * Method called each time the image processing information changes requires to recompile the effect. */ ImageProcessingConfiguration.prototype._updateParameters = function () { this.onUpdateParameters.notifyObservers(this); }; /** * Gets the current class name. * @return "ImageProcessingConfiguration" */ ImageProcessingConfiguration.prototype.getClassName = function () { return "ImageProcessingConfiguration"; }; /** * Prepare the list of uniforms associated with the Image Processing effects. * @param uniforms The list of uniforms used in the effect * @param defines the list of defines currently in use */ ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) { if (defines.EXPOSURE) { uniforms.push("exposureLinear"); } if (defines.CONTRAST) { uniforms.push("contrast"); } if (defines.COLORGRADING) { uniforms.push("colorTransformSettings"); } if (defines.VIGNETTE) { uniforms.push("vInverseScreenSize"); uniforms.push("vignetteSettings1"); uniforms.push("vignetteSettings2"); } if (defines.COLORCURVES) { _Materials_colorCurves__WEBPACK_IMPORTED_MODULE_6__["ColorCurves"].PrepareUniforms(uniforms); } }; /** * Prepare the list of samplers associated with the Image Processing effects. * @param samplersList The list of uniforms used in the effect * @param defines the list of defines currently in use */ ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) { if (defines.COLORGRADING) { samplersList.push("txColorTransform"); } }; /** * 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 */ ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) { if (forPostProcess === void 0) { forPostProcess = false; } if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) { defines.VIGNETTE = false; defines.TONEMAPPING = false; defines.TONEMAPPING_ACES = false; defines.CONTRAST = false; defines.EXPOSURE = false; defines.COLORCURVES = false; defines.COLORGRADING = false; defines.COLORGRADING3D = false; defines.IMAGEPROCESSING = false; defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled; return; } defines.VIGNETTE = this.vignetteEnabled; defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY); defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY; defines.TONEMAPPING = this.toneMappingEnabled; switch (this._toneMappingType) { case ImageProcessingConfiguration.TONEMAPPING_ACES: defines.TONEMAPPING_ACES = true; break; default: defines.TONEMAPPING_ACES = false; break; } defines.CONTRAST = (this.contrast !== 1.0); defines.EXPOSURE = (this.exposure !== 1.0); defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves); defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture); if (defines.COLORGRADING) { defines.COLORGRADING3D = this.colorGradingTexture.is3D; } else { defines.COLORGRADING3D = false; } defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth; defines.SAMPLER3DBGRMAP = this.colorGradingBGR; defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess; defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING; }; /** * Returns true if all the image processing information are ready. * @returns True if ready, otherwise, false */ ImageProcessingConfiguration.prototype.isReady = function () { // Color Grading texure can not be none blocking. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady(); }; /** * Binds the image processing to the shader. * @param effect The effect to bind to * @param aspectRatio Define the current aspect ratio of the effect */ ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) { if (aspectRatio === void 0) { aspectRatio = 1; } // Color Curves if (this._colorCurvesEnabled && this.colorCurves) { _Materials_colorCurves__WEBPACK_IMPORTED_MODULE_6__["ColorCurves"].Bind(this.colorCurves, effect); } // Vignette if (this._vignetteEnabled) { var inverseWidth = 1 / effect.getEngine().getRenderWidth(); var inverseHeight = 1 / effect.getEngine().getRenderHeight(); effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight); var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5); var vignetteScaleX = vignetteScaleY * aspectRatio; var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY); vignetteScaleX = _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch); vignetteScaleY = _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch); effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY); var vignettePower = -2.0 * this.vignetteWeight; effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower); } // Exposure effect.setFloat("exposureLinear", this.exposure); // Contrast effect.setFloat("contrast", this.contrast); // Color transform settings if (this.colorGradingTexture) { effect.setTexture("txColorTransform", this.colorGradingTexture); var 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. * @return The cloned image processing */ ImageProcessingConfiguration.prototype.clone = function () { return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return new ImageProcessingConfiguration(); }, this); }; /** * Serializes the current image processing instance to a json representation. * @return a JSON representation */ ImageProcessingConfiguration.prototype.serialize = function () { return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); }; /** * Parses the image processing from a json representation. * @param source the JSON source to parse * @return The parsed image processing */ ImageProcessingConfiguration.Parse = function (source) { return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null); }; Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", { /** * Used to apply the vignette as a mix with the pixel color. */ get: function () { return this._VIGNETTEMODE_MULTIPLY; }, enumerable: true, configurable: true }); Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", { /** * Used to apply the vignette as a replacement of the pixel color. */ get: function () { return this._VIGNETTEMODE_OPAQUE; }, enumerable: true, configurable: true }); /** * Default tone mapping applied in BabylonJS. */ ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0; /** * ACES Tone mapping (used by default in unreal and unity). This can help getting closer * to other engines rendering to increase portability. */ ImageProcessingConfiguration.TONEMAPPING_ACES = 1; // Static constants associated to the image processing. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0; ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColorCurves"])() ], ImageProcessingConfiguration.prototype, "colorCurves", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])("colorGradingTexture") ], ImageProcessingConfiguration.prototype, "_colorGradingTexture", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ImageProcessingConfiguration.prototype, "_exposure", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ImageProcessingConfiguration.prototype, "_contrast", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor4"])() ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0); return ImageProcessingConfiguration; }()); // References the dependencies. _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"]._ImageProcessingConfigurationParser = ImageProcessingConfiguration.Parse; /***/ }), /***/ "./Materials/index.ts": /*!****************************!*\ !*** ./Materials/index.ts ***! \****************************/ /*! exports provided: ColorCurves, EffectFallbacks, EffectCreationOptions, Effect, FresnelParameters, ImageProcessingConfigurationDefines, ImageProcessingConfiguration, Material, MaterialDefines, MaterialHelper, MultiMaterial, PushMaterial, ShaderMaterial, StandardMaterialDefines, StandardMaterial, BaseTexture, CubeTexture, EquiRectangularCubeTexture, HDRCubeTexture, InternalTexture, MirrorTexture, MultiRenderTarget, RawTexture, RenderTargetTexture, Texture, UniformBuffer, MaterialFlags, BackgroundMaterial, PBRMaterialDefines, PBRBaseMaterial, PBRBaseSimpleMaterial, PBRMaterial, PBRMetallicRoughnessMaterial, PBRSpecularGlossinessMaterial, ColorGradingTexture, DynamicTexture, ProceduralTexture, RawCubeTexture, RawTexture3D, RefractionTexture, VideoTexture, _DDSTextureLoader, _ENVTextureLoader, _KTXTextureLoader, _TGATextureLoader, CustomProceduralTexture, NoiseProceduralTexture, ProceduralTextureSceneComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _Background_index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Background/index */ "./Materials/Background/index.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BackgroundMaterial", function() { return _Background_index__WEBPACK_IMPORTED_MODULE_0__["BackgroundMaterial"]; }); /* harmony import */ var _colorCurves__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./colorCurves */ "./Materials/colorCurves.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorCurves", function() { return _colorCurves__WEBPACK_IMPORTED_MODULE_1__["ColorCurves"]; }); /* harmony import */ var _effect__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./effect */ "./Materials/effect.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EffectFallbacks", function() { return _effect__WEBPACK_IMPORTED_MODULE_2__["EffectFallbacks"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EffectCreationOptions", function() { return _effect__WEBPACK_IMPORTED_MODULE_2__["EffectCreationOptions"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Effect", function() { return _effect__WEBPACK_IMPORTED_MODULE_2__["Effect"]; }); /* harmony import */ var _fresnelParameters__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./fresnelParameters */ "./Materials/fresnelParameters.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FresnelParameters", function() { return _fresnelParameters__WEBPACK_IMPORTED_MODULE_3__["FresnelParameters"]; }); /* harmony import */ var _imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./imageProcessingConfiguration */ "./Materials/imageProcessingConfiguration.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingConfigurationDefines", function() { return _imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_4__["ImageProcessingConfigurationDefines"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingConfiguration", function() { return _imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_4__["ImageProcessingConfiguration"]; }); /* harmony import */ var _material__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./material */ "./Materials/material.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Material", function() { return _material__WEBPACK_IMPORTED_MODULE_5__["Material"]; }); /* harmony import */ var _materialDefines__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./materialDefines */ "./Materials/materialDefines.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MaterialDefines", function() { return _materialDefines__WEBPACK_IMPORTED_MODULE_6__["MaterialDefines"]; }); /* harmony import */ var _materialHelper__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./materialHelper */ "./Materials/materialHelper.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MaterialHelper", function() { return _materialHelper__WEBPACK_IMPORTED_MODULE_7__["MaterialHelper"]; }); /* harmony import */ var _multiMaterial__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./multiMaterial */ "./Materials/multiMaterial.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiMaterial", function() { return _multiMaterial__WEBPACK_IMPORTED_MODULE_8__["MultiMaterial"]; }); /* harmony import */ var _PBR_index__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./PBR/index */ "./Materials/PBR/index.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMaterialDefines", function() { return _PBR_index__WEBPACK_IMPORTED_MODULE_9__["PBRMaterialDefines"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRBaseMaterial", function() { return _PBR_index__WEBPACK_IMPORTED_MODULE_9__["PBRBaseMaterial"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRBaseSimpleMaterial", function() { return _PBR_index__WEBPACK_IMPORTED_MODULE_9__["PBRBaseSimpleMaterial"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMaterial", function() { return _PBR_index__WEBPACK_IMPORTED_MODULE_9__["PBRMaterial"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMetallicRoughnessMaterial", function() { return _PBR_index__WEBPACK_IMPORTED_MODULE_9__["PBRMetallicRoughnessMaterial"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRSpecularGlossinessMaterial", function() { return _PBR_index__WEBPACK_IMPORTED_MODULE_9__["PBRSpecularGlossinessMaterial"]; }); /* harmony import */ var _pushMaterial__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./pushMaterial */ "./Materials/pushMaterial.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PushMaterial", function() { return _pushMaterial__WEBPACK_IMPORTED_MODULE_10__["PushMaterial"]; }); /* harmony import */ var _shaderMaterial__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./shaderMaterial */ "./Materials/shaderMaterial.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShaderMaterial", function() { return _shaderMaterial__WEBPACK_IMPORTED_MODULE_11__["ShaderMaterial"]; }); /* harmony import */ var _standardMaterial__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./standardMaterial */ "./Materials/standardMaterial.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StandardMaterialDefines", function() { return _standardMaterial__WEBPACK_IMPORTED_MODULE_12__["StandardMaterialDefines"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StandardMaterial", function() { return _standardMaterial__WEBPACK_IMPORTED_MODULE_12__["StandardMaterial"]; }); /* harmony import */ var _Textures_index__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Textures/index */ "./Materials/Textures/index.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BaseTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["BaseTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CubeTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["CubeTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EquiRectangularCubeTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["EquiRectangularCubeTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HDRCubeTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["HDRCubeTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InternalTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["InternalTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MirrorTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["MirrorTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiRenderTarget", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["MultiRenderTarget"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RawTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["RawTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RenderTargetTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["RenderTargetTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Texture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["Texture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorGradingTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["ColorGradingTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DynamicTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["DynamicTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ProceduralTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["ProceduralTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RawCubeTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["RawCubeTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RawTexture3D", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["RawTexture3D"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RefractionTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["RefractionTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VideoTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["VideoTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_DDSTextureLoader", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["_DDSTextureLoader"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_ENVTextureLoader", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["_ENVTextureLoader"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_KTXTextureLoader", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["_KTXTextureLoader"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_TGATextureLoader", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["_TGATextureLoader"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CustomProceduralTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["CustomProceduralTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NoiseProceduralTexture", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["NoiseProceduralTexture"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ProceduralTextureSceneComponent", function() { return _Textures_index__WEBPACK_IMPORTED_MODULE_13__["ProceduralTextureSceneComponent"]; }); /* harmony import */ var _uniformBuffer__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./uniformBuffer */ "./Materials/uniformBuffer.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UniformBuffer", function() { return _uniformBuffer__WEBPACK_IMPORTED_MODULE_14__["UniformBuffer"]; }); /* harmony import */ var _materialFlags__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./materialFlags */ "./Materials/materialFlags.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MaterialFlags", function() { return _materialFlags__WEBPACK_IMPORTED_MODULE_15__["MaterialFlags"]; }); /***/ }), /***/ "./Materials/material.ts": /*!*******************************!*\ !*** ./Materials/material.ts ***! \*******************************/ /*! exports provided: Material */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Material", function() { return Material; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts"); /* harmony import */ var _Meshes_subMesh__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Meshes/subMesh */ "./Meshes/subMesh.ts"); /* harmony import */ var _uniformBuffer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./uniformBuffer */ "./Materials/uniformBuffer.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /** * Base class for the main features of a material in Babylon.js */ var Material = /** @class */ (function () { /** * Creates a material instance * @param name defines the name of the material * @param scene defines the scene to reference * @param doNotAdd specifies if the material should be added to the scene */ function Material(name, scene, doNotAdd) { /** * Gets or sets user defined metadata */ this.metadata = null; /** * For internal use only. Please do not use. */ this.reservedDataStore = null; /** * Specifies if the ready state should be checked on each call */ this.checkReadyOnEveryCall = false; /** * Specifies if the ready state should be checked once */ this.checkReadyOnlyOnce = false; /** * The state of the material */ this.state = ""; /** * The alpha value of the material */ this._alpha = 1.0; /** * Specifies if back face culling is enabled */ this._backFaceCulling = true; /** * Specifies if the material should be serialized */ this.doNotSerialize = false; /** * @hidden */ this._storeEffectOnSubMeshes = false; /** * An event triggered when the material is disposed */ this.onDisposeObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](); /** * Stores the value of the alpha mode */ this._alphaMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].ALPHA_COMBINE; /** * Stores the state of the need depth pre-pass value */ this._needDepthPrePass = false; /** * Specifies if depth writing should be disabled */ this.disableDepthWrite = false; /** * Specifies if depth writing should be forced */ this.forceDepthWrite = false; /** * Specifies if there should be a separate pass for culling */ this.separateCullingPass = false; /** * Stores the state specifing if fog should be enabled */ this._fogEnabled = true; /** * Stores the size of points */ this.pointSize = 1.0; /** * Stores the z offset value */ this.zOffset = 0; /** * @hidden * Specifies if the material was previously ready */ this._wasPreviouslyReady = false; /** * Stores the fill mode state */ this._fillMode = Material.TriangleFillMode; /** @hidden */ this._indexInSceneMaterialArray = -1; this.name = name; this.id = name || _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].RandomId(); this._scene = scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; this.uniqueId = this._scene.getUniqueId(); if (this._scene.useRightHandedSystem) { this.sideOrientation = Material.ClockWiseSideOrientation; } else { this.sideOrientation = Material.CounterClockWiseSideOrientation; } this._uniformBuffer = new _uniformBuffer__WEBPACK_IMPORTED_MODULE_7__["UniformBuffer"](this._scene.getEngine()); this._useUBO = this.getScene().getEngine().supportsUniformBuffers; if (!doNotAdd) { this._scene.addMaterial(this); } if (this._scene.useMaterialMeshMap) { this.meshMap = {}; } } Object.defineProperty(Material.prototype, "alpha", { /** * Gets the alpha value of the material */ get: function () { return this._alpha; }, /** * Sets the alpha value of the material */ set: function (value) { if (this._alpha === value) { return; } this._alpha = value; this.markAsDirty(Material.MiscDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(Material.prototype, "backFaceCulling", { /** * Gets the back-face culling state */ get: function () { return this._backFaceCulling; }, /** * Sets the back-face culling state */ set: function (value) { if (this._backFaceCulling === value) { return; } this._backFaceCulling = value; this.markAsDirty(Material.TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(Material.prototype, "hasRenderTargetTextures", { /** * Gets a boolean indicating that current material needs to register RTT */ get: function () { return false; }, enumerable: true, configurable: true }); Object.defineProperty(Material.prototype, "onDispose", { /** * Called during a dispose event */ set: function (callback) { if (this._onDisposeObserver) { this.onDisposeObservable.remove(this._onDisposeObserver); } this._onDisposeObserver = this.onDisposeObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(Material.prototype, "onBindObservable", { /** * An event triggered when the material is bound */ get: function () { if (!this._onBindObservable) { this._onBindObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](); } return this._onBindObservable; }, enumerable: true, configurable: true }); Object.defineProperty(Material.prototype, "onBind", { /** * Called during a bind event */ set: function (callback) { if (this._onBindObserver) { this.onBindObservable.remove(this._onBindObserver); } this._onBindObserver = this.onBindObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(Material.prototype, "onUnBindObservable", { /** * An event triggered when the material is unbound */ get: function () { if (!this._onUnBindObservable) { this._onUnBindObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](); } return this._onUnBindObservable; }, enumerable: true, configurable: true }); Object.defineProperty(Material.prototype, "alphaMode", { /** * Gets the value of the alpha mode */ get: function () { return this._alphaMode; }, /** * Sets the value of the alpha mode. * * | Value | Type | Description | * | --- | --- | --- | * | 0 | ALPHA_DISABLE | | * | 1 | ALPHA_ADD | | * | 2 | ALPHA_COMBINE | | * | 3 | ALPHA_SUBTRACT | | * | 4 | ALPHA_MULTIPLY | | * | 5 | ALPHA_MAXIMIZED | | * | 6 | ALPHA_ONEONE | | * | 7 | ALPHA_PREMULTIPLIED | | * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | | * | 9 | ALPHA_INTERPOLATE | | * | 10 | ALPHA_SCREENMODE | | * */ set: function (value) { if (this._alphaMode === value) { return; } this._alphaMode = value; this.markAsDirty(Material.TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(Material.prototype, "needDepthPrePass", { /** * Gets the depth pre-pass value */ get: function () { return this._needDepthPrePass; }, /** * Sets the need depth pre-pass value */ set: function (value) { if (this._needDepthPrePass === value) { return; } this._needDepthPrePass = value; if (this._needDepthPrePass) { this.checkReadyOnEveryCall = true; } }, enumerable: true, configurable: true }); Object.defineProperty(Material.prototype, "fogEnabled", { /** * Gets the value of the fog enabled state */ get: function () { return this._fogEnabled; }, /** * Sets the state for enabling fog */ set: function (value) { if (this._fogEnabled === value) { return; } this._fogEnabled = value; this.markAsDirty(Material.MiscDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(Material.prototype, "wireframe", { /** * Gets a value specifying if wireframe mode is enabled */ get: function () { switch (this._fillMode) { case Material.WireFrameFillMode: case Material.LineListDrawMode: case Material.LineLoopDrawMode: case Material.LineStripDrawMode: return true; } return this._scene.forceWireframe; }, /** * Sets the state of wireframe mode */ set: function (value) { this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode); }, enumerable: true, configurable: true }); Object.defineProperty(Material.prototype, "pointsCloud", { /** * Gets the value specifying if point clouds are enabled */ get: function () { switch (this._fillMode) { case Material.PointFillMode: case Material.PointListDrawMode: return true; } return this._scene.forcePointsCloud; }, /** * Sets the state of point cloud mode */ set: function (value) { this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode); }, enumerable: true, configurable: true }); Object.defineProperty(Material.prototype, "fillMode", { /** * Gets the material fill mode */ get: function () { return this._fillMode; }, /** * Sets the material fill mode */ set: function (value) { if (this._fillMode === value) { return; } this._fillMode = value; this.markAsDirty(Material.MiscDirtyFlag); }, enumerable: true, configurable: true }); /** * Returns a string representation of the current material * @param fullDetails defines a boolean indicating which levels of logging is desired * @returns a string with material information */ Material.prototype.toString = function (fullDetails) { var ret = "Name: " + this.name; if (fullDetails) { } return ret; }; /** * Gets the class name of the material * @returns a string with the class name of the material */ Material.prototype.getClassName = function () { return "Material"; }; Object.defineProperty(Material.prototype, "isFrozen", { /** * Specifies if updates for the material been locked */ get: function () { return this.checkReadyOnlyOnce; }, enumerable: true, configurable: true }); /** * Locks updates for the material */ Material.prototype.freeze = function () { this.checkReadyOnlyOnce = true; }; /** * Unlocks updates for the material */ Material.prototype.unfreeze = function () { this.checkReadyOnlyOnce = false; }; /** * Specifies if the material is ready to be used * @param mesh defines the mesh to check * @param useInstances specifies if instances should be used * @returns a boolean indicating if the material is ready to be used */ Material.prototype.isReady = function (mesh, useInstances) { return true; }; /** * Specifies that the submesh is ready to be used * @param mesh defines the mesh to check * @param subMesh defines which submesh to check * @param useInstances specifies that instances should be used * @returns a boolean indicating that the submesh is ready or not */ Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) { return false; }; /** * Returns the material effect * @returns the effect associated with the material */ Material.prototype.getEffect = function () { return this._effect; }; /** * Returns the current scene * @returns a Scene */ Material.prototype.getScene = function () { return this._scene; }; /** * Specifies if the material will require alpha blending * @returns a boolean specifying if alpha blending is needed */ Material.prototype.needAlphaBlending = function () { return (this.alpha < 1.0); }; /** * Specifies if the mesh will require alpha blending * @param mesh defines the mesh to check * @returns a boolean specifying if alpha blending is needed for the mesh */ Material.prototype.needAlphaBlendingForMesh = function (mesh) { return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha; }; /** * Specifies if this material should be rendered in alpha test mode * @returns a boolean specifying if an alpha test is needed. */ Material.prototype.needAlphaTesting = function () { return false; }; /** * Gets the texture used for the alpha test * @returns the texture to use for alpha testing */ Material.prototype.getAlphaTestTexture = function () { return null; }; /** * Marks the material to indicate that it needs to be re-calculated */ Material.prototype.markDirty = function () { this._wasPreviouslyReady = false; }; /** @hidden */ Material.prototype._preBind = function (effect, overrideOrientation) { if (overrideOrientation === void 0) { overrideOrientation = null; } var engine = this._scene.getEngine(); var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation; var reverse = orientation === Material.ClockWiseSideOrientation; engine.enableEffect(effect ? effect : this._effect); engine.setState(this.backFaceCulling, this.zOffset, false, reverse); return reverse; }; /** * Binds the material to the mesh * @param world defines the world transformation matrix * @param mesh defines the mesh to bind the material to */ Material.prototype.bind = function (world, mesh) { }; /** * Binds the submesh to the material * @param world defines the world transformation matrix * @param mesh defines the mesh containing the submesh * @param subMesh defines the submesh to bind the material to */ Material.prototype.bindForSubMesh = function (world, mesh, subMesh) { }; /** * Binds the world matrix to the material * @param world defines the world transformation matrix */ Material.prototype.bindOnlyWorldMatrix = function (world) { }; /** * Binds the scene's uniform buffer to the effect. * @param effect defines the effect to bind to the scene uniform buffer * @param sceneUbo defines the uniform buffer storing scene data */ Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) { sceneUbo.bindToEffect(effect, "Scene"); }; /** * Binds the view matrix to the effect * @param effect defines the effect to bind the view matrix to */ Material.prototype.bindView = function (effect) { if (!this._useUBO) { effect.setMatrix("view", this.getScene().getViewMatrix()); } else { this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer()); } }; /** * Binds the view projection matrix to the effect * @param effect defines the effect to bind the view projection matrix to */ Material.prototype.bindViewProjection = function (effect) { if (!this._useUBO) { effect.setMatrix("viewProjection", this.getScene().getTransformMatrix()); } else { this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer()); } }; /** * Specifies if material alpha testing should be turned on for the mesh * @param mesh defines the mesh to check */ Material.prototype._shouldTurnAlphaTestOn = function (mesh) { return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting()); }; /** * Processes to execute after binding the material to a mesh * @param mesh defines the rendered mesh */ Material.prototype._afterBind = function (mesh) { this._scene._cachedMaterial = this; if (mesh) { this._scene._cachedVisibility = mesh.visibility; } else { this._scene._cachedVisibility = 1; } if (this._onBindObservable && mesh) { this._onBindObservable.notifyObservers(mesh); } if (this.disableDepthWrite) { var engine = this._scene.getEngine(); this._cachedDepthWriteState = engine.getDepthWrite(); engine.setDepthWrite(false); } }; /** * Unbinds the material from the mesh */ Material.prototype.unbind = function () { if (this._onUnBindObservable) { this._onUnBindObservable.notifyObservers(this); } if (this.disableDepthWrite) { var engine = this._scene.getEngine(); engine.setDepthWrite(this._cachedDepthWriteState); } }; /** * Gets the active textures from the material * @returns an array of textures */ Material.prototype.getActiveTextures = function () { return []; }; /** * Specifies if the material uses a texture * @param texture defines the texture to check against the material * @returns a boolean specifying if the material uses the texture */ Material.prototype.hasTexture = function (texture) { return false; }; /** * Makes a duplicate of the material, and gives it a new name * @param name defines the new name for the duplicated material * @returns the cloned material */ Material.prototype.clone = function (name) { return null; }; /** * Gets the meshes bound to the material * @returns an array of meshes bound to the material */ Material.prototype.getBindedMeshes = function () { var _this = this; if (this.meshMap) { var result = new Array(); for (var meshId in this.meshMap) { var mesh = this.meshMap[meshId]; if (mesh) { result.push(mesh); } } return result; } else { var meshes = this._scene.meshes; return meshes.filter(function (mesh) { return mesh.material === _this; }); } }; /** * Force shader compilation * @param mesh defines the mesh associated with this material * @param onCompiled defines a function to execute once the material is compiled * @param options defines the options to configure the compilation */ Material.prototype.forceCompilation = function (mesh, onCompiled, options) { var _this = this; var localOptions = tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"]({ clipPlane: false }, options); var subMesh = new _Meshes_subMesh__WEBPACK_IMPORTED_MODULE_6__["BaseSubMesh"](); var scene = this.getScene(); var checkReady = function () { if (!_this._scene || !_this._scene.getEngine()) { return; } if (subMesh._materialDefines) { subMesh._materialDefines._renderId = -1; } var clipPlaneState = scene.clipPlane; if (localOptions.clipPlane) { scene.clipPlane = new _Maths_math__WEBPACK_IMPORTED_MODULE_4__["Plane"](0, 0, 0, 1); } if (_this._storeEffectOnSubMeshes) { if (_this.isReadyForSubMesh(mesh, subMesh)) { if (onCompiled) { onCompiled(_this); } } else { setTimeout(checkReady, 16); } } else { if (_this.isReady()) { if (onCompiled) { onCompiled(_this); } } else { setTimeout(checkReady, 16); } } if (localOptions.clipPlane) { scene.clipPlane = clipPlaneState; } }; checkReady(); }; /** * Force shader compilation * @param mesh defines the mesh that will use this material * @param options defines additional options for compiling the shaders * @returns a promise that resolves when the compilation completes */ Material.prototype.forceCompilationAsync = function (mesh, options) { var _this = this; return new Promise(function (resolve) { _this.forceCompilation(mesh, function () { resolve(); }, options); }); }; /** * Marks a define in the material to indicate that it needs to be re-computed * @param flag defines a flag used to determine which parts of the material have to be marked as dirty */ Material.prototype.markAsDirty = function (flag) { if (this.getScene().blockMaterialDirtyMechanism) { return; } Material._DirtyCallbackArray.length = 0; if (flag & Material.TextureDirtyFlag) { Material._DirtyCallbackArray.push(Material._TextureDirtyCallBack); } if (flag & Material.LightDirtyFlag) { Material._DirtyCallbackArray.push(Material._LightsDirtyCallBack); } if (flag & Material.FresnelDirtyFlag) { Material._DirtyCallbackArray.push(Material._FresnelDirtyCallBack); } if (flag & Material.AttributesDirtyFlag) { Material._DirtyCallbackArray.push(Material._AttributeDirtyCallBack); } if (flag & Material.MiscDirtyFlag) { Material._DirtyCallbackArray.push(Material._MiscDirtyCallBack); } if (Material._DirtyCallbackArray.length) { this._markAllSubMeshesAsDirty(Material._RunDirtyCallBacks); } this.getScene().resetCachedMaterial(); }; /** * Marks all submeshes of a material to indicate that their material defines need to be re-calculated * @param func defines a function which checks material defines against the submeshes */ Material.prototype._markAllSubMeshesAsDirty = function (func) { if (this.getScene().blockMaterialDirtyMechanism) { return; } var meshes = this.getScene().meshes; for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) { var mesh = meshes_1[_i]; if (!mesh.subMeshes) { continue; } for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) { var subMesh = _b[_a]; if (subMesh.getMaterial() !== this) { continue; } if (!subMesh._materialDefines) { continue; } func(subMesh._materialDefines); } } }; /** * Indicates that image processing needs to be re-calculated for all submeshes */ Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () { this._markAllSubMeshesAsDirty(Material._ImageProcessingDirtyCallBack); }; /** * Indicates that textures need to be re-calculated for all submeshes */ Material.prototype._markAllSubMeshesAsTexturesDirty = function () { this._markAllSubMeshesAsDirty(Material._TextureDirtyCallBack); }; /** * Indicates that fresnel needs to be re-calculated for all submeshes */ Material.prototype._markAllSubMeshesAsFresnelDirty = function () { this._markAllSubMeshesAsDirty(Material._FresnelDirtyCallBack); }; /** * Indicates that fresnel and misc need to be re-calculated for all submeshes */ Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () { this._markAllSubMeshesAsDirty(Material._FresnelAndMiscDirtyCallBack); }; /** * Indicates that lights need to be re-calculated for all submeshes */ Material.prototype._markAllSubMeshesAsLightsDirty = function () { this._markAllSubMeshesAsDirty(Material._LightsDirtyCallBack); }; /** * Indicates that attributes need to be re-calculated for all submeshes */ Material.prototype._markAllSubMeshesAsAttributesDirty = function () { this._markAllSubMeshesAsDirty(Material._AttributeDirtyCallBack); }; /** * Indicates that misc needs to be re-calculated for all submeshes */ Material.prototype._markAllSubMeshesAsMiscDirty = function () { this._markAllSubMeshesAsDirty(Material._MiscDirtyCallBack); }; /** * Indicates that textures and misc need to be re-calculated for all submeshes */ Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () { this._markAllSubMeshesAsDirty(Material._TextureAndMiscDirtyCallBack); }; /** * Disposes the material * @param forceDisposeEffect specifies if effects should be forcefully disposed * @param forceDisposeTextures specifies if textures should be forcefully disposed * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh */ Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures, notBoundToMesh) { var scene = this.getScene(); // Animations scene.stopAnimation(this); scene.freeProcessedMaterials(); // Remove from scene scene.removeMaterial(this); if (notBoundToMesh !== true) { // Remove from meshes if (this.meshMap) { for (var meshId in this.meshMap) { var mesh = this.meshMap[meshId]; if (mesh) { mesh.material = null; // will set the entry in the map to undefined this.releaseVertexArrayObject(mesh, forceDisposeEffect); } } } else { var meshes = scene.meshes; for (var _i = 0, meshes_2 = meshes; _i < meshes_2.length; _i++) { var mesh = meshes_2[_i]; if (mesh.material === this) { mesh.material = null; this.releaseVertexArrayObject(mesh, forceDisposeEffect); } } } } this._uniformBuffer.dispose(); // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect if (forceDisposeEffect && this._effect) { if (!this._storeEffectOnSubMeshes) { scene.getEngine()._releaseEffect(this._effect); } this._effect = null; } // Callback this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); if (this._onBindObservable) { this._onBindObservable.clear(); } if (this._onUnBindObservable) { this._onUnBindObservable.clear(); } }; /** @hidden */ Material.prototype.releaseVertexArrayObject = function (mesh, forceDisposeEffect) { if (mesh.geometry) { var geometry = (mesh.geometry); var scene = this.getScene(); if (this._storeEffectOnSubMeshes) { for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) { var subMesh = _a[_i]; geometry._releaseVertexArrayObject(subMesh._materialEffect); if (forceDisposeEffect && subMesh._materialEffect) { scene.getEngine()._releaseEffect(subMesh._materialEffect); } } } else { geometry._releaseVertexArrayObject(this._effect); } } }; /** * Serializes this material * @returns the serialized material object */ Material.prototype.serialize = function () { return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this); }; /** * Creates a material from parsed material data * @param parsedMaterial defines parsed material data * @param scene defines the hosting scene * @param rootUrl defines the root URL to use to load textures * @returns a new material */ Material.Parse = function (parsedMaterial, scene, rootUrl) { if (!parsedMaterial.customType) { parsedMaterial.customType = "BABYLON.StandardMaterial"; } else if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) { parsedMaterial.customType = "BABYLON.LegacyPBRMaterial"; if (!BABYLON.LegacyPBRMaterial) { _Misc_logger__WEBPACK_IMPORTED_MODULE_9__["Logger"].Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."); return null; } } var materialType = _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].Instantiate(parsedMaterial.customType); return materialType.Parse(parsedMaterial, scene, rootUrl); }; /** * Returns the triangle fill mode */ Material.TriangleFillMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_TriangleFillMode; /** * Returns the wireframe mode */ Material.WireFrameFillMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_WireFrameFillMode; /** * Returns the point fill mode */ Material.PointFillMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_PointFillMode; /** * Returns the point list draw mode */ Material.PointListDrawMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_PointListDrawMode; /** * Returns the line list draw mode */ Material.LineListDrawMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_LineListDrawMode; /** * Returns the line loop draw mode */ Material.LineLoopDrawMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_LineLoopDrawMode; /** * Returns the line strip draw mode */ Material.LineStripDrawMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_LineStripDrawMode; /** * Returns the triangle strip draw mode */ Material.TriangleStripDrawMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_TriangleStripDrawMode; /** * Returns the triangle fan draw mode */ Material.TriangleFanDrawMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_TriangleFanDrawMode; /** * Stores the clock-wise side orientation */ Material.ClockWiseSideOrientation = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_ClockWiseSideOrientation; /** * Stores the counter clock-wise side orientation */ Material.CounterClockWiseSideOrientation = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_CounterClockWiseSideOrientation; /** * The dirty texture flag value */ Material.TextureDirtyFlag = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_TextureDirtyFlag; /** * The dirty light flag value */ Material.LightDirtyFlag = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_LightDirtyFlag; /** * The dirty fresnel flag value */ Material.FresnelDirtyFlag = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_FresnelDirtyFlag; /** * The dirty attribute flag value */ Material.AttributesDirtyFlag = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_AttributesDirtyFlag; /** * The dirty misc flag value */ Material.MiscDirtyFlag = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_MiscDirtyFlag; /** * The all dirty flag value */ Material.AllDirtyFlag = _Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].MATERIAL_AllDirtyFlag; Material._ImageProcessingDirtyCallBack = function (defines) { return defines.markAsImageProcessingDirty(); }; Material._TextureDirtyCallBack = function (defines) { return defines.markAsTexturesDirty(); }; Material._FresnelDirtyCallBack = function (defines) { return defines.markAsFresnelDirty(); }; Material._MiscDirtyCallBack = function (defines) { return defines.markAsMiscDirty(); }; Material._LightsDirtyCallBack = function (defines) { return defines.markAsLightDirty(); }; Material._AttributeDirtyCallBack = function (defines) { return defines.markAsAttributesDirty(); }; Material._FresnelAndMiscDirtyCallBack = function (defines) { Material._FresnelDirtyCallBack(defines); Material._MiscDirtyCallBack(defines); }; Material._TextureAndMiscDirtyCallBack = function (defines) { Material._TextureDirtyCallBack(defines); Material._MiscDirtyCallBack(defines); }; Material._DirtyCallbackArray = []; Material._RunDirtyCallBacks = function (defines) { for (var _i = 0, _a = Material._DirtyCallbackArray; _i < _a.length; _i++) { var cb = _a[_i]; cb(defines); } }; tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Material.prototype, "id", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Material.prototype, "uniqueId", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Material.prototype, "name", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Material.prototype, "checkReadyOnEveryCall", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Material.prototype, "checkReadyOnlyOnce", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Material.prototype, "state", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("alpha") ], Material.prototype, "_alpha", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("backFaceCulling") ], Material.prototype, "_backFaceCulling", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Material.prototype, "sideOrientation", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("alphaMode") ], Material.prototype, "_alphaMode", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Material.prototype, "_needDepthPrePass", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Material.prototype, "disableDepthWrite", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Material.prototype, "forceDepthWrite", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Material.prototype, "separateCullingPass", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("fogEnabled") ], Material.prototype, "_fogEnabled", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Material.prototype, "pointSize", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Material.prototype, "zOffset", void 0); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Material.prototype, "wireframe", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Material.prototype, "pointsCloud", null); tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], Material.prototype, "fillMode", null); return Material; }()); /***/ }), /***/ "./Materials/materialDefines.ts": /*!**************************************!*\ !*** ./Materials/materialDefines.ts ***! \**************************************/ /*! exports provided: MaterialDefines */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MaterialDefines", function() { return MaterialDefines; }); /** * Manages the defines for the Material */ var MaterialDefines = /** @class */ (function () { function MaterialDefines() { this._isDirty = true; /** @hidden */ this._areLightsDirty = true; /** @hidden */ this._areAttributesDirty = true; /** @hidden */ this._areTexturesDirty = true; /** @hidden */ this._areFresnelDirty = true; /** @hidden */ this._areMiscDirty = true; /** @hidden */ this._areImageProcessingDirty = true; /** @hidden */ this._normals = false; /** @hidden */ this._uvs = false; /** @hidden */ this._needNormals = false; /** @hidden */ this._needUVs = false; } Object.defineProperty(MaterialDefines.prototype, "isDirty", { /** * Specifies if the material needs to be re-calculated */ get: function () { return this._isDirty; }, enumerable: true, configurable: true }); /** * Marks the material to indicate that it has been re-calculated */ MaterialDefines.prototype.markAsProcessed = function () { this._isDirty = false; this._areAttributesDirty = false; this._areTexturesDirty = false; this._areFresnelDirty = false; this._areLightsDirty = false; this._areMiscDirty = false; this._areImageProcessingDirty = false; }; /** * Marks the material to indicate that it needs to be re-calculated */ MaterialDefines.prototype.markAsUnprocessed = function () { this._isDirty = true; }; /** * Marks the material to indicate all of its defines need to be re-calculated */ MaterialDefines.prototype.markAllAsDirty = function () { this._areTexturesDirty = true; this._areAttributesDirty = true; this._areLightsDirty = true; this._areFresnelDirty = true; this._areMiscDirty = true; this._areImageProcessingDirty = true; this._isDirty = true; }; /** * Marks the material to indicate that image processing needs to be re-calculated */ MaterialDefines.prototype.markAsImageProcessingDirty = function () { this._areImageProcessingDirty = true; this._isDirty = true; }; /** * Marks the material to indicate the lights need to be re-calculated */ MaterialDefines.prototype.markAsLightDirty = function () { this._areLightsDirty = true; this._isDirty = true; }; /** * Marks the attribute state as changed */ MaterialDefines.prototype.markAsAttributesDirty = function () { this._areAttributesDirty = true; this._isDirty = true; }; /** * Marks the texture state as changed */ MaterialDefines.prototype.markAsTexturesDirty = function () { this._areTexturesDirty = true; this._isDirty = true; }; /** * Marks the fresnel state as changed */ MaterialDefines.prototype.markAsFresnelDirty = function () { this._areFresnelDirty = true; this._isDirty = true; }; /** * Marks the misc state as changed */ MaterialDefines.prototype.markAsMiscDirty = function () { this._areMiscDirty = true; this._isDirty = true; }; /** * Rebuilds the material defines */ MaterialDefines.prototype.rebuild = function () { if (this._keys) { delete this._keys; } this._keys = []; for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) { var key = _a[_i]; if (key[0] === "_") { continue; } this._keys.push(key); } }; /** * Specifies if two material defines are equal * @param other - A material define instance to compare to * @returns - Boolean indicating if the material defines are equal (true) or not (false) */ MaterialDefines.prototype.isEqual = function (other) { if (this._keys.length !== other._keys.length) { return false; } for (var index = 0; index < this._keys.length; index++) { var prop = this._keys[index]; if (this[prop] !== other[prop]) { return false; } } return true; }; /** * Clones this instance's defines to another instance * @param other - material defines to clone values to */ MaterialDefines.prototype.cloneTo = function (other) { if (this._keys.length !== other._keys.length) { other._keys = this._keys.slice(0); } for (var index = 0; index < this._keys.length; index++) { var prop = this._keys[index]; other[prop] = this[prop]; } }; /** * Resets the material define values */ MaterialDefines.prototype.reset = function () { for (var index = 0; index < this._keys.length; index++) { var prop = this._keys[index]; var type = typeof this[prop]; switch (type) { case "number": this[prop] = 0; break; case "string": this[prop] = ""; break; default: this[prop] = false; break; } } }; /** * Converts the material define values to a string * @returns - String of material define information */ MaterialDefines.prototype.toString = function () { var result = ""; for (var index = 0; index < this._keys.length; index++) { var prop = this._keys[index]; var value = this[prop]; var type = typeof value; switch (type) { case "number": case "string": result += "#define " + prop + " " + value + "\n"; break; default: if (value) { result += "#define " + prop + "\n"; } break; } } return result; }; return MaterialDefines; }()); /***/ }), /***/ "./Materials/materialFlags.ts": /*!************************************!*\ !*** ./Materials/materialFlags.ts ***! \************************************/ /*! exports provided: MaterialFlags */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MaterialFlags", function() { return MaterialFlags; }); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); /** * This groups all the flags used to control the materials channel. */ var MaterialFlags = /** @class */ (function () { function MaterialFlags() { } Object.defineProperty(MaterialFlags, "DiffuseTextureEnabled", { /** * Are diffuse textures enabled in the application. */ get: function () { return this._DiffuseTextureEnabled; }, set: function (value) { if (this._DiffuseTextureEnabled === value) { return; } this._DiffuseTextureEnabled = value; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(MaterialFlags, "AmbientTextureEnabled", { /** * Are ambient textures enabled in the application. */ get: function () { return this._AmbientTextureEnabled; }, set: function (value) { if (this._AmbientTextureEnabled === value) { return; } this._AmbientTextureEnabled = value; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(MaterialFlags, "OpacityTextureEnabled", { /** * Are opacity textures enabled in the application. */ get: function () { return this._OpacityTextureEnabled; }, set: function (value) { if (this._OpacityTextureEnabled === value) { return; } this._OpacityTextureEnabled = value; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(MaterialFlags, "ReflectionTextureEnabled", { /** * Are reflection textures enabled in the application. */ get: function () { return this._ReflectionTextureEnabled; }, set: function (value) { if (this._ReflectionTextureEnabled === value) { return; } this._ReflectionTextureEnabled = value; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(MaterialFlags, "EmissiveTextureEnabled", { /** * Are emissive textures enabled in the application. */ get: function () { return this._EmissiveTextureEnabled; }, set: function (value) { if (this._EmissiveTextureEnabled === value) { return; } this._EmissiveTextureEnabled = value; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(MaterialFlags, "SpecularTextureEnabled", { /** * Are specular textures enabled in the application. */ get: function () { return this._SpecularTextureEnabled; }, set: function (value) { if (this._SpecularTextureEnabled === value) { return; } this._SpecularTextureEnabled = value; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(MaterialFlags, "BumpTextureEnabled", { /** * Are bump textures enabled in the application. */ get: function () { return this._BumpTextureEnabled; }, set: function (value) { if (this._BumpTextureEnabled === value) { return; } this._BumpTextureEnabled = value; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(MaterialFlags, "LightmapTextureEnabled", { /** * Are lightmap textures enabled in the application. */ get: function () { return this._LightmapTextureEnabled; }, set: function (value) { if (this._LightmapTextureEnabled === value) { return; } this._LightmapTextureEnabled = value; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(MaterialFlags, "RefractionTextureEnabled", { /** * Are refraction textures enabled in the application. */ get: function () { return this._RefractionTextureEnabled; }, set: function (value) { if (this._RefractionTextureEnabled === value) { return; } this._RefractionTextureEnabled = value; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(MaterialFlags, "ColorGradingTextureEnabled", { /** * Are color grading textures enabled in the application. */ get: function () { return this._ColorGradingTextureEnabled; }, set: function (value) { if (this._ColorGradingTextureEnabled === value) { return; } this._ColorGradingTextureEnabled = value; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(MaterialFlags, "FresnelEnabled", { /** * Are fresnels enabled in the application. */ get: function () { return this._FresnelEnabled; }, set: function (value) { if (this._FresnelEnabled === value) { return; } this._FresnelEnabled = value; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_FresnelDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(MaterialFlags, "ClearCoatTextureEnabled", { /** * Are clear coat textures enabled in the application. */ get: function () { return this._ClearCoatTextureEnabled; }, set: function (value) { if (this._ClearCoatTextureEnabled === value) { return; } this._ClearCoatTextureEnabled = value; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(MaterialFlags, "ClearCoatBumpTextureEnabled", { /** * Are clear coat bump textures enabled in the application. */ get: function () { return this._ClearCoatBumpTextureEnabled; }, set: function (value) { if (this._ClearCoatBumpTextureEnabled === value) { return; } this._ClearCoatBumpTextureEnabled = value; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(MaterialFlags, "ClearCoatTintTextureEnabled", { /** * Are clear coat tint textures enabled in the application. */ get: function () { return this._ClearCoatTintTextureEnabled; }, set: function (value) { if (this._ClearCoatTintTextureEnabled === value) { return; } this._ClearCoatTintTextureEnabled = value; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(MaterialFlags, "SheenTextureEnabled", { /** * Are sheen textures enabled in the application. */ get: function () { return this._SheenTextureEnabled; }, set: function (value) { if (this._SheenTextureEnabled === value) { return; } this._SheenTextureEnabled = value; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(MaterialFlags, "AnisotropicTextureEnabled", { /** * Are anisotropic textures enabled in the application. */ get: function () { return this._AnisotropicTextureEnabled; }, set: function (value) { if (this._AnisotropicTextureEnabled === value) { return; } this._AnisotropicTextureEnabled = value; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(MaterialFlags, "ThicknessTextureEnabled", { /** * Are thickness textures enabled in the application. */ get: function () { return this._ThicknessTextureEnabled; }, set: function (value) { if (this._ThicknessTextureEnabled === value) { return; } this._ThicknessTextureEnabled = value; _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].MarkAllMaterialsAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].MATERIAL_TextureDirtyFlag); }, enumerable: true, configurable: true }); // Flags used to enable or disable a type of texture for all Standard Materials MaterialFlags._DiffuseTextureEnabled = 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; return MaterialFlags; }()); /***/ }), /***/ "./Materials/materialHelper.ts": /*!*************************************!*\ !*** ./Materials/materialHelper.ts ***! \*************************************/ /*! exports provided: MaterialHelper */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MaterialHelper", function() { return MaterialHelper; }); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../scene */ "./scene.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts"); /* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/buffer */ "./Meshes/buffer.ts"); /* harmony import */ var _Lights_light__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Lights/light */ "./Lights/light.ts"); /** * "Static Class" containing the most commonly used helper while dealing with material for * rendering purpose. * * It contains the basic tools to help defining defines, binding uniform for the common part of the materials. * * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions. */ var MaterialHelper = /** @class */ (function () { function MaterialHelper() { } /** * Bind the current view position to an effect. * @param effect The effect to be bound * @param scene The scene the eyes position is used from */ MaterialHelper.BindEyePosition = function (effect, scene) { if (scene._forcedViewPosition) { effect.setVector3("vEyePosition", scene._forcedViewPosition); return; } var globalPosition = scene.activeCamera.globalPosition; if (!globalPosition) { // Use WebVRFreecamera's device position as global position is not it's actual position in babylon space globalPosition = scene.activeCamera.devicePosition; } effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : globalPosition); }; /** * Helps preparing the defines values about the UVs in used in the effect. * UVs are shared as much as we can accross channels in the shaders. * @param texture The texture we are preparing the UVs for * @param defines The defines to update * @param key The channel key "diffuse", "specular"... used in the shader */ MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) { defines._needUVs = true; defines[key] = true; if (texture.getTextureMatrix().isIdentityAs3x2()) { defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1; if (texture.coordinatesIndex === 0) { defines["MAINUV1"] = true; } else { defines["MAINUV2"] = true; } } else { defines[key + "DIRECTUV"] = 0; } }; /** * Binds a texture matrix value to its corrsponding uniform * @param texture The texture to bind the matrix for * @param uniformBuffer The uniform buffer receivin the data * @param key The channel key "diffuse", "specular"... used in the shader */ MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) { var matrix = texture.getTextureMatrix(); if (!matrix.isIdentityAs3x2()) { uniformBuffer.updateMatrix(key + "Matrix", matrix); } }; /** * Helper used to prepare the list of defines associated with misc. values for shader compilation * @param mesh defines the current mesh * @param scene defines the current scene * @param useLogarithmicDepth defines if logarithmic depth has to be turned on * @param pointsCloud defines if point cloud rendering has to be turned on * @param fogEnabled defines if fog has to be turned on * @param alphaTest defines if alpha testing has to be turned on * @param defines defines the current list of defines */ MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) { if (defines._areMiscDirty) { defines["LOGARITHMICDEPTH"] = useLogarithmicDepth; defines["POINTSIZE"] = pointsCloud; defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== _scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].FOGMODE_NONE && fogEnabled); defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling; defines["ALPHATEST"] = alphaTest; } }; /** * Helper used to prepare the list of defines associated with frame values for shader compilation * @param scene defines the current scene * @param engine defines the current engine * @param defines specifies the list of active defines * @param useInstances defines if instances have to be turned on * @param useClipPlane defines if clip plane have to be turned on */ MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) { if (useClipPlane === void 0) { useClipPlane = null; } var changed = false; var useClipPlane1 = false; var useClipPlane2 = false; var useClipPlane3 = false; var useClipPlane4 = false; useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane; useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane; useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane; useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane; if (defines["CLIPPLANE"] !== useClipPlane1) { defines["CLIPPLANE"] = useClipPlane1; changed = true; } if (defines["CLIPPLANE2"] !== useClipPlane2) { defines["CLIPPLANE2"] = useClipPlane2; changed = true; } if (defines["CLIPPLANE3"] !== useClipPlane3) { defines["CLIPPLANE3"] = useClipPlane3; changed = true; } if (defines["CLIPPLANE4"] !== useClipPlane4) { defines["CLIPPLANE4"] = useClipPlane4; changed = true; } if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) { defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"]; changed = true; } if (defines["INSTANCES"] !== useInstances) { defines["INSTANCES"] = useInstances; changed = true; } if (changed) { defines.markAsUnprocessed(); } }; /** * Prepares the defines used in the shader depending on the attributes data available in the mesh * @param mesh The mesh containing the geometry data we will draw * @param defines The defines to update * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info) * @param useBones Precise whether bones should be used or not (override mesh info) * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info) * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info) * @returns false if defines are considered not dirty and have not been checked */ MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) { if (useMorphTargets === void 0) { useMorphTargets = false; } if (useVertexAlpha === void 0) { useVertexAlpha = 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(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].NormalKind)); if (defines._needNormals && mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].TangentKind)) { defines["TANGENT"] = true; } if (defines._needUVs) { defines["UV1"] = mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].UVKind); defines["UV2"] = mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].UV2Kind); } else { defines["UV1"] = false; defines["UV2"] = false; } if (useVertexColor) { var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].ColorKind); defines["VERTEXCOLOR"] = hasVertexColors; defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha; } if (useBones) { if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers; var materialSupportsBoneTexture = defines["BONETEXTURE"] !== undefined; if (mesh.skeleton.isUsingTextureForMatrices && materialSupportsBoneTexture) { defines["BONETEXTURE"] = true; } else { defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1); defines["BONETEXTURE"] = materialSupportsBoneTexture ? false : undefined; } } else { defines["NUM_BONE_INFLUENCERS"] = 0; defines["BonesPerMesh"] = 0; } } if (useMorphTargets) { var manager = mesh.morphTargetManager; if (manager) { defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"]; defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"]; defines["MORPHTARGETS"] = (manager.numInfluencers > 0); defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers; } else { defines["MORPHTARGETS_TANGENT"] = false; defines["MORPHTARGETS_NORMAL"] = false; defines["MORPHTARGETS"] = false; defines["NUM_MORPH_INFLUENCERS"] = 0; } } return true; }; /** * Prepares the defines related to multiview * @param scene The scene we are intending to draw * @param defines The defines to update */ MaterialHelper.PrepareDefinesForMultiview = function (scene, defines) { if (scene.activeCamera) { var previousMultiview = defines.MULTIVIEW; defines.MULTIVIEW = (scene.activeCamera.outputRenderTarget !== null && scene.activeCamera.outputRenderTarget.getViewCount() > 1); if (defines.MULTIVIEW != previousMultiview) { defines.markAsUnprocessed(); } } }; /** * Prepares the defines related to the light information passed in parameter * @param scene The scene we are intending to draw * @param mesh The mesh the effect is compiling for * @param defines The defines to update * @param specularSupported Specifies whether specular is supported or not (override lights data) * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max * @param disableLighting Specifies whether the lighting is disabled (override scene and light) * @returns true if normals will be required for the rest of the effect */ MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) { if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; } if (disableLighting === void 0) { disableLighting = false; } if (!defines._areLightsDirty) { return defines._needNormals; } var lightIndex = 0; var needNormals = false; var needRebuild = false; var lightmapMode = false; var shadowEnabled = false; var specularEnabled = false; if (scene.lightsEnabled && !disableLighting) { for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) { var light = _a[_i]; needNormals = true; if (defines["LIGHT" + lightIndex] === undefined) { needRebuild = true; } defines["LIGHT" + lightIndex] = true; defines["SPOTLIGHT" + lightIndex] = false; defines["HEMILIGHT" + lightIndex] = false; defines["POINTLIGHT" + lightIndex] = false; defines["DIRLIGHT" + lightIndex] = false; light.prepareLightSpecificDefines(defines, lightIndex); // FallOff. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false; defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false; defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false; switch (light.falloffType) { case _Lights_light__WEBPACK_IMPORTED_MODULE_5__["Light"].FALLOFF_GLTF: defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true; break; case _Lights_light__WEBPACK_IMPORTED_MODULE_5__["Light"].FALLOFF_PHYSICAL: defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true; break; case _Lights_light__WEBPACK_IMPORTED_MODULE_5__["Light"].FALLOFF_STANDARD: defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true; break; } // Specular if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) { specularEnabled = true; } // Shadows defines["SHADOW" + lightIndex] = false; defines["SHADOWPCF" + lightIndex] = false; defines["SHADOWPCSS" + lightIndex] = false; defines["SHADOWPOISSON" + lightIndex] = false; defines["SHADOWESM" + lightIndex] = false; defines["SHADOWCUBE" + lightIndex] = false; defines["SHADOWLOWQUALITY" + lightIndex] = false; defines["SHADOWMEDIUMQUALITY" + lightIndex] = false; if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) { var shadowGenerator = light.getShadowGenerator(); if (shadowGenerator) { var shadowMap = shadowGenerator.getShadowMap(); if (shadowMap) { if (shadowMap.renderList && shadowMap.renderList.length > 0) { shadowEnabled = true; shadowGenerator.prepareDefines(defines, lightIndex); } } } } if (light.lightmapMode != _Lights_light__WEBPACK_IMPORTED_MODULE_5__["Light"].LIGHTMAP_DEFAULT) { lightmapMode = true; defines["LIGHTMAPEXCLUDED" + lightIndex] = true; defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == _Lights_light__WEBPACK_IMPORTED_MODULE_5__["Light"].LIGHTMAP_SHADOWSONLY); } else { defines["LIGHTMAPEXCLUDED" + lightIndex] = false; defines["LIGHTMAPNOSPECULAR" + lightIndex] = false; } lightIndex++; if (lightIndex === maxSimultaneousLights) { break; } } } defines["SPECULARTERM"] = specularEnabled; defines["SHADOWS"] = shadowEnabled; // Resetting all other lights if any for (var index = lightIndex; index < maxSimultaneousLights; index++) { if (defines["LIGHT" + index] !== undefined) { defines["LIGHT" + index] = false; defines["HEMILIGHT" + index] = false; defines["POINTLIGHT" + index] = false; defines["DIRLIGHT" + index] = false; defines["SPOTLIGHT" + index] = false; defines["SHADOW" + index] = false; defines["SHADOWPCF" + index] = false; defines["SHADOWPCSS" + index] = false; defines["SHADOWPOISSON" + index] = false; defines["SHADOWESM" + index] = false; defines["SHADOWCUBE" + index] = false; defines["SHADOWLOWQUALITY" + index] = false; defines["SHADOWMEDIUMQUALITY" + index] = false; } } var caps = scene.getEngine().getCaps(); if (defines["SHADOWFLOAT"] === undefined) { needRebuild = true; } defines["SHADOWFLOAT"] = shadowEnabled && ((caps.textureFloatRender && caps.textureFloatLinearFiltering) || (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering)); defines["LIGHTMAPEXCLUDED"] = lightmapMode; if (needRebuild) { defines.rebuild(); } return needNormals; }; /** * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms * that won t be acctive due to defines being turned off. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information * @param samplersList The samplers list * @param defines The defines helping in the list generation * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect */ MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) { if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; } var uniformsList; var uniformBuffersList = null; if (uniformsListOrOptions.uniformsNames) { var options = uniformsListOrOptions; uniformsList = options.uniformsNames; uniformBuffersList = options.uniformBuffersNames; samplersList = options.samplers; defines = options.defines; maxSimultaneousLights = options.maxSimultaneousLights; } else { uniformsList = uniformsListOrOptions; if (!samplersList) { samplersList = []; } } for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) { if (!defines["LIGHT" + lightIndex]) { break; } uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex); if (uniformBuffersList) { uniformBuffersList.push("Light" + lightIndex); } samplersList.push("shadowSampler" + lightIndex); samplersList.push("depthSampler" + lightIndex); if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) { samplersList.push("projectionLightSampler" + lightIndex); uniformsList.push("textureProjectionMatrix" + lightIndex); } } if (defines["NUM_MORPH_INFLUENCERS"]) { uniformsList.push("morphTargetInfluences"); } }; /** * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality) * @param defines The defines to update while falling back * @param fallbacks The authorized effect fallbacks * @param maxSimultaneousLights The maximum number of lights allowed * @param rank the current rank of the Effect * @returns The newly affected rank */ MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) { if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; } if (rank === void 0) { rank = 0; } var lightFallbackRank = 0; for (var 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); } } } return lightFallbackRank++; }; /** * Prepares the list of attributes required for morph targets according to the effect defines. * @param attribs The current list of supported attribs * @param mesh The mesh to prepare the morph targets attributes for * @param defines The current Defines of the effect */ MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) { var influencers = defines["NUM_MORPH_INFLUENCERS"]; if (influencers > 0 && _Engines_engineStore__WEBPACK_IMPORTED_MODULE_3__["EngineStore"].LastCreatedEngine) { var maxAttributesCount = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_3__["EngineStore"].LastCreatedEngine.getCaps().maxVertexAttribs; var manager = mesh.morphTargetManager; var normal = manager && manager.supportsNormals && defines["NORMAL"]; var tangent = manager && manager.supportsTangents && defines["TANGENT"]; for (var index = 0; index < influencers; index++) { attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind + index); if (normal) { attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].NormalKind + index); } if (tangent) { attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].TangentKind + index); } if (attribs.length > maxAttributesCount) { _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Error("Cannot add more vertex attributes for mesh " + mesh.name); } } } }; /** * Prepares the list of attributes required for bones according to the effect defines. * @param attribs The current list of supported attribs * @param mesh The mesh to prepare the bones attributes for * @param defines The current Defines of the effect * @param fallbacks The current efffect fallback strategy */ MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) { if (defines["NUM_BONE_INFLUENCERS"] > 0) { fallbacks.addCPUSkinningFallback(0, mesh); attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].MatricesIndicesKind); attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].MatricesWeightsKind); if (defines["NUM_BONE_INFLUENCERS"] > 4) { attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].MatricesIndicesExtraKind); attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].MatricesWeightsExtraKind); } } }; /** * Prepares the list of attributes required for instances according to the effect defines. * @param attribs The current list of supported attribs * @param defines The current Defines of the effect */ MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) { if (defines["INSTANCES"]) { attribs.push("world0"); attribs.push("world1"); attribs.push("world2"); attribs.push("world3"); } }; /** * Binds the light shadow information to the effect for the given mesh. * @param light The light containing the generator * @param scene The scene the lights belongs to * @param mesh The mesh we are binding the information to render * @param lightIndex The light index in the effect used to render the mesh * @param effect The effect we are binding the data to */ MaterialHelper.BindLightShadow = function (light, mesh, lightIndex, effect) { if (light.shadowEnabled && mesh.receiveShadows) { var shadowGenerator = light.getShadowGenerator(); if (shadowGenerator) { shadowGenerator.bindShadowLight(lightIndex, effect); } } }; /** * Binds the light information to the effect. * @param light The light containing the generator * @param effect The effect we are binding the data to * @param lightIndex The light index in the effect used to render */ MaterialHelper.BindLightProperties = function (light, effect, lightIndex) { light.transferToEffect(effect, lightIndex + ""); }; /** * Binds the lights information from the scene to the effect for the given mesh. * @param scene The scene the lights belongs to * @param mesh The mesh we are binding the information to render * @param effect The effect we are binding the data to * @param defines The generated defines for the effect * @param maxSimultaneousLights The maximum number of light that can be bound to the effect * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not */ MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) { if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; } if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; } var len = Math.min(mesh._lightSources.length, maxSimultaneousLights); for (var i = 0; i < len; i++) { var light = mesh._lightSources[i]; var iAsString = i.toString(); var scaledIntensity = light.getScaledIntensity(); light._uniformBuffer.bindToEffect(effect, "Light" + i); MaterialHelper.BindLightProperties(light, effect, i); light.diffuse.scaleToRef(scaledIntensity, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Tmp"].Color3[0]); light._uniformBuffer.updateColor4("vLightDiffuse", _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Tmp"].Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString); if (defines["SPECULARTERM"]) { light.specular.scaleToRef(scaledIntensity, _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Tmp"].Color3[1]); light._uniformBuffer.updateColor3("vLightSpecular", _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Tmp"].Color3[1], iAsString); } // Shadows if (scene.shadowsEnabled) { this.BindLightShadow(light, mesh, iAsString, effect); } light._uniformBuffer.update(); } }; /** * Binds the fog information from the scene to the effect for the given mesh. * @param scene The scene the lights belongs to * @param mesh The mesh we are binding the information to render * @param effect The effect we are binding the data to * @param linearSpace Defines if the fog effect is applied in linear space */ MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) { if (linearSpace === void 0) { linearSpace = false; } if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== _scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].FOGMODE_NONE) { effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity); // Convert fog color to linear space if used in a linear space computed shader. if (linearSpace) { scene.fogColor.toLinearSpaceToRef(this._tempFogColor); effect.setColor3("vFogColor", this._tempFogColor); } else { effect.setColor3("vFogColor", scene.fogColor); } } }; /** * Binds the bones information from the mesh to the effect. * @param mesh The mesh we are binding the information to render * @param effect The effect we are binding the data to */ MaterialHelper.BindBonesParameters = function (mesh, effect) { if (!effect || !mesh) { return; } if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) { mesh.computeBonesUsingShaders = false; } if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { var skeleton = mesh.skeleton; if (skeleton.isUsingTextureForMatrices && effect.getUniformIndex("boneTextureWidth") > -1) { var boneTexture = skeleton.getTransformMatrixTexture(); effect.setTexture("boneSampler", boneTexture); effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1)); } else { var matrices = skeleton.getTransformMatrices(mesh); if (matrices) { effect.setMatrices("mBones", matrices); } } } }; /** * Binds the morph targets information from the mesh to the effect. * @param abstractMesh The mesh we are binding the information to render * @param effect The effect we are binding the data to */ MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) { var manager = abstractMesh.morphTargetManager; if (!abstractMesh || !manager) { return; } effect.setFloatArray("morphTargetInfluences", manager.influences); }; /** * Binds the logarithmic depth information from the scene to the effect for the given defines. * @param defines The generated defines used in the effect * @param effect The effect we are binding the data to * @param scene The scene we are willing to render with logarithmic scale for */ MaterialHelper.BindLogDepth = function (defines, effect, scene) { if (defines["LOGARITHMICDEPTH"]) { effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2)); } }; /** * Binds the clip plane information from the scene to the effect. * @param scene The scene the clip plane information are extracted from * @param effect The effect we are binding the data to */ MaterialHelper.BindClipPlane = function (effect, scene) { if (scene.clipPlane) { var clipPlane = scene.clipPlane; effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d); } if (scene.clipPlane2) { var clipPlane = scene.clipPlane2; effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d); } if (scene.clipPlane3) { var clipPlane = scene.clipPlane3; effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d); } if (scene.clipPlane4) { var clipPlane = scene.clipPlane4; effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d); } }; MaterialHelper._tempFogColor = _Maths_math__WEBPACK_IMPORTED_MODULE_2__["Color3"].Black(); return MaterialHelper; }()); /***/ }), /***/ "./Materials/multiMaterial.ts": /*!************************************!*\ !*** ./Materials/multiMaterial.ts ***! \************************************/ /*! exports provided: MultiMaterial */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MultiMaterial", function() { return MultiMaterial; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Materials/material */ "./Materials/material.ts"); /* harmony import */ var _Misc_tags__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/tags */ "./Misc/tags.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); /** * A multi-material is used to apply different materials to different parts of the same object without the need of * separate meshes. This can be use to improve performances. * @see http://doc.babylonjs.com/how_to/multi_materials */ var MultiMaterial = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](MultiMaterial, _super); /** * Instantiates a new Multi Material * A multi-material is used to apply different materials to different parts of the same object without the need of * separate meshes. This can be use to improve performances. * @see http://doc.babylonjs.com/how_to/multi_materials * @param name Define the name in the scene * @param scene Define the scene the material belongs to */ function MultiMaterial(name, scene) { var _this = _super.call(this, name, scene, true) || this; scene.multiMaterials.push(_this); _this.subMaterials = new Array(); _this._storeEffectOnSubMeshes = true; // multimaterial is considered like a push material return _this; } Object.defineProperty(MultiMaterial.prototype, "subMaterials", { /** * Gets or Sets the list of Materials used within the multi material. * They need to be ordered according to the submeshes order in the associated mesh */ get: function () { return this._subMaterials; }, set: function (value) { this._subMaterials = value; this._hookArray(value); }, enumerable: true, configurable: true }); /** * Function used to align with Node.getChildren() * @returns the list of Materials used within the multi material */ MultiMaterial.prototype.getChildren = function () { return this.subMaterials; }; MultiMaterial.prototype._hookArray = function (array) { var _this = this; var oldPush = array.push; array.push = function () { var items = []; for (var _i = 0; _i < arguments.length; _i++) { items[_i] = arguments[_i]; } var result = oldPush.apply(array, items); _this._markAllSubMeshesAsTexturesDirty(); return result; }; var oldSplice = array.splice; array.splice = function (index, deleteCount) { var deleted = oldSplice.apply(array, [index, deleteCount]); _this._markAllSubMeshesAsTexturesDirty(); return deleted; }; }; /** * Get one of the submaterial by its index in the submaterials array * @param index The index to look the sub material at * @returns The Material if the index has been defined */ MultiMaterial.prototype.getSubMaterial = function (index) { if (index < 0 || index >= this.subMaterials.length) { return this.getScene().defaultMaterial; } return this.subMaterials[index]; }; /** * Get the list of active textures for the whole sub materials list. * @returns All the textures that will be used during the rendering */ MultiMaterial.prototype.getActiveTextures = function () { var _a; return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { if (subMaterial) { return subMaterial.getActiveTextures(); } else { return []; } })); }; /** * Gets the current class name of the material e.g. "MultiMaterial" * Mainly use in serialization. * @returns the class name */ MultiMaterial.prototype.getClassName = function () { return "MultiMaterial"; }; /** * Checks if the material is ready to render the requested sub mesh * @param mesh Define the mesh the submesh belongs to * @param subMesh Define the sub mesh to look readyness for * @param useInstances Define whether or not the material is used with instances * @returns true if ready, otherwise false */ MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) { for (var index = 0; index < this.subMaterials.length; index++) { var subMaterial = this.subMaterials[index]; if (subMaterial) { if (subMaterial._storeEffectOnSubMeshes) { if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) { return false; } continue; } if (!subMaterial.isReady(mesh)) { return false; } } } return true; }; /** * Clones the current material and its related sub materials * @param name Define the name of the newly cloned material * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance * @returns the cloned material */ MultiMaterial.prototype.clone = function (name, cloneChildren) { var newMultiMaterial = new MultiMaterial(name, this.getScene()); for (var index = 0; index < this.subMaterials.length; index++) { var subMaterial = null; var current = this.subMaterials[index]; if (cloneChildren && current) { subMaterial = current.clone(name + "-" + current.name); } else { subMaterial = this.subMaterials[index]; } newMultiMaterial.subMaterials.push(subMaterial); } return newMultiMaterial; }; /** * Serializes the materials into a JSON representation. * @returns the JSON representation */ MultiMaterial.prototype.serialize = function () { var serializationObject = {}; serializationObject.name = this.name; serializationObject.id = this.id; if (_Misc_tags__WEBPACK_IMPORTED_MODULE_2__["Tags"]) { serializationObject.tags = _Misc_tags__WEBPACK_IMPORTED_MODULE_2__["Tags"].GetTags(this); } serializationObject.materials = []; for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) { var subMat = this.subMaterials[matIndex]; if (subMat) { serializationObject.materials.push(subMat.id); } else { serializationObject.materials.push(null); } } return serializationObject; }; /** * Dispose the material and release its associated resources * @param forceDisposeEffect Define if we want to force disposing the associated effect (if false the shader is not released and could be reuse later on) * @param forceDisposeTextures Define if we want to force disposing the associated textures (if false, they will not be disposed and can still be use elsewhere in the app) * @param forceDisposeChildren Define if we want to force disposing the associated submaterials (if false, they will not be disposed and can still be use elsewhere in the app) */ MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures, forceDisposeChildren) { var scene = this.getScene(); if (!scene) { return; } if (forceDisposeChildren) { for (var index = 0; index < this.subMaterials.length; index++) { var subMaterial = this.subMaterials[index]; if (subMaterial) { subMaterial.dispose(forceDisposeEffect, forceDisposeTextures); } } } var index = scene.multiMaterials.indexOf(this); if (index >= 0) { scene.multiMaterials.splice(index, 1); } _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures); }; /** * Creates a MultiMaterial from parsed MultiMaterial data. * @param parsedMultiMaterial defines parsed MultiMaterial data. * @param scene defines the hosting scene * @returns a new MultiMaterial */ MultiMaterial.ParseMultiMaterial = function (parsedMultiMaterial, scene) { var multiMaterial = new MultiMaterial(parsedMultiMaterial.name, scene); multiMaterial.id = parsedMultiMaterial.id; if (_Misc_tags__WEBPACK_IMPORTED_MODULE_2__["Tags"]) { _Misc_tags__WEBPACK_IMPORTED_MODULE_2__["Tags"].AddTagsTo(multiMaterial, parsedMultiMaterial.tags); } for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) { var subMatId = parsedMultiMaterial.materials[matIndex]; if (subMatId) { multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId)); } else { multiMaterial.subMaterials.push(null); } } return multiMaterial; }; return MultiMaterial; }(_Materials_material__WEBPACK_IMPORTED_MODULE_1__["Material"])); _Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__["_TypeStore"].RegisteredTypes["BABYLON.MultiMaterial"] = MultiMaterial; /***/ }), /***/ "./Materials/pushMaterial.ts": /*!***********************************!*\ !*** ./Materials/pushMaterial.ts ***! \***********************************/ /*! exports provided: PushMaterial */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PushMaterial", function() { return PushMaterial; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Materials/material */ "./Materials/material.ts"); /** * Base class of materials working in push mode in babylon JS * @hidden */ var PushMaterial = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](PushMaterial, _super); function PushMaterial(name, scene) { var _this = _super.call(this, name, scene) || this; _this._normalMatrix = new _Maths_math__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); /** * Gets or sets a boolean indicating that the material is allowed to do shader hot swapping. * This means that the material can keep using a previous shader while a new one is being compiled. * This is mostly used when shader parallel compilation is supported (true by default) */ _this.allowShaderHotSwapping = true; _this._storeEffectOnSubMeshes = true; return _this; } PushMaterial.prototype.getEffect = function () { return this._activeEffect; }; PushMaterial.prototype.isReady = function (mesh, useInstances) { if (!mesh) { return false; } if (!mesh.subMeshes || mesh.subMeshes.length === 0) { return true; } return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances); }; /** * Binds the given world matrix to the active effect * * @param world the matrix to bind */ PushMaterial.prototype.bindOnlyWorldMatrix = function (world) { this._activeEffect.setMatrix("world", world); }; /** * Binds the given normal matrix to the active effect * * @param normalMatrix the matrix to bind */ PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) { this._activeEffect.setMatrix("normalMatrix", normalMatrix); }; PushMaterial.prototype.bind = function (world, mesh) { if (!mesh) { return; } this.bindForSubMesh(world, mesh, mesh.subMeshes[0]); }; PushMaterial.prototype._afterBind = function (mesh, effect) { if (effect === void 0) { effect = null; } _super.prototype._afterBind.call(this, mesh); this.getScene()._cachedEffect = effect; }; PushMaterial.prototype._mustRebind = function (scene, effect, visibility) { if (visibility === void 0) { visibility = 1; } return scene.isCachedMaterialInvalid(this, effect, visibility); }; return PushMaterial; }(_Materials_material__WEBPACK_IMPORTED_MODULE_2__["Material"])); /***/ }), /***/ "./Materials/shaderMaterial.ts": /*!*************************************!*\ !*** ./Materials/shaderMaterial.ts ***! \*************************************/ /*! exports provided: ShaderMaterial */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderMaterial", function() { return ShaderMaterial; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts"); /* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Meshes/buffer */ "./Meshes/buffer.ts"); /* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts"); /* harmony import */ var _materialHelper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./materialHelper */ "./Materials/materialHelper.ts"); /* harmony import */ var _effect__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./effect */ "./Materials/effect.ts"); /* harmony import */ var _material__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./material */ "./Materials/material.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); /** * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh. * * This returned material effects how the mesh will look based on the code in the shaders. * * @see http://doc.babylonjs.com/how_to/shader_material */ var ShaderMaterial = /** @class */ (function (_super) { tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"](ShaderMaterial, _super); /** * Instantiate a new shader material. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh. * This returned material effects how the mesh will look based on the code in the shaders. * @see http://doc.babylonjs.com/how_to/shader_material * @param name Define the name of the material in the scene * @param scene Define the scene the material belongs to * @param shaderPath Defines the route to the shader code in one of three ways: * - object - { vertex: "custom", fragment: "custom" }, used with Effect.ShadersStore["customVertexShader"] and Effect.ShadersStore["customFragmentShader"] * - object - { vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }, used with shader code in