(function universalModuleDefinition(root, factory) { var amdDependencies = []; if(typeof exports === 'object' && typeof module === 'object') { module.exports = factory(); } else if(typeof define === 'function' && define.amd) { define("babylonjs-viewer", amdDependencies, factory); } else if(typeof exports === 'object') { exports["babylonjs-viewer"] = factory(); } else { root["BabylonViewer"] = factory(); } })(this, function() { var BabylonViewer = /******/ (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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = 15); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) { (function universalModuleDefinition(root, factory) { var amdDependencies = []; var CANNON = root.CANNON || this.CANNON; var OIMO = root.OIMO || this.OIMO; var earcut = root.earcut || this.earcut; if(true) { try { CANNON = CANNON || __webpack_require__(18); } catch(e) {} try { OIMO = OIMO || __webpack_require__(19); } catch(e) {} try { earcut = earcut || __webpack_require__(20); } catch(e) {} module.exports = factory(CANNON,OIMO,earcut); } else if(typeof define === 'function' && define.amd) { if(require.specified && require.specified("cannon")) amdDependencies.push("cannon"); if(require.specified && require.specified("oimo")) amdDependencies.push("oimo"); if(require.specified && require.specified("earcut")) amdDependencies.push("earcut"); define("babylonjs", amdDependencies, factory); } else if(typeof exports === 'object') { try { CANNON = CANNON || require("cannon"); } catch(e) {} try { OIMO = OIMO || require("oimo"); } catch(e) {} try { earcut = earcut || require("earcut"); } catch(e) {} exports["babylonjs"] = factory(CANNON,OIMO,earcut); } else { root["BABYLON"] = factory(CANNON,OIMO,earcut); } })(this, function(CANNON,OIMO,earcut) { CANNON = CANNON || this.CANNON; OIMO = OIMO || this.OIMO; earcut = earcut || this.earcut; var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n}; var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(); var BABYLON; (function (BABYLON) { /** * 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; }()); BABYLON.EffectFallbacks = EffectFallbacks; /** * Options to be used when creating an effect. */ var EffectCreationOptions = /** @class */ (function () { function EffectCreationOptions() { } return EffectCreationOptions; }()); BABYLON.EffectCreationOptions = 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. */ this.onCompileObservable = new BABYLON.Observable(); /** * Observable that will be called if an error occurs during shader compilation. */ this.onErrorObservable = new BABYLON.Observable(); /** * Observable that will be called when effect is bound. */ this.onBindObservable = new BABYLON.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; 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, "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 () { 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) { if (this.isReady()) { func(this); return; } this.onCompileObservable.add(function (effect) { func(effect); }); }; /** @hidden */ Effect.prototype._loadVertexShader = function (vertex, callback) { if (BABYLON.Tools.IsWindowObjectExist()) { // DOM element ? if (vertex instanceof HTMLElement) { var vertexCode = BABYLON.Tools.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 = BABYLON.Engine.ShadersRepository + vertex; } // Vertex shader this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback); }; /** @hidden */ Effect.prototype._loadFragmentShader = function (fragment, callback) { if (BABYLON.Tools.IsWindowObjectExist()) { // DOM element ? if (fragment instanceof HTMLElement) { var fragmentCode = BABYLON.Tools.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 = BABYLON.Engine.ShadersRepository + fragment; } // Fragment shader this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback); }; 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) { BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode); BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode); } else if (this.name.vertex) { BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode); BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode); } else { BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode); BABYLON.Tools.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_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"); if (isFragment) { result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod("); result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod("); result = result.replace(/texture2D\s*\(/g, "texture("); 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("); } 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 = BABYLON.Engine.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) { if (source.indexOf("precision highp float") === -1) { if (!this._engine.getCaps().highPrecisionShaderSupported) { source = "precision mediump float;\n" + source; } else { source = "precision highp float;\n" + source; } } else { if (!this._engine.getCaps().highPrecisionShaderSupported) { // 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. */ 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(BABYLON.Material.TextureDirtyFlag); } 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 */ Effect.prototype._prepareEffect = function () { var attributesNames = this._attributesNames; var defines = this.defines; var fallbacks = this._fallbacks; this._valueCache = {}; var previousProgram = this._program; try { var engine = this._engine; if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) { this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings); } else { this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings); } this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this); if (engine.supportsUniformBuffers) { for (var name in this._uniformBuffersNames) { this.bindUniformBlock(name, this._uniformBuffersNames[name]); } } this._uniforms = engine.getUniforms(this._program, this._uniformsNames); this._attributes = engine.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.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); } } catch (e) { this._compilationError = e.message; // Let's go through fallbacks then BABYLON.Tools.Error("Unable to compile effect:"); BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) { return " " + uniform; })); BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) { return " " + attribute; })); this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines); BABYLON.Tools.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) { BABYLON.Tools.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. */ 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; }; /** * Resets the cache of effects. */ Effect.ResetCache = function () { Effect._baseCache = {}; }; 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; }()); BABYLON.Effect = Effect; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.effect.js.map //# sourceMappingURL=babylon.types.js.map var BABYLON; (function (BABYLON) { var KeyboardEventTypes = /** @class */ (function () { function KeyboardEventTypes() { } Object.defineProperty(KeyboardEventTypes, "KEYDOWN", { get: function () { return KeyboardEventTypes._KEYDOWN; }, enumerable: true, configurable: true }); Object.defineProperty(KeyboardEventTypes, "KEYUP", { get: function () { return KeyboardEventTypes._KEYUP; }, enumerable: true, configurable: true }); KeyboardEventTypes._KEYDOWN = 0x01; KeyboardEventTypes._KEYUP = 0x02; return KeyboardEventTypes; }()); BABYLON.KeyboardEventTypes = KeyboardEventTypes; var KeyboardInfo = /** @class */ (function () { function KeyboardInfo(type, event) { this.type = type; this.event = event; } return KeyboardInfo; }()); BABYLON.KeyboardInfo = 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) { __extends(KeyboardInfoPre, _super); function KeyboardInfoPre(type, event) { var _this = _super.call(this, type, event) || this; _this.skipOnPointerObservable = false; return _this; } return KeyboardInfoPre; }(KeyboardInfo)); BABYLON.KeyboardInfoPre = KeyboardInfoPre; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.keyboardEvents.js.map var BABYLON; (function (BABYLON) { var PointerEventTypes = /** @class */ (function () { function PointerEventTypes() { } Object.defineProperty(PointerEventTypes, "POINTERDOWN", { get: function () { return PointerEventTypes._POINTERDOWN; }, enumerable: true, configurable: true }); Object.defineProperty(PointerEventTypes, "POINTERUP", { get: function () { return PointerEventTypes._POINTERUP; }, enumerable: true, configurable: true }); Object.defineProperty(PointerEventTypes, "POINTERMOVE", { get: function () { return PointerEventTypes._POINTERMOVE; }, enumerable: true, configurable: true }); Object.defineProperty(PointerEventTypes, "POINTERWHEEL", { get: function () { return PointerEventTypes._POINTERWHEEL; }, enumerable: true, configurable: true }); Object.defineProperty(PointerEventTypes, "POINTERPICK", { get: function () { return PointerEventTypes._POINTERPICK; }, enumerable: true, configurable: true }); Object.defineProperty(PointerEventTypes, "POINTERTAP", { get: function () { return PointerEventTypes._POINTERTAP; }, enumerable: true, configurable: true }); Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", { get: function () { return PointerEventTypes._POINTERDOUBLETAP; }, enumerable: true, configurable: true }); PointerEventTypes._POINTERDOWN = 0x01; PointerEventTypes._POINTERUP = 0x02; PointerEventTypes._POINTERMOVE = 0x04; PointerEventTypes._POINTERWHEEL = 0x08; PointerEventTypes._POINTERPICK = 0x10; PointerEventTypes._POINTERTAP = 0x20; PointerEventTypes._POINTERDOUBLETAP = 0x40; return PointerEventTypes; }()); BABYLON.PointerEventTypes = PointerEventTypes; var PointerInfoBase = /** @class */ (function () { function PointerInfoBase(type, event) { this.type = type; this.event = event; } return PointerInfoBase; }()); BABYLON.PointerInfoBase = 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) { __extends(PointerInfoPre, _super); 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 BABYLON.Vector2(localX, localY); return _this; } return PointerInfoPre; }(PointerInfoBase)); BABYLON.PointerInfoPre = PointerInfoPre; /** * 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) { __extends(PointerInfo, _super); function PointerInfo(type, event, pickInfo) { var _this = _super.call(this, type, event) || this; _this.pickInfo = pickInfo; return _this; } return PointerInfo; }(PointerInfoBase)); BABYLON.PointerInfo = PointerInfo; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.pointerEvents.js.map var BABYLON; (function (BABYLON) { BABYLON.ToGammaSpace = 1 / 2.2; BABYLON.ToLinearSpace = 2.2; BABYLON.Epsilon = 0.001; /** * Class used to hold a RBG color */ var Color3 = /** @class */ (function () { /** * Creates a new Color3 object from red, green, blue values, all between 0 and 1 * @param r defines the red component (between 0 and 1, default is 0) * @param g defines the green component (between 0 and 1, default is 0) * @param b defines the blue component (between 0 and 1, default is 0) */ function Color3( /** * Defines the red component (between 0 and 1, default is 0) */ r, /** * Defines the green component (between 0 and 1, default is 0) */ g, /** * Defines the blue component (between 0 and 1, default is 0) */ b) { if (r === void 0) { r = 0; } if (g === void 0) { g = 0; } if (b === void 0) { b = 0; } this.r = r; this.g = g; this.b = b; } /** * Creates a string with the Color3 current values * @returns the string representation of the Color3 object */ Color3.prototype.toString = function () { return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}"; }; /** * Returns the string "Color3" * @returns "Color3" */ Color3.prototype.getClassName = function () { return "Color3"; }; /** * Compute the Color3 hash code * @returns an unique number that can be used to hash Color3 objects */ Color3.prototype.getHashCode = function () { var hash = this.r || 0; hash = (hash * 397) ^ (this.g || 0); hash = (hash * 397) ^ (this.b || 0); return hash; }; // Operators /** * Stores in the given array from the given starting index the red, green, blue values as successive elements * @param array defines the array where to store the r,g,b components * @param index defines an optional index in the target array to define where to start storing values * @returns the current Color3 object */ Color3.prototype.toArray = function (array, index) { if (index === undefined) { index = 0; } array[index] = this.r; array[index + 1] = this.g; array[index + 2] = this.b; return this; }; /** * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1) * @returns a new {BABYLON.Color4} object */ Color3.prototype.toColor4 = function (alpha) { if (alpha === void 0) { alpha = 1; } return new Color4(this.r, this.g, this.b, alpha); }; /** * Returns a new array populated with 3 numeric elements : red, green and blue values * @returns the new array */ Color3.prototype.asArray = function () { var result = new Array(); this.toArray(result, 0); return result; }; /** * Returns the luminance value * @returns a float value */ Color3.prototype.toLuminance = function () { return this.r * 0.3 + this.g * 0.59 + this.b * 0.11; }; /** * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object * @param otherColor defines the second operand * @returns the new Color3 object */ Color3.prototype.multiply = function (otherColor) { return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b); }; /** * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result" * @param otherColor defines the second operand * @param result defines the Color3 object where to store the result * @returns the current Color3 */ Color3.prototype.multiplyToRef = function (otherColor, result) { result.r = this.r * otherColor.r; result.g = this.g * otherColor.g; result.b = this.b * otherColor.b; return this; }; /** * Determines equality between Color3 objects * @param otherColor defines the second operand * @returns true if the rgb values are equal to the given ones */ Color3.prototype.equals = function (otherColor) { return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b; }; /** * Determines equality between the current Color3 object and a set of r,b,g values * @param r defines the red component to check * @param g defines the green component to check * @param b defines the blue component to check * @returns true if the rgb values are equal to the given ones */ Color3.prototype.equalsFloats = function (r, g, b) { return this.r === r && this.g === g && this.b === b; }; /** * Multiplies in place each rgb value by scale * @param scale defines the scaling factor * @returns the updated Color3 */ Color3.prototype.scale = function (scale) { return new Color3(this.r * scale, this.g * scale, this.b * scale); }; /** * Multiplies the rgb values by scale and stores the result into "result" * @param scale defines the scaling factor * @param result defines the Color3 object where to store the result * @returns the unmodified current Color3 */ Color3.prototype.scaleToRef = function (scale, result) { result.r = this.r * scale; result.g = this.g * scale; result.b = this.b * scale; return this; }; /** * Scale the current Color3 values by a factor and add the result to a given Color3 * @param scale defines the scale factor * @param result defines color to store the result into * @returns the unmodified current Color3 */ Color3.prototype.scaleAndAddToRef = function (scale, result) { result.r += this.r * scale; result.g += this.g * scale; result.b += this.b * scale; return this; }; /** * Clamps the rgb values by the min and max values and stores the result into "result" * @param min defines minimum clamping value (default is 0) * @param max defines maximum clamping value (default is 1) * @param result defines color to store the result into * @returns the original Color3 */ Color3.prototype.clampToRef = function (min, max, result) { if (min === void 0) { min = 0; } if (max === void 0) { max = 1; } result.r = BABYLON.Scalar.Clamp(this.r, min, max); result.g = BABYLON.Scalar.Clamp(this.g, min, max); result.b = BABYLON.Scalar.Clamp(this.b, min, max); return this; }; /** * Creates a new Color3 set with the added values of the current Color3 and of the given one * @param otherColor defines the second operand * @returns the new Color3 */ Color3.prototype.add = function (otherColor) { return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b); }; /** * Stores the result of the addition of the current Color3 and given one rgb values into "result" * @param otherColor defines the second operand * @param result defines Color3 object to store the result into * @returns the unmodified current Color3 */ Color3.prototype.addToRef = function (otherColor, result) { result.r = this.r + otherColor.r; result.g = this.g + otherColor.g; result.b = this.b + otherColor.b; return this; }; /** * Returns a new Color3 set with the subtracted values of the given one from the current Color3 * @param otherColor defines the second operand * @returns the new Color3 */ Color3.prototype.subtract = function (otherColor) { return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b); }; /** * Stores the result of the subtraction of given one from the current Color3 rgb values into "result" * @param otherColor defines the second operand * @param result defines Color3 object to store the result into * @returns the unmodified current Color3 */ Color3.prototype.subtractToRef = function (otherColor, result) { result.r = this.r - otherColor.r; result.g = this.g - otherColor.g; result.b = this.b - otherColor.b; return this; }; /** * Copy the current object * @returns a new Color3 copied the current one */ Color3.prototype.clone = function () { return new Color3(this.r, this.g, this.b); }; /** * Copies the rgb values from the source in the current Color3 * @param source defines the source Color3 object * @returns the updated Color3 object */ Color3.prototype.copyFrom = function (source) { this.r = source.r; this.g = source.g; this.b = source.b; return this; }; /** * Updates the Color3 rgb values from the given floats * @param r defines the red component to read from * @param g defines the green component to read from * @param b defines the blue component to read from * @returns the current Color3 object */ Color3.prototype.copyFromFloats = function (r, g, b) { this.r = r; this.g = g; this.b = b; return this; }; /** * Updates the Color3 rgb values from the given floats * @param r defines the red component to read from * @param g defines the green component to read from * @param b defines the blue component to read from * @returns the current Color3 object */ Color3.prototype.set = function (r, g, b) { return this.copyFromFloats(r, g, b); }; /** * Compute the Color3 hexadecimal code as a string * @returns a string containing the hexadecimal representation of the Color3 object */ Color3.prototype.toHexString = function () { var intR = (this.r * 255) | 0; var intG = (this.g * 255) | 0; var intB = (this.b * 255) | 0; return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB); }; /** * Computes a new Color3 converted from the current one to linear space * @returns a new Color3 object */ Color3.prototype.toLinearSpace = function () { var convertedColor = new Color3(); this.toLinearSpaceToRef(convertedColor); return convertedColor; }; /** * Converts the Color3 values to linear space and stores the result in "convertedColor" * @param convertedColor defines the Color3 object where to store the linear space version * @returns the unmodified Color3 */ Color3.prototype.toLinearSpaceToRef = function (convertedColor) { convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace); convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace); convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace); return this; }; /** * Computes a new Color3 converted from the current one to gamma space * @returns a new Color3 object */ Color3.prototype.toGammaSpace = function () { var convertedColor = new Color3(); this.toGammaSpaceToRef(convertedColor); return convertedColor; }; /** * Converts the Color3 values to gamma space and stores the result in "convertedColor" * @param convertedColor defines the Color3 object where to store the gamma space version * @returns the unmodified Color3 */ Color3.prototype.toGammaSpaceToRef = function (convertedColor) { convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace); convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace); convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace); return this; }; // Statics /** * Creates a new Color3 from the string containing valid hexadecimal values * @param hex defines a string containing valid hexadecimal values * @returns a new Color3 object */ Color3.FromHexString = function (hex) { if (hex.substring(0, 1) !== "#" || hex.length !== 7) { return new Color3(0, 0, 0); } var r = parseInt(hex.substring(1, 3), 16); var g = parseInt(hex.substring(3, 5), 16); var b = parseInt(hex.substring(5, 7), 16); return Color3.FromInts(r, g, b); }; /** * Creates a new Vector3 from the starting index of the given array * @param array defines the source array * @param offset defines an offset in the source array * @returns a new Color3 object */ Color3.FromArray = function (array, offset) { if (offset === void 0) { offset = 0; } return new Color3(array[offset], array[offset + 1], array[offset + 2]); }; /** * Creates a new Color3 from integer values (< 256) * @param r defines the red component to read from (value between 0 and 255) * @param g defines the green component to read from (value between 0 and 255) * @param b defines the blue component to read from (value between 0 and 255) * @returns a new Color3 object */ Color3.FromInts = function (r, g, b) { return new Color3(r / 255.0, g / 255.0, b / 255.0); }; /** * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3 * @param start defines the start Color3 value * @param end defines the end Color3 value * @param amount defines the gradient value between start and end * @returns a new Color3 object */ Color3.Lerp = function (start, end, amount) { var r = start.r + ((end.r - start.r) * amount); var g = start.g + ((end.g - start.g) * amount); var b = start.b + ((end.b - start.b) * amount); return new Color3(r, g, b); }; /** * Returns a Color3 value containing a red color * @returns a new Color3 object */ Color3.Red = function () { return new Color3(1, 0, 0); }; /** * Returns a Color3 value containing a green color * @returns a new Color3 object */ Color3.Green = function () { return new Color3(0, 1, 0); }; /** * Returns a Color3 value containing a blue color * @returns a new Color3 object */ Color3.Blue = function () { return new Color3(0, 0, 1); }; /** * Returns a Color3 value containing a black color * @returns a new Color3 object */ Color3.Black = function () { return new Color3(0, 0, 0); }; /** * Returns a Color3 value containing a white color * @returns a new Color3 object */ Color3.White = function () { return new Color3(1, 1, 1); }; /** * Returns a Color3 value containing a purple color * @returns a new Color3 object */ Color3.Purple = function () { return new Color3(0.5, 0, 0.5); }; /** * Returns a Color3 value containing a magenta color * @returns a new Color3 object */ Color3.Magenta = function () { return new Color3(1, 0, 1); }; /** * Returns a Color3 value containing a yellow color * @returns a new Color3 object */ Color3.Yellow = function () { return new Color3(1, 1, 0); }; /** * Returns a Color3 value containing a gray color * @returns a new Color3 object */ Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); }; /** * Returns a Color3 value containing a teal color * @returns a new Color3 object */ Color3.Teal = function () { return new Color3(0, 1.0, 1.0); }; /** * Returns a Color3 value containing a random color * @returns a new Color3 object */ Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); }; return Color3; }()); BABYLON.Color3 = Color3; /** * Class used to hold a RBGA color */ var Color4 = /** @class */ (function () { /** * Creates a new Color4 object from red, green, blue values, all between 0 and 1 * @param r defines the red component (between 0 and 1, default is 0) * @param g defines the green component (between 0 and 1, default is 0) * @param b defines the blue component (between 0 and 1, default is 0) * @param a defines the alpha component (between 0 and 1, default is 1) */ function Color4( /** * Defines the red component (between 0 and 1, default is 0) */ r, /** * Defines the green component (between 0 and 1, default is 0) */ g, /** * Defines the blue component (between 0 and 1, default is 0) */ b, /** * Defines the alpha component (between 0 and 1, default is 1) */ a) { if (r === void 0) { r = 0; } if (g === void 0) { g = 0; } if (b === void 0) { b = 0; } if (a === void 0) { a = 1; } this.r = r; this.g = g; this.b = b; this.a = a; } // Operators /** * Adds in place the given Color4 values to the current Color4 object * @param right defines the second operand * @returns the current updated Color4 object */ Color4.prototype.addInPlace = function (right) { this.r += right.r; this.g += right.g; this.b += right.b; this.a += right.a; return this; }; /** * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values * @returns the new array */ Color4.prototype.asArray = function () { var result = new Array(); this.toArray(result, 0); return result; }; /** * Stores from the starting index in the given array the Color4 successive values * @param array defines the array where to store the r,g,b components * @param index defines an optional index in the target array to define where to start storing values * @returns the current Color4 object */ Color4.prototype.toArray = function (array, index) { if (index === undefined) { index = 0; } array[index] = this.r; array[index + 1] = this.g; array[index + 2] = this.b; array[index + 3] = this.a; return this; }; /** * Creates a new Color4 set with the added values of the current Color4 and of the given one * @param right defines the second operand * @returns a new Color4 object */ Color4.prototype.add = function (right) { return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a); }; /** * Creates a new Color4 set with the subtracted values of the given one from the current Color4 * @param right defines the second operand * @returns a new Color4 object */ Color4.prototype.subtract = function (right) { return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a); }; /** * Subtracts the given ones from the current Color4 values and stores the results in "result" * @param right defines the second operand * @param result defines the Color4 object where to store the result * @returns the current Color4 object */ Color4.prototype.subtractToRef = function (right, result) { result.r = this.r - right.r; result.g = this.g - right.g; result.b = this.b - right.b; result.a = this.a - right.a; return this; }; /** * Creates a new Color4 with the current Color4 values multiplied by scale * @param scale defines the scaling factor to apply * @returns a new Color4 object */ Color4.prototype.scale = function (scale) { return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale); }; /** * Multiplies the current Color4 values by scale and stores the result in "result" * @param scale defines the scaling factor to apply * @param result defines the Color4 object where to store the result * @returns the current unmodified Color4 */ Color4.prototype.scaleToRef = function (scale, result) { result.r = this.r * scale; result.g = this.g * scale; result.b = this.b * scale; result.a = this.a * scale; return this; }; /** * Scale the current Color4 values by a factor and add the result to a given Color4 * @param scale defines the scale factor * @param result defines the Color4 object where to store the result * @returns the unmodified current Color4 */ Color4.prototype.scaleAndAddToRef = function (scale, result) { result.r += this.r * scale; result.g += this.g * scale; result.b += this.b * scale; result.a += this.a * scale; return this; }; /** * Clamps the rgb values by the min and max values and stores the result into "result" * @param min defines minimum clamping value (default is 0) * @param max defines maximum clamping value (default is 1) * @param result defines color to store the result into. * @returns the cuurent Color4 */ Color4.prototype.clampToRef = function (min, max, result) { if (min === void 0) { min = 0; } if (max === void 0) { max = 1; } result.r = BABYLON.Scalar.Clamp(this.r, min, max); result.g = BABYLON.Scalar.Clamp(this.g, min, max); result.b = BABYLON.Scalar.Clamp(this.b, min, max); result.a = BABYLON.Scalar.Clamp(this.a, min, max); return this; }; /** * Multipy an Color4 value by another and return a new Color4 object * @param color defines the Color4 value to multiply by * @returns a new Color4 object */ Color4.prototype.multiply = function (color) { return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a); }; /** * Multipy a Color4 value by another and push the result in a reference value * @param color defines the Color4 value to multiply by * @param result defines the Color4 to fill the result in * @returns the result Color4 */ Color4.prototype.multiplyToRef = function (color, result) { result.r = this.r * color.r; result.g = this.g * color.g; result.b = this.b * color.b; result.a = this.a * color.a; return result; }; /** * Creates a string with the Color4 current values * @returns the string representation of the Color4 object */ Color4.prototype.toString = function () { return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}"; }; /** * Returns the string "Color4" * @returns "Color4" */ Color4.prototype.getClassName = function () { return "Color4"; }; /** * Compute the Color4 hash code * @returns an unique number that can be used to hash Color4 objects */ Color4.prototype.getHashCode = function () { var hash = this.r || 0; hash = (hash * 397) ^ (this.g || 0); hash = (hash * 397) ^ (this.b || 0); hash = (hash * 397) ^ (this.a || 0); return hash; }; /** * Creates a new Color4 copied from the current one * @returns a new Color4 object */ Color4.prototype.clone = function () { return new Color4(this.r, this.g, this.b, this.a); }; /** * Copies the given Color4 values into the current one * @param source defines the source Color4 object * @returns the current updated Color4 object */ Color4.prototype.copyFrom = function (source) { this.r = source.r; this.g = source.g; this.b = source.b; this.a = source.a; return this; }; /** * Copies the given float values into the current one * @param r defines the red component to read from * @param g defines the green component to read from * @param b defines the blue component to read from * @param a defines the alpha component to read from * @returns the current updated Color4 object */ Color4.prototype.copyFromFloats = function (r, g, b, a) { this.r = r; this.g = g; this.b = b; this.a = a; return this; }; /** * Copies the given float values into the current one * @param r defines the red component to read from * @param g defines the green component to read from * @param b defines the blue component to read from * @param a defines the alpha component to read from * @returns the current updated Color4 object */ Color4.prototype.set = function (r, g, b, a) { return this.copyFromFloats(r, g, b, a); }; /** * Compute the Color4 hexadecimal code as a string * @returns a string containing the hexadecimal representation of the Color4 object */ Color4.prototype.toHexString = function () { var intR = (this.r * 255) | 0; var intG = (this.g * 255) | 0; var intB = (this.b * 255) | 0; var intA = (this.a * 255) | 0; return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA); }; /** * Computes a new Color4 converted from the current one to linear space * @returns a new Color4 object */ Color4.prototype.toLinearSpace = function () { var convertedColor = new Color4(); this.toLinearSpaceToRef(convertedColor); return convertedColor; }; /** * Converts the Color4 values to linear space and stores the result in "convertedColor" * @param convertedColor defines the Color4 object where to store the linear space version * @returns the unmodified Color4 */ Color4.prototype.toLinearSpaceToRef = function (convertedColor) { convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace); convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace); convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace); convertedColor.a = this.a; return this; }; /** * Computes a new Color4 converted from the current one to gamma space * @returns a new Color4 object */ Color4.prototype.toGammaSpace = function () { var convertedColor = new Color4(); this.toGammaSpaceToRef(convertedColor); return convertedColor; }; /** * Converts the Color4 values to gamma space and stores the result in "convertedColor" * @param convertedColor defines the Color4 object where to store the gamma space version * @returns the unmodified Color4 */ Color4.prototype.toGammaSpaceToRef = function (convertedColor) { convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace); convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace); convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace); convertedColor.a = this.a; return this; }; // Statics /** * Creates a new Color4 from the string containing valid hexadecimal values * @param hex defines a string containing valid hexadecimal values * @returns a new Color4 object */ Color4.FromHexString = function (hex) { if (hex.substring(0, 1) !== "#" || hex.length !== 9) { return new Color4(0.0, 0.0, 0.0, 0.0); } var r = parseInt(hex.substring(1, 3), 16); var g = parseInt(hex.substring(3, 5), 16); var b = parseInt(hex.substring(5, 7), 16); var a = parseInt(hex.substring(7, 9), 16); return Color4.FromInts(r, g, b, a); }; /** * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object * @param left defines the start value * @param right defines the end value * @param amount defines the gradient factor * @returns a new Color4 object */ Color4.Lerp = function (left, right, amount) { var result = new Color4(0.0, 0.0, 0.0, 0.0); Color4.LerpToRef(left, right, amount, result); return result; }; /** * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object * @param left defines the start value * @param right defines the end value * @param amount defines the gradient factor * @param result defines the Color4 object where to store data */ Color4.LerpToRef = function (left, right, amount, result) { result.r = left.r + (right.r - left.r) * amount; result.g = left.g + (right.g - left.g) * amount; result.b = left.b + (right.b - left.b) * amount; result.a = left.a + (right.a - left.a) * amount; }; /** * Creates a new Color4 from the starting index element of the given array * @param array defines the source array to read from * @param offset defines the offset in the source array * @returns a new Color4 object */ Color4.FromArray = function (array, offset) { if (offset === void 0) { offset = 0; } return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]); }; /** * Creates a new Color3 from integer values (< 256) * @param r defines the red component to read from (value between 0 and 255) * @param g defines the green component to read from (value between 0 and 255) * @param b defines the blue component to read from (value between 0 and 255) * @param a defines the alpha component to read from (value between 0 and 255) * @returns a new Color3 object */ Color4.FromInts = function (r, g, b, a) { return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0); }; /** * Check the content of a given array and convert it to an array containing RGBA data * If the original array was already containing count * 4 values then it is returned directly * @param colors defines the array to check * @param count defines the number of RGBA data to expect * @returns an array containing count * 4 values (RGBA) */ Color4.CheckColors4 = function (colors, count) { // Check if color3 was used if (colors.length === count * 3) { var colors4 = []; for (var index = 0; index < colors.length; index += 3) { var newIndex = (index / 3) * 4; colors4[newIndex] = colors[index]; colors4[newIndex + 1] = colors[index + 1]; colors4[newIndex + 2] = colors[index + 2]; colors4[newIndex + 3] = 1.0; } return colors4; } return colors; }; return Color4; }()); BABYLON.Color4 = Color4; /** * Class representing a vector containing 2 coordinates */ var Vector2 = /** @class */ (function () { /** * Creates a new Vector2 from the given x and y coordinates * @param x defines the first coordinate * @param y defines the second coordinate */ function Vector2( /** defines the first coordinate */ x, /** defines the second coordinate */ y) { this.x = x; this.y = y; } /** * Gets a string with the Vector2 coordinates * @returns a string with the Vector2 coordinates */ Vector2.prototype.toString = function () { return "{X: " + this.x + " Y:" + this.y + "}"; }; /** * Gets class name * @returns the string "Vector2" */ Vector2.prototype.getClassName = function () { return "Vector2"; }; /** * Gets current vector hash code * @returns the Vector2 hash code as a number */ Vector2.prototype.getHashCode = function () { var hash = this.x || 0; hash = (hash * 397) ^ (this.y || 0); return hash; }; // Operators /** * Sets the Vector2 coordinates in the given array or Float32Array from the given index. * @param array defines the source array * @param index defines the offset in source array * @returns the current Vector2 */ Vector2.prototype.toArray = function (array, index) { if (index === void 0) { index = 0; } array[index] = this.x; array[index + 1] = this.y; return this; }; /** * Copy the current vector to an array * @returns a new array with 2 elements: the Vector2 coordinates. */ Vector2.prototype.asArray = function () { var result = new Array(); this.toArray(result, 0); return result; }; /** * Sets the Vector2 coordinates with the given Vector2 coordinates * @param source defines the source Vector2 * @returns the current updated Vector2 */ Vector2.prototype.copyFrom = function (source) { this.x = source.x; this.y = source.y; return this; }; /** * Sets the Vector2 coordinates with the given floats * @param x defines the first coordinate * @param y defines the second coordinate * @returns the current updated Vector2 */ Vector2.prototype.copyFromFloats = function (x, y) { this.x = x; this.y = y; return this; }; /** * Sets the Vector2 coordinates with the given floats * @param x defines the first coordinate * @param y defines the second coordinate * @returns the current updated Vector2 */ Vector2.prototype.set = function (x, y) { return this.copyFromFloats(x, y); }; /** * Add another vector with the current one * @param otherVector defines the other vector * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates */ Vector2.prototype.add = function (otherVector) { return new Vector2(this.x + otherVector.x, this.y + otherVector.y); }; /** * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates * @param otherVector defines the other vector * @param result defines the target vector * @returns the unmodified current Vector2 */ Vector2.prototype.addToRef = function (otherVector, result) { result.x = this.x + otherVector.x; result.y = this.y + otherVector.y; return this; }; /** * Set the Vector2 coordinates by adding the given Vector2 coordinates * @param otherVector defines the other vector * @returns the current updated Vector2 */ Vector2.prototype.addInPlace = function (otherVector) { this.x += otherVector.x; this.y += otherVector.y; return this; }; /** * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates * @param otherVector defines the other vector * @returns a new Vector2 */ Vector2.prototype.addVector3 = function (otherVector) { return new Vector2(this.x + otherVector.x, this.y + otherVector.y); }; /** * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2 * @param otherVector defines the other vector * @returns a new Vector2 */ Vector2.prototype.subtract = function (otherVector) { return new Vector2(this.x - otherVector.x, this.y - otherVector.y); }; /** * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates. * @param otherVector defines the other vector * @param result defines the target vector * @returns the unmodified current Vector2 */ Vector2.prototype.subtractToRef = function (otherVector, result) { result.x = this.x - otherVector.x; result.y = this.y - otherVector.y; return this; }; /** * Sets the current Vector2 coordinates by subtracting from it the given one coordinates * @param otherVector defines the other vector * @returns the current updated Vector2 */ Vector2.prototype.subtractInPlace = function (otherVector) { this.x -= otherVector.x; this.y -= otherVector.y; return this; }; /** * Multiplies in place the current Vector2 coordinates by the given ones * @param otherVector defines the other vector * @returns the current updated Vector2 */ Vector2.prototype.multiplyInPlace = function (otherVector) { this.x *= otherVector.x; this.y *= otherVector.y; return this; }; /** * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates * @param otherVector defines the other vector * @returns a new Vector2 */ Vector2.prototype.multiply = function (otherVector) { return new Vector2(this.x * otherVector.x, this.y * otherVector.y); }; /** * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates * @param otherVector defines the other vector * @param result defines the target vector * @returns the unmodified current Vector2 */ Vector2.prototype.multiplyToRef = function (otherVector, result) { result.x = this.x * otherVector.x; result.y = this.y * otherVector.y; return this; }; /** * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats * @param x defines the first coordinate * @param y defines the second coordinate * @returns a new Vector2 */ Vector2.prototype.multiplyByFloats = function (x, y) { return new Vector2(this.x * x, this.y * y); }; /** * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates * @param otherVector defines the other vector * @returns a new Vector2 */ Vector2.prototype.divide = function (otherVector) { return new Vector2(this.x / otherVector.x, this.y / otherVector.y); }; /** * Sets the "result" coordinates with the Vector2 divided by the given one coordinates * @param otherVector defines the other vector * @param result defines the target vector * @returns the unmodified current Vector2 */ Vector2.prototype.divideToRef = function (otherVector, result) { result.x = this.x / otherVector.x; result.y = this.y / otherVector.y; return this; }; /** * Divides the current Vector3 coordinates by the given ones * @param otherVector defines the other vector * @returns the current updated Vector2 */ Vector2.prototype.divideInPlace = function (otherVector) { return this.divideToRef(otherVector, this); }; /** * Gets a new Vector2 with current Vector2 negated coordinates * @returns a new Vector2 */ Vector2.prototype.negate = function () { return new Vector2(-this.x, -this.y); }; /** * Multiply the Vector2 coordinates by scale * @param scale defines the scaling factor * @returns the current updated Vector2 */ Vector2.prototype.scaleInPlace = function (scale) { this.x *= scale; this.y *= scale; return this; }; /** * Returns a new Vector2 scaled by "scale" from the current Vector2 * @param scale defines the scaling factor * @returns a new Vector2 */ Vector2.prototype.scale = function (scale) { var result = new Vector2(0, 0); this.scaleToRef(scale, result); return result; }; /** * Scale the current Vector2 values by a factor to a given Vector2 * @param scale defines the scale factor * @param result defines the Vector2 object where to store the result * @returns the unmodified current Vector2 */ Vector2.prototype.scaleToRef = function (scale, result) { result.x = this.x * scale; result.y = this.y * scale; return this; }; /** * Scale the current Vector2 values by a factor and add the result to a given Vector2 * @param scale defines the scale factor * @param result defines the Vector2 object where to store the result * @returns the unmodified current Vector2 */ Vector2.prototype.scaleAndAddToRef = function (scale, result) { result.x += this.x * scale; result.y += this.y * scale; return this; }; /** * Gets a boolean if two vectors are equals * @param otherVector defines the other vector * @returns true if the given vector coordinates strictly equal the current Vector2 ones */ Vector2.prototype.equals = function (otherVector) { return otherVector && this.x === otherVector.x && this.y === otherVector.y; }; /** * Gets a boolean if two vectors are equals (using an epsilon value) * @param otherVector defines the other vector * @param epsilon defines the minimal distance to consider equality * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon. */ Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) { if (epsilon === void 0) { epsilon = BABYLON.Epsilon; } return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon); }; // Properties /** * Gets the length of the vector * @returns the vector length (float) */ Vector2.prototype.length = function () { return Math.sqrt(this.x * this.x + this.y * this.y); }; /** * Gets the vector squared length * @returns the vector squared length (float) */ Vector2.prototype.lengthSquared = function () { return (this.x * this.x + this.y * this.y); }; // Methods /** * Normalize the vector * @returns the current updated Vector2 */ Vector2.prototype.normalize = function () { var len = this.length(); if (len === 0) return this; var num = 1.0 / len; this.x *= num; this.y *= num; return this; }; /** * Gets a new Vector2 copied from the Vector2 * @returns a new Vector2 */ Vector2.prototype.clone = function () { return new Vector2(this.x, this.y); }; // Statics /** * Gets a new Vector2(0, 0) * @returns a new Vector2 */ Vector2.Zero = function () { return new Vector2(0, 0); }; /** * Gets a new Vector2(1, 1) * @returns a new Vector2 */ Vector2.One = function () { return new Vector2(1, 1); }; /** * Gets a new Vector2 set from the given index element of the given array * @param array defines the data source * @param offset defines the offset in the data source * @returns a new Vector2 */ Vector2.FromArray = function (array, offset) { if (offset === void 0) { offset = 0; } return new Vector2(array[offset], array[offset + 1]); }; /** * Sets "result" from the given index element of the given array * @param array defines the data source * @param offset defines the offset in the data source * @param result defines the target vector */ Vector2.FromArrayToRef = function (array, offset, result) { result.x = array[offset]; result.y = array[offset + 1]; }; /** * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2 * @param value1 defines 1st point of control * @param value2 defines 2nd point of control * @param value3 defines 3rd point of control * @param value4 defines 4th point of control * @param amount defines the interpolation factor * @returns a new Vector2 */ Vector2.CatmullRom = function (value1, value2, value3, value4, amount) { var squared = amount * amount; var cubed = amount * squared; var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed)); var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed)); return new Vector2(x, y); }; /** * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max". * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate * @param value defines the value to clamp * @param min defines the lower limit * @param max defines the upper limit * @returns a new Vector2 */ Vector2.Clamp = function (value, min, max) { var x = value.x; x = (x > max.x) ? max.x : x; x = (x < min.x) ? min.x : x; var y = value.y; y = (y > max.y) ? max.y : y; y = (y < min.y) ? min.y : y; return new Vector2(x, y); }; /** * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2" * @param value1 defines the 1st control point * @param tangent1 defines the outgoing tangent * @param value2 defines the 2nd control point * @param tangent2 defines the incoming tangent * @param amount defines the interpolation factor * @returns a new Vector2 */ Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) { var squared = amount * amount; var cubed = amount * squared; var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0; var part2 = (-2.0 * cubed) + (3.0 * squared); var part3 = (cubed - (2.0 * squared)) + amount; var part4 = cubed - squared; var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4); var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4); return new Vector2(x, y); }; /** * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end". * @param start defines the start vector * @param end defines the end vector * @param amount defines the interpolation factor * @returns a new Vector2 */ Vector2.Lerp = function (start, end, amount) { var x = start.x + ((end.x - start.x) * amount); var y = start.y + ((end.y - start.y) * amount); return new Vector2(x, y); }; /** * Gets the dot product of the vector "left" and the vector "right" * @param left defines first vector * @param right defines second vector * @returns the dot product (float) */ Vector2.Dot = function (left, right) { return left.x * right.x + left.y * right.y; }; /** * Returns a new Vector2 equal to the normalized given vector * @param vector defines the vector to normalize * @returns a new Vector2 */ Vector2.Normalize = function (vector) { var newVector = vector.clone(); newVector.normalize(); return newVector; }; /** * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors * @param left defines 1st vector * @param right defines 2nd vector * @returns a new Vector2 */ Vector2.Minimize = function (left, right) { var x = (left.x < right.x) ? left.x : right.x; var y = (left.y < right.y) ? left.y : right.y; return new Vector2(x, y); }; /** * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors * @param left defines 1st vector * @param right defines 2nd vector * @returns a new Vector2 */ Vector2.Maximize = function (left, right) { var x = (left.x > right.x) ? left.x : right.x; var y = (left.y > right.y) ? left.y : right.y; return new Vector2(x, y); }; /** * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix * @param vector defines the vector to transform * @param transformation defines the matrix to apply * @returns a new Vector2 */ Vector2.Transform = function (vector, transformation) { var r = Vector2.Zero(); Vector2.TransformToRef(vector, transformation, r); return r; }; /** * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates * @param vector defines the vector to transform * @param transformation defines the matrix to apply * @param result defines the target vector */ Vector2.TransformToRef = function (vector, transformation, result) { var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12]; var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13]; result.x = x; result.y = y; }; /** * Determines if a given vector is included in a triangle * @param p defines the vector to test * @param p0 defines 1st triangle point * @param p1 defines 2nd triangle point * @param p2 defines 3rd triangle point * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2" */ Vector2.PointInTriangle = function (p, p0, p1, p2) { var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y); var sign = a < 0 ? -1 : 1; var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign; var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign; return s > 0 && t > 0 && (s + t) < 2 * a * sign; }; /** * Gets the distance between the vectors "value1" and "value2" * @param value1 defines first vector * @param value2 defines second vector * @returns the distance between vectors */ Vector2.Distance = function (value1, value2) { return Math.sqrt(Vector2.DistanceSquared(value1, value2)); }; /** * Returns the squared distance between the vectors "value1" and "value2" * @param value1 defines first vector * @param value2 defines second vector * @returns the squared distance between vectors */ Vector2.DistanceSquared = function (value1, value2) { var x = value1.x - value2.x; var y = value1.y - value2.y; return (x * x) + (y * y); }; /** * Gets a new Vector2 located at the center of the vectors "value1" and "value2" * @param value1 defines first vector * @param value2 defines second vector * @returns a new Vector2 */ Vector2.Center = function (value1, value2) { var center = value1.add(value2); center.scaleInPlace(0.5); return center; }; /** * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB". * @param p defines the middle point * @param segA defines one point of the segment * @param segB defines the other point of the segment * @returns the shortest distance */ Vector2.DistanceOfPointFromSegment = function (p, segA, segB) { var l2 = Vector2.DistanceSquared(segA, segB); if (l2 === 0.0) { return Vector2.Distance(p, segA); } var v = segB.subtract(segA); var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2)); var proj = segA.add(v.multiplyByFloats(t, t)); return Vector2.Distance(p, proj); }; return Vector2; }()); BABYLON.Vector2 = Vector2; /** * Classed used to store (x,y,z) vector representation * A Vector3 is the main object used in 3D geometry * It can represent etiher the coordinates of a point the space, either a direction * Reminder: Babylon.js uses a left handed forward facing system */ var Vector3 = /** @class */ (function () { /** * Creates a new Vector3 object from the given x, y, z (floats) coordinates. * @param x defines the first coordinates (on X axis) * @param y defines the second coordinates (on Y axis) * @param z defines the third coordinates (on Z axis) */ function Vector3( /** * Defines the first coordinates (on X axis) */ x, /** * Defines the second coordinates (on Y axis) */ y, /** * Defines the third coordinates (on Z axis) */ z) { this.x = x; this.y = y; this.z = z; } /** * Creates a string representation of the Vector3 * @returns a string with the Vector3 coordinates. */ Vector3.prototype.toString = function () { return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}"; }; /** * Gets the class name * @returns the string "Vector3" */ Vector3.prototype.getClassName = function () { return "Vector3"; }; /** * Creates the Vector3 hash code * @returns a number which tends to be unique between Vector3 instances */ Vector3.prototype.getHashCode = function () { var hash = this.x || 0; hash = (hash * 397) ^ (this.y || 0); hash = (hash * 397) ^ (this.z || 0); return hash; }; // Operators /** * Creates an array containing three elements : the coordinates of the Vector3 * @returns a new array of numbers */ Vector3.prototype.asArray = function () { var result = []; this.toArray(result, 0); return result; }; /** * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3 * @param array defines the destination array * @param index defines the offset in the destination array * @returns the current Vector3 */ Vector3.prototype.toArray = function (array, index) { if (index === void 0) { index = 0; } array[index] = this.x; array[index + 1] = this.y; array[index + 2] = this.z; return this; }; /** * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation) * @returns a new Quaternion object, computed from the Vector3 coordinates */ Vector3.prototype.toQuaternion = function () { return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z); }; /** * Adds the given vector to the current Vector3 * @param otherVector defines the second operand * @returns the current updated Vector3 */ Vector3.prototype.addInPlace = function (otherVector) { this.x += otherVector.x; this.y += otherVector.y; this.z += otherVector.z; return this; }; /** * Gets a new Vector3, result of the addition the current Vector3 and the given vector * @param otherVector defines the second operand * @returns the resulting Vector3 */ Vector3.prototype.add = function (otherVector) { return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z); }; /** * Adds the current Vector3 to the given one and stores the result in the vector "result" * @param otherVector defines the second operand * @param result defines the Vector3 object where to store the result * @returns the current Vector3 */ Vector3.prototype.addToRef = function (otherVector, result) { result.x = this.x + otherVector.x; result.y = this.y + otherVector.y; result.z = this.z + otherVector.z; return this; }; /** * Subtract the given vector from the current Vector3 * @param otherVector defines the second operand * @returns the current updated Vector3 */ Vector3.prototype.subtractInPlace = function (otherVector) { this.x -= otherVector.x; this.y -= otherVector.y; this.z -= otherVector.z; return this; }; /** * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3 * @param otherVector defines the second operand * @returns the resulting Vector3 */ Vector3.prototype.subtract = function (otherVector) { return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z); }; /** * Subtracts the given vector from the current Vector3 and stores the result in the vector "result". * @param otherVector defines the second operand * @param result defines the Vector3 object where to store the result * @returns the current Vector3 */ Vector3.prototype.subtractToRef = function (otherVector, result) { result.x = this.x - otherVector.x; result.y = this.y - otherVector.y; result.z = this.z - otherVector.z; return this; }; /** * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates * @param x defines the x coordinate of the operand * @param y defines the y coordinate of the operand * @param z defines the z coordinate of the operand * @returns the resulting Vector3 */ Vector3.prototype.subtractFromFloats = function (x, y, z) { return new Vector3(this.x - x, this.y - y, this.z - z); }; /** * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result * @param x defines the x coordinate of the operand * @param y defines the y coordinate of the operand * @param z defines the z coordinate of the operand * @param result defines the Vector3 object where to store the result * @returns the current Vector3 */ Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) { result.x = this.x - x; result.y = this.y - y; result.z = this.z - z; return this; }; /** * Gets a new Vector3 set with the current Vector3 negated coordinates * @returns a new Vector3 */ Vector3.prototype.negate = function () { return new Vector3(-this.x, -this.y, -this.z); }; /** * Multiplies the Vector3 coordinates by the float "scale" * @param scale defines the multiplier factor * @returns the current updated Vector3 */ Vector3.prototype.scaleInPlace = function (scale) { this.x *= scale; this.y *= scale; this.z *= scale; return this; }; /** * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale" * @param scale defines the multiplier factor * @returns a new Vector3 */ Vector3.prototype.scale = function (scale) { return new Vector3(this.x * scale, this.y * scale, this.z * scale); }; /** * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates * @param scale defines the multiplier factor * @param result defines the Vector3 object where to store the result * @returns the current Vector3 */ Vector3.prototype.scaleToRef = function (scale, result) { result.x = this.x * scale; result.y = this.y * scale; result.z = this.z * scale; return this; }; /** * Scale the current Vector3 values by a factor and add the result to a given Vector3 * @param scale defines the scale factor * @param result defines the Vector3 object where to store the result * @returns the unmodified current Vector3 */ Vector3.prototype.scaleAndAddToRef = function (scale, result) { result.x += this.x * scale; result.y += this.y * scale; result.z += this.z * scale; return this; }; /** * Returns true if the current Vector3 and the given vector coordinates are strictly equal * @param otherVector defines the second operand * @returns true if both vectors are equals */ Vector3.prototype.equals = function (otherVector) { return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z; }; /** * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon * @param otherVector defines the second operand * @param epsilon defines the minimal distance to define values as equals * @returns true if both vectors are distant less than epsilon */ Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) { if (epsilon === void 0) { epsilon = BABYLON.Epsilon; } return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon); }; /** * Returns true if the current Vector3 coordinates equals the given floats * @param x defines the x coordinate of the operand * @param y defines the y coordinate of the operand * @param z defines the z coordinate of the operand * @returns true if both vectors are equals */ Vector3.prototype.equalsToFloats = function (x, y, z) { return this.x === x && this.y === y && this.z === z; }; /** * Multiplies the current Vector3 coordinates by the given ones * @param otherVector defines the second operand * @returns the current updated Vector3 */ Vector3.prototype.multiplyInPlace = function (otherVector) { this.x *= otherVector.x; this.y *= otherVector.y; this.z *= otherVector.z; return this; }; /** * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector * @param otherVector defines the second operand * @returns the new Vector3 */ Vector3.prototype.multiply = function (otherVector) { return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z); }; /** * Multiplies the current Vector3 by the given one and stores the result in the given vector "result" * @param otherVector defines the second operand * @param result defines the Vector3 object where to store the result * @returns the current Vector3 */ Vector3.prototype.multiplyToRef = function (otherVector, result) { result.x = this.x * otherVector.x; result.y = this.y * otherVector.y; result.z = this.z * otherVector.z; return this; }; /** * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats * @param x defines the x coordinate of the operand * @param y defines the y coordinate of the operand * @param z defines the z coordinate of the operand * @returns the new Vector3 */ Vector3.prototype.multiplyByFloats = function (x, y, z) { return new Vector3(this.x * x, this.y * y, this.z * z); }; /** * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones * @param otherVector defines the second operand * @returns the new Vector3 */ Vector3.prototype.divide = function (otherVector) { return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z); }; /** * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result" * @param otherVector defines the second operand * @param result defines the Vector3 object where to store the result * @returns the current Vector3 */ Vector3.prototype.divideToRef = function (otherVector, result) { result.x = this.x / otherVector.x; result.y = this.y / otherVector.y; result.z = this.z / otherVector.z; return this; }; /** * Divides the current Vector3 coordinates by the given ones. * @param otherVector defines the second operand * @returns the current updated Vector3 */ Vector3.prototype.divideInPlace = function (otherVector) { return this.divideToRef(otherVector, this); }; /** * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones * @param other defines the second operand * @returns the current updated Vector3 */ Vector3.prototype.minimizeInPlace = function (other) { if (other.x < this.x) this.x = other.x; if (other.y < this.y) this.y = other.y; if (other.z < this.z) this.z = other.z; return this; }; /** * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones. * @param other defines the second operand * @returns the current updated Vector3 */ Vector3.prototype.maximizeInPlace = function (other) { if (other.x > this.x) this.x = other.x; if (other.y > this.y) this.y = other.y; if (other.z > this.z) this.z = other.z; return this; }; Object.defineProperty(Vector3.prototype, "isNonUniform", { /** * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same */ get: function () { var absX = Math.abs(this.x); var absY = Math.abs(this.y); if (absX !== absY) { return true; } var absZ = Math.abs(this.z); if (absX !== absZ) { return true; } if (absY !== absZ) { return true; } return false; }, enumerable: true, configurable: true }); // Properties /** * Gets the length of the Vector3 * @returns the length of the Vecto3 */ Vector3.prototype.length = function () { return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); }; /** * Gets the squared length of the Vector3 * @returns squared length of the Vector3 */ Vector3.prototype.lengthSquared = function () { return (this.x * this.x + this.y * this.y + this.z * this.z); }; /** * Normalize the current Vector3. * Please note that this is an in place operation. * @returns the current updated Vector3 */ Vector3.prototype.normalize = function () { var len = this.length(); if (len === 0 || len === 1.0) return this; var num = 1.0 / len; this.x *= num; this.y *= num; this.z *= num; return this; }; /** * Normalize the current Vector3 to a new vector * @returns the new Vector3 */ Vector3.prototype.normalizeToNew = function () { var normalized = new Vector3(0, 0, 0); this.normalizeToRef(normalized); return normalized; }; /** * Normalize the current Vector3 to the reference * @param reference define the Vector3 to update * @returns the updated Vector3 */ Vector3.prototype.normalizeToRef = function (reference) { var len = this.length(); if (len === 0 || len === 1.0) { reference.set(this.x, this.y, this.z); return reference; } var scale = 1.0 / len; this.scaleToRef(scale, reference); return reference; }; /** * Creates a new Vector3 copied from the current Vector3 * @returns the new Vector3 */ Vector3.prototype.clone = function () { return new Vector3(this.x, this.y, this.z); }; /** * Copies the given vector coordinates to the current Vector3 ones * @param source defines the source Vector3 * @returns the current updated Vector3 */ Vector3.prototype.copyFrom = function (source) { this.x = source.x; this.y = source.y; this.z = source.z; return this; }; /** * Copies the given floats to the current Vector3 coordinates * @param x defines the x coordinate of the operand * @param y defines the y coordinate of the operand * @param z defines the z coordinate of the operand * @returns the current updated Vector3 */ Vector3.prototype.copyFromFloats = function (x, y, z) { this.x = x; this.y = y; this.z = z; return this; }; /** * Copies the given floats to the current Vector3 coordinates * @param x defines the x coordinate of the operand * @param y defines the y coordinate of the operand * @param z defines the z coordinate of the operand * @returns the current updated Vector3 */ Vector3.prototype.set = function (x, y, z) { return this.copyFromFloats(x, y, z); }; // Statics /** * Get the clip factor between two vectors * @param vector0 defines the first operand * @param vector1 defines the second operand * @param axis defines the axis to use * @param size defines the size along the axis * @returns the clip factor */ Vector3.GetClipFactor = function (vector0, vector1, axis, size) { var d0 = Vector3.Dot(vector0, axis) - size; var d1 = Vector3.Dot(vector1, axis) - size; var s = d0 / (d0 - d1); return s; }; /** * Get angle between two vectors * @param vector0 angle between vector0 and vector1 * @param vector1 angle between vector0 and vector1 * @param normal direction of the normal * @return the angle between vector0 and vector1 */ Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) { var v0 = vector0.clone().normalize(); var v1 = vector1.clone().normalize(); var dot = Vector3.Dot(v0, v1); var n = Vector3.Cross(v0, v1); if (Vector3.Dot(n, normal) > 0) { return Math.acos(dot); } return -Math.acos(dot); }; /** * Returns a new Vector3 set from the index "offset" of the given array * @param array defines the source array * @param offset defines the offset in the source array * @returns the new Vector3 */ Vector3.FromArray = function (array, offset) { if (!offset) { offset = 0; } return new Vector3(array[offset], array[offset + 1], array[offset + 2]); }; /** * Returns a new Vector3 set from the index "offset" of the given Float32Array * This function is deprecated. Use FromArray instead * @param array defines the source array * @param offset defines the offset in the source array * @returns the new Vector3 */ Vector3.FromFloatArray = function (array, offset) { return Vector3.FromArray(array, offset); }; /** * Sets the given vector "result" with the element values from the index "offset" of the given array * @param array defines the source array * @param offset defines the offset in the source array * @param result defines the Vector3 where to store the result */ Vector3.FromArrayToRef = function (array, offset, result) { result.x = array[offset]; result.y = array[offset + 1]; result.z = array[offset + 2]; }; /** * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array * This function is deprecated. Use FromArrayToRef instead. * @param array defines the source array * @param offset defines the offset in the source array * @param result defines the Vector3 where to store the result */ Vector3.FromFloatArrayToRef = function (array, offset, result) { return Vector3.FromArrayToRef(array, offset, result); }; /** * Sets the given vector "result" with the given floats. * @param x defines the x coordinate of the source * @param y defines the y coordinate of the source * @param z defines the z coordinate of the source * @param result defines the Vector3 where to store the result */ Vector3.FromFloatsToRef = function (x, y, z, result) { result.x = x; result.y = y; result.z = z; }; /** * Returns a new Vector3 set to (0.0, 0.0, 0.0) * @returns a new empty Vector3 */ Vector3.Zero = function () { return new Vector3(0.0, 0.0, 0.0); }; /** * Returns a new Vector3 set to (1.0, 1.0, 1.0) * @returns a new unit Vector3 */ Vector3.One = function () { return new Vector3(1.0, 1.0, 1.0); }; /** * Returns a new Vector3 set to (0.0, 1.0, 0.0) * @returns a new up Vector3 */ Vector3.Up = function () { return new Vector3(0.0, 1.0, 0.0); }; /** * Returns a new Vector3 set to (0.0, 0.0, 1.0) * @returns a new forward Vector3 */ Vector3.Forward = function () { return new Vector3(0.0, 0.0, 1.0); }; /** * Returns a new Vector3 set to (1.0, 0.0, 0.0) * @returns a new right Vector3 */ Vector3.Right = function () { return new Vector3(1.0, 0.0, 0.0); }; /** * Returns a new Vector3 set to (-1.0, 0.0, 0.0) * @returns a new left Vector3 */ Vector3.Left = function () { return new Vector3(-1.0, 0.0, 0.0); }; /** * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account) * @param vector defines the Vector3 to transform * @param transformation defines the transformation matrix * @returns the transformed Vector3 */ Vector3.TransformCoordinates = function (vector, transformation) { var result = Vector3.Zero(); Vector3.TransformCoordinatesToRef(vector, transformation, result); return result; }; /** * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account) * @param vector defines the Vector3 to transform * @param transformation defines the transformation matrix * @param result defines the Vector3 where to store the result */ Vector3.TransformCoordinatesToRef = function (vector, transformation, result) { var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12]; var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13]; var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14]; var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15]; result.x = x / w; result.y = y / w; result.z = z / w; }; /** * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z) * This method computes tranformed coordinates only, not transformed direction vectors * @param x define the x coordinate of the source vector * @param y define the y coordinate of the source vector * @param z define the z coordinate of the source vector * @param transformation defines the transformation matrix * @param result defines the Vector3 where to store the result */ Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) { var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12]; var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13]; var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14]; var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15]; result.x = rx / rw; result.y = ry / rw; result.z = rz / rw; }; /** * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector * This methods computes transformed normalized direction vectors only (ie. it does not apply translation) * @param vector defines the Vector3 to transform * @param transformation defines the transformation matrix * @returns the new Vector3 */ Vector3.TransformNormal = function (vector, transformation) { var result = Vector3.Zero(); Vector3.TransformNormalToRef(vector, transformation, result); return result; }; /** * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector * This methods computes transformed normalized direction vectors only (ie. it does not apply translation) * @param vector defines the Vector3 to transform * @param transformation defines the transformation matrix * @param result defines the Vector3 where to store the result */ Vector3.TransformNormalToRef = function (vector, transformation, result) { var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]); var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]); var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]); result.x = x; result.y = y; result.z = z; }; /** * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z) * This methods computes transformed normalized direction vectors only (ie. it does not apply translation) * @param x define the x coordinate of the source vector * @param y define the y coordinate of the source vector * @param z define the z coordinate of the source vector * @param transformation defines the transformation matrix * @param result defines the Vector3 where to store the result */ Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) { result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]); result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]); result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]); }; /** * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4" * @param value1 defines the first control point * @param value2 defines the second control point * @param value3 defines the third control point * @param value4 defines the fourth control point * @param amount defines the amount on the spline to use * @returns the new Vector3 */ Vector3.CatmullRom = function (value1, value2, value3, value4, amount) { var squared = amount * amount; var cubed = amount * squared; var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed)); var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed)); var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed)); return new Vector3(x, y, z); }; /** * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max" * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one * @param value defines the current value * @param min defines the lower range value * @param max defines the upper range value * @returns the new Vector3 */ Vector3.Clamp = function (value, min, max) { var x = value.x; x = (x > max.x) ? max.x : x; x = (x < min.x) ? min.x : x; var y = value.y; y = (y > max.y) ? max.y : y; y = (y < min.y) ? min.y : y; var z = value.z; z = (z > max.z) ? max.z : z; z = (z < min.z) ? min.z : z; return new Vector3(x, y, z); }; /** * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2" * @param value1 defines the first control point * @param tangent1 defines the first tangent vector * @param value2 defines the second control point * @param tangent2 defines the second tangent vector * @param amount defines the amount on the interpolation spline (between 0 and 1) * @returns the new Vector3 */ Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) { var squared = amount * amount; var cubed = amount * squared; var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0; var part2 = (-2.0 * cubed) + (3.0 * squared); var part3 = (cubed - (2.0 * squared)) + amount; var part4 = cubed - squared; var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4); var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4); var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4); return new Vector3(x, y, z); }; /** * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end" * @param start defines the start value * @param end defines the end value * @param amount max defines amount between both (between 0 and 1) * @returns the new Vector3 */ Vector3.Lerp = function (start, end, amount) { var result = new Vector3(0, 0, 0); Vector3.LerpToRef(start, end, amount, result); return result; }; /** * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end" * @param start defines the start value * @param end defines the end value * @param amount max defines amount between both (between 0 and 1) * @param result defines the Vector3 where to store the result */ Vector3.LerpToRef = function (start, end, amount, result) { result.x = start.x + ((end.x - start.x) * amount); result.y = start.y + ((end.y - start.y) * amount); result.z = start.z + ((end.z - start.z) * amount); }; /** * Returns the dot product (float) between the vectors "left" and "right" * @param left defines the left operand * @param right defines the right operand * @returns the dot product */ Vector3.Dot = function (left, right) { return (left.x * right.x + left.y * right.y + left.z * right.z); }; /** * Returns a new Vector3 as the cross product of the vectors "left" and "right" * The cross product is then orthogonal to both "left" and "right" * @param left defines the left operand * @param right defines the right operand * @returns the cross product */ Vector3.Cross = function (left, right) { var result = Vector3.Zero(); Vector3.CrossToRef(left, right, result); return result; }; /** * Sets the given vector "result" with the cross product of "left" and "right" * The cross product is then orthogonal to both "left" and "right" * @param left defines the left operand * @param right defines the right operand * @param result defines the Vector3 where to store the result */ Vector3.CrossToRef = function (left, right, result) { MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y; MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z; MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x; result.copyFrom(MathTmp.Vector3[0]); }; /** * Returns a new Vector3 as the normalization of the given vector * @param vector defines the Vector3 to normalize * @returns the new Vector3 */ Vector3.Normalize = function (vector) { var result = Vector3.Zero(); Vector3.NormalizeToRef(vector, result); return result; }; /** * Sets the given vector "result" with the normalization of the given first vector * @param vector defines the Vector3 to normalize * @param result defines the Vector3 where to store the result */ Vector3.NormalizeToRef = function (vector, result) { result.copyFrom(vector); result.normalize(); }; /** * Project a Vector3 onto screen space * @param vector defines the Vector3 to project * @param world defines the world matrix to use * @param transform defines the transform (view x projection) matrix to use * @param viewport defines the screen viewport to use * @returns the new Vector3 */ Vector3.Project = function (vector, world, transform, viewport) { var cw = viewport.width; var ch = viewport.height; var cx = viewport.x; var cy = viewport.y; var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix()); Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix); var matrix = MathTmp.Matrix[0]; world.multiplyToRef(transform, matrix); matrix.multiplyToRef(viewportMatrix, matrix); return Vector3.TransformCoordinates(vector, matrix); }; /** * Unproject from screen space to object space * @param source defines the screen space Vector3 to use * @param viewportWidth defines the current width of the viewport * @param viewportHeight defines the current height of the viewport * @param world defines the world matrix to use (can be set to Identity to go to world space) * @param transform defines the transform (view x projection) matrix to use * @returns the new Vector3 */ Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) { var matrix = MathTmp.Matrix[0]; world.multiplyToRef(transform, matrix); matrix.invert(); source.x = source.x / viewportWidth * 2 - 1; source.y = -(source.y / viewportHeight * 2 - 1); var vector = Vector3.TransformCoordinates(source, matrix); var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15]; if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) { vector = vector.scale(1.0 / num); } return vector; }; /** * Unproject from screen space to object space * @param source defines the screen space Vector3 to use * @param viewportWidth defines the current width of the viewport * @param viewportHeight defines the current height of the viewport * @param world defines the world matrix to use (can be set to Identity to go to world space) * @param view defines the view matrix to use * @param projection defines the projection matrix to use * @returns the new Vector3 */ Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) { var result = Vector3.Zero(); Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result); return result; }; /** * Unproject from screen space to object space * @param source defines the screen space Vector3 to use * @param viewportWidth defines the current width of the viewport * @param viewportHeight defines the current height of the viewport * @param world defines the world matrix to use (can be set to Identity to go to world space) * @param view defines the view matrix to use * @param projection defines the projection matrix to use * @param result defines the Vector3 where to store the result */ Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) { Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result); }; /** * Unproject 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 sourceZ defines the screen space z coordinate to use * @param viewportWidth defines the current width of the viewport * @param viewportHeight defines the current height of the viewport * @param world defines the world matrix to use (can be set to Identity to go to world space) * @param view defines the view matrix to use * @param projection defines the projection matrix to use * @param result defines the Vector3 where to store the result */ Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) { var matrix = MathTmp.Matrix[0]; world.multiplyToRef(view, matrix); matrix.multiplyToRef(projection, matrix); matrix.invert(); var screenSource = MathTmp.Vector3[0]; screenSource.x = sourceX / viewportWidth * 2 - 1; screenSource.y = -(sourceY / viewportHeight * 2 - 1); screenSource.z = 2 * sourceZ - 1.0; Vector3.TransformCoordinatesToRef(screenSource, matrix, result); var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15]; if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) { result.scaleInPlace(1.0 / num); } }; /** * Gets the minimal coordinate values between two Vector3 * @param left defines the first operand * @param right defines the second operand * @returns the new Vector3 */ Vector3.Minimize = function (left, right) { var min = left.clone(); min.minimizeInPlace(right); return min; }; /** * Gets the maximal coordinate values between two Vector3 * @param left defines the first operand * @param right defines the second operand * @returns the new Vector3 */ Vector3.Maximize = function (left, right) { var max = left.clone(); max.maximizeInPlace(right); return max; }; /** * Returns the distance between the vectors "value1" and "value2" * @param value1 defines the first operand * @param value2 defines the second operand * @returns the distance */ Vector3.Distance = function (value1, value2) { return Math.sqrt(Vector3.DistanceSquared(value1, value2)); }; /** * Returns the squared distance between the vectors "value1" and "value2" * @param value1 defines the first operand * @param value2 defines the second operand * @returns the squared distance */ Vector3.DistanceSquared = function (value1, value2) { var x = value1.x - value2.x; var y = value1.y - value2.y; var z = value1.z - value2.z; return (x * x) + (y * y) + (z * z); }; /** * Returns a new Vector3 located at the center between "value1" and "value2" * @param value1 defines the first operand * @param value2 defines the second operand * @returns the new Vector3 */ Vector3.Center = function (value1, value2) { var center = value1.add(value2); center.scaleInPlace(0.5); return center; }; /** * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system), * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply * to something in order to rotate it from its local system to the given target system * Note: axis1, axis2 and axis3 are normalized during this operation * @param axis1 defines the first axis * @param axis2 defines the second axis * @param axis3 defines the third axis * @returns a new Vector3 */ Vector3.RotationFromAxis = function (axis1, axis2, axis3) { var rotation = Vector3.Zero(); Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation); return rotation; }; /** * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3 * @param axis1 defines the first axis * @param axis2 defines the second axis * @param axis3 defines the third axis * @param ref defines the Vector3 where to store the result */ Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) { var quat = MathTmp.Quaternion[0]; Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat); quat.toEulerAnglesToRef(ref); }; return Vector3; }()); BABYLON.Vector3 = Vector3; //Vector4 class created for EulerAngle class conversion to Quaternion var Vector4 = /** @class */ (function () { /** * Creates a Vector4 object from the given floats. */ function Vector4(x, y, z, w) { this.x = x; this.y = y; this.z = z; this.w = w; } /** * Returns the string with the Vector4 coordinates. */ Vector4.prototype.toString = function () { return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}"; }; /** * Returns the string "Vector4". */ Vector4.prototype.getClassName = function () { return "Vector4"; }; /** * Returns the Vector4 hash code. */ Vector4.prototype.getHashCode = function () { var hash = this.x || 0; hash = (hash * 397) ^ (this.y || 0); hash = (hash * 397) ^ (this.z || 0); hash = (hash * 397) ^ (this.w || 0); return hash; }; // Operators /** * Returns a new array populated with 4 elements : the Vector4 coordinates. */ Vector4.prototype.asArray = function () { var result = new Array(); this.toArray(result, 0); return result; }; /** * Populates the given array from the given index with the Vector4 coordinates. * Returns the Vector4. */ Vector4.prototype.toArray = function (array, index) { if (index === undefined) { index = 0; } array[index] = this.x; array[index + 1] = this.y; array[index + 2] = this.z; array[index + 3] = this.w; return this; }; /** * Adds the given vector to the current Vector4. * Returns the updated Vector4. */ Vector4.prototype.addInPlace = function (otherVector) { this.x += otherVector.x; this.y += otherVector.y; this.z += otherVector.z; this.w += otherVector.w; return this; }; /** * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one. */ Vector4.prototype.add = function (otherVector) { return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w); }; /** * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one. * Returns the current Vector4. */ Vector4.prototype.addToRef = function (otherVector, result) { result.x = this.x + otherVector.x; result.y = this.y + otherVector.y; result.z = this.z + otherVector.z; result.w = this.w + otherVector.w; return this; }; /** * Subtract in place the given vector from the current Vector4. * Returns the updated Vector4. */ Vector4.prototype.subtractInPlace = function (otherVector) { this.x -= otherVector.x; this.y -= otherVector.y; this.z -= otherVector.z; this.w -= otherVector.w; return this; }; /** * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4. */ Vector4.prototype.subtract = function (otherVector) { return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w); }; /** * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4. * Returns the current Vector4. */ Vector4.prototype.subtractToRef = function (otherVector, result) { result.x = this.x - otherVector.x; result.y = this.y - otherVector.y; result.z = this.z - otherVector.z; result.w = this.w - otherVector.w; return this; }; /** * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates. */ Vector4.prototype.subtractFromFloats = function (x, y, z, w) { return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w); }; /** * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates. * Returns the current Vector4. */ Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) { result.x = this.x - x; result.y = this.y - y; result.z = this.z - z; result.w = this.w - w; return this; }; /** * Returns a new Vector4 set with the current Vector4 negated coordinates. */ Vector4.prototype.negate = function () { return new Vector4(-this.x, -this.y, -this.z, -this.w); }; /** * Multiplies the current Vector4 coordinates by scale (float). * Returns the updated Vector4. */ Vector4.prototype.scaleInPlace = function (scale) { this.x *= scale; this.y *= scale; this.z *= scale; this.w *= scale; return this; }; /** * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float). */ Vector4.prototype.scale = function (scale) { return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale); }; /** * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float). * Returns the current Vector4. */ Vector4.prototype.scaleToRef = function (scale, result) { result.x = this.x * scale; result.y = this.y * scale; result.z = this.z * scale; result.w = this.w * scale; return this; }; /** * Scale the current Vector4 values by a factor and add the result to a given Vector4 * @param scale defines the scale factor * @param result defines the Vector4 object where to store the result * @returns the unmodified current Vector4 */ Vector4.prototype.scaleAndAddToRef = function (scale, result) { result.x += this.x * scale; result.y += this.y * scale; result.z += this.z * scale; result.w += this.w * scale; return this; }; /** * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones. */ Vector4.prototype.equals = function (otherVector) { return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w; }; /** * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones. */ Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) { if (epsilon === void 0) { epsilon = BABYLON.Epsilon; } return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon) && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon); }; /** * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates. */ Vector4.prototype.equalsToFloats = function (x, y, z, w) { return this.x === x && this.y === y && this.z === z && this.w === w; }; /** * Multiplies in place the current Vector4 by the given one. * Returns the updated Vector4. */ Vector4.prototype.multiplyInPlace = function (otherVector) { this.x *= otherVector.x; this.y *= otherVector.y; this.z *= otherVector.z; this.w *= otherVector.w; return this; }; /** * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one. */ Vector4.prototype.multiply = function (otherVector) { return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w); }; /** * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one. * Returns the current Vector4. */ Vector4.prototype.multiplyToRef = function (otherVector, result) { result.x = this.x * otherVector.x; result.y = this.y * otherVector.y; result.z = this.z * otherVector.z; result.w = this.w * otherVector.w; return this; }; /** * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates. */ Vector4.prototype.multiplyByFloats = function (x, y, z, w) { return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w); }; /** * Returns a new Vector4 set with the division result of the current Vector4 by the given one. */ Vector4.prototype.divide = function (otherVector) { return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w); }; /** * Updates the given vector "result" with the division result of the current Vector4 by the given one. * Returns the current Vector4. */ Vector4.prototype.divideToRef = function (otherVector, result) { result.x = this.x / otherVector.x; result.y = this.y / otherVector.y; result.z = this.z / otherVector.z; result.w = this.w / otherVector.w; return this; }; /** * Divides the current Vector3 coordinates by the given ones. * @returns the updated Vector3. */ Vector4.prototype.divideInPlace = function (otherVector) { return this.divideToRef(otherVector, this); }; /** * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones * @param other defines the second operand * @returns the current updated Vector4 */ Vector4.prototype.minimizeInPlace = function (other) { if (other.x < this.x) this.x = other.x; if (other.y < this.y) this.y = other.y; if (other.z < this.z) this.z = other.z; if (other.w < this.w) this.w = other.w; return this; }; /** * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones * @param other defines the second operand * @returns the current updated Vector4 */ Vector4.prototype.maximizeInPlace = function (other) { if (other.x > this.x) this.x = other.x; if (other.y > this.y) this.y = other.y; if (other.z > this.z) this.z = other.z; if (other.w > this.w) this.w = other.w; return this; }; // Properties /** * Returns the Vector4 length (float). */ Vector4.prototype.length = function () { return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); }; /** * Returns the Vector4 squared length (float). */ Vector4.prototype.lengthSquared = function () { return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); }; // Methods /** * Normalizes in place the Vector4. * Returns the updated Vector4. */ Vector4.prototype.normalize = function () { var len = this.length(); if (len === 0) return this; var num = 1.0 / len; this.x *= num; this.y *= num; this.z *= num; this.w *= num; return this; }; /** * Returns a new Vector3 from the Vector4 (x, y, z) coordinates. */ Vector4.prototype.toVector3 = function () { return new Vector3(this.x, this.y, this.z); }; /** * Returns a new Vector4 copied from the current one. */ Vector4.prototype.clone = function () { return new Vector4(this.x, this.y, this.z, this.w); }; /** * Updates the current Vector4 with the given one coordinates. * Returns the updated Vector4. */ Vector4.prototype.copyFrom = function (source) { this.x = source.x; this.y = source.y; this.z = source.z; this.w = source.w; return this; }; /** * Updates the current Vector4 coordinates with the given floats. * Returns the updated Vector4. */ Vector4.prototype.copyFromFloats = function (x, y, z, w) { this.x = x; this.y = y; this.z = z; this.w = w; return this; }; /** * Updates the current Vector4 coordinates with the given floats. * Returns the updated Vector4. */ Vector4.prototype.set = function (x, y, z, w) { return this.copyFromFloats(x, y, z, w); }; // Statics /** * Returns a new Vector4 set from the starting index of the given array. */ Vector4.FromArray = function (array, offset) { if (!offset) { offset = 0; } return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]); }; /** * Updates the given vector "result" from the starting index of the given array. */ Vector4.FromArrayToRef = function (array, offset, result) { result.x = array[offset]; result.y = array[offset + 1]; result.z = array[offset + 2]; result.w = array[offset + 3]; }; /** * Updates the given vector "result" from the starting index of the given Float32Array. */ Vector4.FromFloatArrayToRef = function (array, offset, result) { Vector4.FromArrayToRef(array, offset, result); }; /** * Updates the given vector "result" coordinates from the given floats. */ Vector4.FromFloatsToRef = function (x, y, z, w, result) { result.x = x; result.y = y; result.z = z; result.w = w; }; /** * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0) */ Vector4.Zero = function () { return new Vector4(0.0, 0.0, 0.0, 0.0); }; /** * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0) */ Vector4.One = function () { return new Vector4(1.0, 1.0, 1.0, 1.0); }; /** * Returns a new normalized Vector4 from the given one. */ Vector4.Normalize = function (vector) { var result = Vector4.Zero(); Vector4.NormalizeToRef(vector, result); return result; }; /** * Updates the given vector "result" from the normalization of the given one. */ Vector4.NormalizeToRef = function (vector, result) { result.copyFrom(vector); result.normalize(); }; Vector4.Minimize = function (left, right) { var min = left.clone(); min.minimizeInPlace(right); return min; }; Vector4.Maximize = function (left, right) { var max = left.clone(); max.maximizeInPlace(right); return max; }; /** * Returns the distance (float) between the vectors "value1" and "value2". */ Vector4.Distance = function (value1, value2) { return Math.sqrt(Vector4.DistanceSquared(value1, value2)); }; /** * Returns the squared distance (float) between the vectors "value1" and "value2". */ Vector4.DistanceSquared = function (value1, value2) { var x = value1.x - value2.x; var y = value1.y - value2.y; var z = value1.z - value2.z; var w = value1.w - value2.w; return (x * x) + (y * y) + (z * z) + (w * w); }; /** * Returns a new Vector4 located at the center between the vectors "value1" and "value2". */ Vector4.Center = function (value1, value2) { var center = value1.add(value2); center.scaleInPlace(0.5); return center; }; /** * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector. * This methods computes transformed normalized direction vectors only. */ Vector4.TransformNormal = function (vector, transformation) { var result = Vector4.Zero(); Vector4.TransformNormalToRef(vector, transformation, result); return result; }; /** * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector. * This methods computes transformed normalized direction vectors only. */ Vector4.TransformNormalToRef = function (vector, transformation, result) { var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]); var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]); var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]); result.x = x; result.y = y; result.z = z; result.w = vector.w; }; /** * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w). * This methods computes transformed normalized direction vectors only. */ Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) { result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]); result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]); result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]); result.w = w; }; return Vector4; }()); BABYLON.Vector4 = Vector4; var Size = /** @class */ (function () { /** * Creates a Size object from the given width and height (floats). */ function Size(width, height) { this.width = width; this.height = height; } // Returns a string with the Size width and height. Size.prototype.toString = function () { return "{W: " + this.width + ", H: " + this.height + "}"; }; /** * Returns the string "Size" */ Size.prototype.getClassName = function () { return "Size"; }; /** * Returns the Size hash code. */ Size.prototype.getHashCode = function () { var hash = this.width || 0; hash = (hash * 397) ^ (this.height || 0); return hash; }; /** * Updates the current size from the given one. * Returns the updated Size. */ Size.prototype.copyFrom = function (src) { this.width = src.width; this.height = src.height; }; /** * Updates in place the current Size from the given floats. * Returns the updated Size. */ Size.prototype.copyFromFloats = function (width, height) { this.width = width; this.height = height; return this; }; /** * Updates in place the current Size from the given floats. * Returns the updated Size. */ Size.prototype.set = function (width, height) { return this.copyFromFloats(width, height); }; /** * Returns a new Size set with the multiplication result of the current Size and the given floats. */ Size.prototype.multiplyByFloats = function (w, h) { return new Size(this.width * w, this.height * h); }; /** * Returns a new Size copied from the given one. */ Size.prototype.clone = function () { return new Size(this.width, this.height); }; /** * Boolean : True if the current Size and the given one width and height are strictly equal. */ Size.prototype.equals = function (other) { if (!other) { return false; } return (this.width === other.width) && (this.height === other.height); }; Object.defineProperty(Size.prototype, "surface", { /** * Returns the surface of the Size : width * height (float). */ get: function () { return this.width * this.height; }, enumerable: true, configurable: true }); /** * Returns a new Size set to (0.0, 0.0) */ Size.Zero = function () { return new Size(0.0, 0.0); }; /** * Returns a new Size set as the addition result of the current Size and the given one. */ Size.prototype.add = function (otherSize) { var r = new Size(this.width + otherSize.width, this.height + otherSize.height); return r; }; /** * Returns a new Size set as the subtraction result of the given one from the current Size. */ Size.prototype.subtract = function (otherSize) { var r = new Size(this.width - otherSize.width, this.height - otherSize.height); return r; }; /** * Returns a new Size set at the linear interpolation "amount" between "start" and "end". */ Size.Lerp = function (start, end, amount) { var w = start.width + ((end.width - start.width) * amount); var h = start.height + ((end.height - start.height) * amount); return new Size(w, h); }; return Size; }()); BABYLON.Size = Size; /** * Class used to store quaternion data * @see https://en.wikipedia.org/wiki/Quaternion * @see http://doc.babylonjs.com/features/position,_rotation,_scaling */ var Quaternion = /** @class */ (function () { /** * Creates a new Quaternion from the given floats * @param x defines the first component (0 by default) * @param y defines the second component (0 by default) * @param z defines the third component (0 by default) * @param w defines the fourth component (1.0 by default) */ function Quaternion( /** defines the first component (0 by default) */ x, /** defines the second component (0 by default) */ y, /** defines the third component (0 by default) */ z, /** defines the fourth component (1.0 by default) */ w) { if (x === void 0) { x = 0.0; } if (y === void 0) { y = 0.0; } if (z === void 0) { z = 0.0; } if (w === void 0) { w = 1.0; } this.x = x; this.y = y; this.z = z; this.w = w; } /** * Gets a string representation for the current quaternion * @returns a string with the Quaternion coordinates */ Quaternion.prototype.toString = function () { return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}"; }; /** * Gets the class name of the quaternion * @returns the string "Quaternion" */ Quaternion.prototype.getClassName = function () { return "Quaternion"; }; /** * Gets a hash code for this quaternion * @returns the quaternion hash code */ Quaternion.prototype.getHashCode = function () { var hash = this.x || 0; hash = (hash * 397) ^ (this.y || 0); hash = (hash * 397) ^ (this.z || 0); hash = (hash * 397) ^ (this.w || 0); return hash; }; /** * Copy the quaternion to an array * @returns a new array populated with 4 elements from the quaternion coordinates */ Quaternion.prototype.asArray = function () { return [this.x, this.y, this.z, this.w]; }; /** * Check if two quaternions are equals * @param otherQuaternion defines the second operand * @return true if the current quaternion and the given one coordinates are strictly equals */ Quaternion.prototype.equals = function (otherQuaternion) { return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w; }; /** * Clone the current quaternion * @returns a new quaternion copied from the current one */ Quaternion.prototype.clone = function () { return new Quaternion(this.x, this.y, this.z, this.w); }; /** * Copy a quaternion to the current one * @param other defines the other quaternion * @returns the updated current quaternion */ Quaternion.prototype.copyFrom = function (other) { this.x = other.x; this.y = other.y; this.z = other.z; this.w = other.w; return this; }; /** * Updates the current quaternion with the given float coordinates * @param x defines the x coordinate * @param y defines the y coordinate * @param z defines the z coordinate * @param w defines the w coordinate * @returns the updated current quaternion */ Quaternion.prototype.copyFromFloats = function (x, y, z, w) { this.x = x; this.y = y; this.z = z; this.w = w; return this; }; /** * Updates the current quaternion from the given float coordinates * @param x defines the x coordinate * @param y defines the y coordinate * @param z defines the z coordinate * @param w defines the w coordinate * @returns the updated current quaternion */ Quaternion.prototype.set = function (x, y, z, w) { return this.copyFromFloats(x, y, z, w); }; /** * Adds two quaternions * @param other defines the second operand * @returns a new quaternion as the addition result of the given one and the current quaternion */ Quaternion.prototype.add = function (other) { return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w); }; /** * Add a quaternion to the current one * @param other defines the quaternion to add * @returns the current quaternion */ Quaternion.prototype.addInPlace = function (other) { this.x += other.x; this.y += other.y; this.z += other.z; this.w += other.w; return this; }; /** * Subtract two quaternions * @param other defines the second operand * @returns a new quaternion as the subtraction result of the given one from the current one */ Quaternion.prototype.subtract = function (other) { return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w); }; /** * Multiplies the current quaternion by a scale factor * @param value defines the scale factor * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale" */ Quaternion.prototype.scale = function (value) { return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value); }; /** * Scale the current quaternion values by a factor and stores the result to a given quaternion * @param scale defines the scale factor * @param result defines the Quaternion object where to store the result * @returns the unmodified current quaternion */ Quaternion.prototype.scaleToRef = function (scale, result) { result.x = this.x * scale; result.y = this.y * scale; result.z = this.z * scale; result.w = this.w * scale; return this; }; /** * Multiplies in place the current quaternion by a scale factor * @param value defines the scale factor * @returns the current modified quaternion */ Quaternion.prototype.scaleInPlace = function (value) { this.x *= value; this.y *= value; this.z *= value; this.w *= value; return this; }; /** * Scale the current quaternion values by a factor and add the result to a given quaternion * @param scale defines the scale factor * @param result defines the Quaternion object where to store the result * @returns the unmodified current quaternion */ Quaternion.prototype.scaleAndAddToRef = function (scale, result) { result.x += this.x * scale; result.y += this.y * scale; result.z += this.z * scale; result.w += this.w * scale; return this; }; /** * Multiplies two quaternions * @param q1 defines the second operand * @returns a new quaternion set as the multiplication result of the current one with the given one "q1" */ Quaternion.prototype.multiply = function (q1) { var result = new Quaternion(0, 0, 0, 1.0); this.multiplyToRef(q1, result); return result; }; /** * Sets the given "result" as the the multiplication result of the current one with the given one "q1" * @param q1 defines the second operand * @param result defines the target quaternion * @returns the current quaternion */ Quaternion.prototype.multiplyToRef = function (q1, result) { var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x; var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y; var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z; var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w; result.copyFromFloats(x, y, z, w); return this; }; /** * Updates the current quaternion with the multiplication of itself with the given one "q1" * @param q1 defines the second operand * @returns the currentupdated quaternion */ Quaternion.prototype.multiplyInPlace = function (q1) { this.multiplyToRef(q1, this); return this; }; /** * Conjugates (1-q) the current quaternion and stores the result in the given quaternion * @param ref defines the target quaternion * @returns the current quaternion */ Quaternion.prototype.conjugateToRef = function (ref) { ref.copyFromFloats(-this.x, -this.y, -this.z, this.w); return this; }; /** * Conjugates in place (1-q) the current quaternion * @returns the current updated quaternion */ Quaternion.prototype.conjugateInPlace = function () { this.x *= -1; this.y *= -1; this.z *= -1; return this; }; /** * Conjugates in place (1-q) the current quaternion * @returns a new quaternion */ Quaternion.prototype.conjugate = function () { var result = new Quaternion(-this.x, -this.y, -this.z, this.w); return result; }; /** * Gets length of current quaternion * @returns the quaternion length (float) */ Quaternion.prototype.length = function () { return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w)); }; /** * Normalize in place the current quaternion * @returns the current updated quaternion */ Quaternion.prototype.normalize = function () { var length = 1.0 / this.length(); this.x *= length; this.y *= length; this.z *= length; this.w *= length; return this; }; /** * Returns a new Vector3 set with the Euler angles translated from the current quaternion * @param order is a reserved parameter and is ignore for now * @returns a new Vector3 containing the Euler angles */ Quaternion.prototype.toEulerAngles = function (order) { if (order === void 0) { order = "YZX"; } var result = Vector3.Zero(); this.toEulerAnglesToRef(result, order); return result; }; /** * Sets the given vector3 "result" with the Euler angles translated from the current quaternion * @param result defines the vector which will be filled with the Euler angles * @param order is a reserved parameter and is ignore for now * @returns the current unchanged quaternion */ Quaternion.prototype.toEulerAnglesToRef = function (result, order) { if (order === void 0) { order = "YZX"; } var qz = this.z; var qx = this.x; var qy = this.y; var qw = this.w; var sqw = qw * qw; var sqz = qz * qz; var sqx = qx * qx; var sqy = qy * qy; var zAxisY = qy * qz - qx * qw; var limit = .4999999; if (zAxisY < -limit) { result.y = 2 * Math.atan2(qy, qw); result.x = Math.PI / 2; result.z = 0; } else if (zAxisY > limit) { result.y = 2 * Math.atan2(qy, qw); result.x = -Math.PI / 2; result.z = 0; } else { result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw)); result.x = Math.asin(-2.0 * (qz * qy - qx * qw)); result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw)); } return this; }; /** * Updates the given rotation matrix with the current quaternion values * @param result defines the target matrix * @returns the current unchanged quaternion */ Quaternion.prototype.toRotationMatrix = function (result) { var xx = this.x * this.x; var yy = this.y * this.y; var zz = this.z * this.z; var xy = this.x * this.y; var zw = this.z * this.w; var zx = this.z * this.x; var yw = this.y * this.w; var yz = this.y * this.z; var xw = this.x * this.w; result.m[0] = 1.0 - (2.0 * (yy + zz)); result.m[1] = 2.0 * (xy + zw); result.m[2] = 2.0 * (zx - yw); result.m[3] = 0; result.m[4] = 2.0 * (xy - zw); result.m[5] = 1.0 - (2.0 * (zz + xx)); result.m[6] = 2.0 * (yz + xw); result.m[7] = 0; result.m[8] = 2.0 * (zx + yw); result.m[9] = 2.0 * (yz - xw); result.m[10] = 1.0 - (2.0 * (yy + xx)); result.m[11] = 0; result.m[12] = 0; result.m[13] = 0; result.m[14] = 0; result.m[15] = 1.0; result._markAsUpdated(); return this; }; /** * Updates the current quaternion from the given rotation matrix values * @param matrix defines the source matrix * @returns the current updated quaternion */ Quaternion.prototype.fromRotationMatrix = function (matrix) { Quaternion.FromRotationMatrixToRef(matrix, this); return this; }; // Statics /** * Creates a new quaternion from a rotation matrix * @param matrix defines the source matrix * @returns a new quaternion created from the given rotation matrix values */ Quaternion.FromRotationMatrix = function (matrix) { var result = new Quaternion(); Quaternion.FromRotationMatrixToRef(matrix, result); return result; }; /** * Updates the given quaternion with the given rotation matrix values * @param matrix defines the source matrix * @param result defines the target quaternion */ Quaternion.FromRotationMatrixToRef = function (matrix, result) { var data = matrix.m; var m11 = data[0], m12 = data[4], m13 = data[8]; var m21 = data[1], m22 = data[5], m23 = data[9]; var m31 = data[2], m32 = data[6], m33 = data[10]; var trace = m11 + m22 + m33; var s; if (trace > 0) { s = 0.5 / Math.sqrt(trace + 1.0); result.w = 0.25 / s; result.x = (m32 - m23) * s; result.y = (m13 - m31) * s; result.z = (m21 - m12) * s; } else if (m11 > m22 && m11 > m33) { s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33); result.w = (m32 - m23) / s; result.x = 0.25 * s; result.y = (m12 + m21) / s; result.z = (m13 + m31) / s; } else if (m22 > m33) { s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33); result.w = (m13 - m31) / s; result.x = (m12 + m21) / s; result.y = 0.25 * s; result.z = (m23 + m32) / s; } else { s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22); result.w = (m21 - m12) / s; result.x = (m13 + m31) / s; result.y = (m23 + m32) / s; result.z = 0.25 * s; } }; /** * Returns the dot product (float) between the quaternions "left" and "right" * @param left defines the left operand * @param right defines the right operand * @returns the dot product */ Quaternion.Dot = function (left, right) { return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w); }; /** * Checks if the two quaternions are close to each other * @param quat0 defines the first quaternion to check * @param quat1 defines the second quaternion to check * @returns true if the two quaternions are close to each other */ Quaternion.AreClose = function (quat0, quat1) { var dot = Quaternion.Dot(quat0, quat1); return dot >= 0; }; /** * Creates an empty quaternion * @returns a new quaternion set to (0.0, 0.0, 0.0) */ Quaternion.Zero = function () { return new Quaternion(0.0, 0.0, 0.0, 0.0); }; /** * Inverse a given quaternion * @param q defines the source quaternion * @returns a new quaternion as the inverted current quaternion */ Quaternion.Inverse = function (q) { return new Quaternion(-q.x, -q.y, -q.z, q.w); }; /** * Creates an identity quaternion * @returns the identity quaternion */ Quaternion.Identity = function () { return new Quaternion(0.0, 0.0, 0.0, 1.0); }; /** * Gets a boolean indicating if the given quaternion is identity * @param quaternion defines the quaternion to check * @returns true if the quaternion is identity */ Quaternion.IsIdentity = function (quaternion) { return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1; }; /** * Creates a quaternion from a rotation around an axis * @param axis defines the axis to use * @param angle defines the angle to use * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float) */ Quaternion.RotationAxis = function (axis, angle) { return Quaternion.RotationAxisToRef(axis, angle, new Quaternion()); }; /** * Creates a rotation around an axis and stores it into the given quaternion * @param axis defines the axis to use * @param angle defines the angle to use * @param result defines the target quaternion * @returns the target quaternion */ Quaternion.RotationAxisToRef = function (axis, angle, result) { var sin = Math.sin(angle / 2); axis.normalize(); result.w = Math.cos(angle / 2); result.x = axis.x * sin; result.y = axis.y * sin; result.z = axis.z * sin; return result; }; /** * Creates a new quaternion from data stored into an array * @param array defines the data source * @param offset defines the offset in the source array where the data starts * @returns a new quaternion */ Quaternion.FromArray = function (array, offset) { if (!offset) { offset = 0; } return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]); }; /** * Creates a new quaternion from the given Euler float angles (y, x, z) * @param yaw defines the rotation around Y axis * @param pitch defines the rotation around X axis * @param roll defines the rotation around Z axis * @returns the new quaternion */ Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) { var q = new Quaternion(); Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q); return q; }; /** * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion * @param yaw defines the rotation around Y axis * @param pitch defines the rotation around X axis * @param roll defines the rotation around Z axis * @param result defines the target quaternion */ Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) { // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles) var halfRoll = roll * 0.5; var halfPitch = pitch * 0.5; var halfYaw = yaw * 0.5; var sinRoll = Math.sin(halfRoll); var cosRoll = Math.cos(halfRoll); var sinPitch = Math.sin(halfPitch); var cosPitch = Math.cos(halfPitch); var sinYaw = Math.sin(halfYaw); var cosYaw = Math.cos(halfYaw); result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll); result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll); result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll); result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll); }; /** * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation * @param alpha defines the rotation around first axis * @param beta defines the rotation around second axis * @param gamma defines the rotation around third axis * @returns the new quaternion */ Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) { var result = new Quaternion(); Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result); return result; }; /** * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion * @param alpha defines the rotation around first axis * @param beta defines the rotation around second axis * @param gamma defines the rotation around third axis * @param result defines the target quaternion */ Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) { // Produces a quaternion from Euler angles in the z-x-z orientation var halfGammaPlusAlpha = (gamma + alpha) * 0.5; var halfGammaMinusAlpha = (gamma - alpha) * 0.5; var halfBeta = beta * 0.5; result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta); result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta); result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta); result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta); }; /** * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) * @param axis1 defines the first axis * @param axis2 defines the second axis * @param axis3 defines the third axis * @returns the new quaternion */ Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) { var quat = new Quaternion(0.0, 0.0, 0.0, 0.0); Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat); return quat; }; /** * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion * @param axis1 defines the first axis * @param axis2 defines the second axis * @param axis3 defines the third axis * @param ref defines the target quaternion */ Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) { var rotMat = MathTmp.Matrix[0]; Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat); Quaternion.FromRotationMatrixToRef(rotMat, ref); }; /** * Interpolates between two quaternions * @param left defines first quaternion * @param right defines second quaternion * @param amount defines the gradient to use * @returns the new interpolated quaternion */ Quaternion.Slerp = function (left, right, amount) { var result = Quaternion.Identity(); Quaternion.SlerpToRef(left, right, amount, result); return result; }; /** * Interpolates between two quaternions and stores it into a target quaternion * @param left defines first quaternion * @param right defines second quaternion * @param amount defines the gradient to use * @param result defines the target quaternion */ Quaternion.SlerpToRef = function (left, right, amount, result) { var num2; var num3; var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w); var flag = false; if (num4 < 0) { flag = true; num4 = -num4; } if (num4 > 0.999999) { num3 = 1 - amount; num2 = flag ? -amount : amount; } else { var num5 = Math.acos(num4); var num6 = (1.0 / Math.sin(num5)); num3 = (Math.sin((1.0 - amount) * num5)) * num6; num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6); } result.x = (num3 * left.x) + (num2 * right.x); result.y = (num3 * left.y) + (num2 * right.y); result.z = (num3 * left.z) + (num2 * right.z); result.w = (num3 * left.w) + (num2 * right.w); }; /** * Interpolate between two quaternions using Hermite interpolation * @param value1 defines first quaternion * @param tangent1 defines the incoming tangent * @param value2 defines second quaternion * @param tangent2 defines the outgoing tangent * @param amount defines the target quaternion * @returns the new interpolated quaternion */ Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) { var squared = amount * amount; var cubed = amount * squared; var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0; var part2 = (-2.0 * cubed) + (3.0 * squared); var part3 = (cubed - (2.0 * squared)) + amount; var part4 = cubed - squared; var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4); var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4); var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4); var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4); return new Quaternion(x, y, z, w); }; return Quaternion; }()); BABYLON.Quaternion = Quaternion; /** * Class used to store matrix data (4x4) */ var Matrix = /** @class */ (function () { /** * Creates an empty matrix (filled with zeros) */ function Matrix() { this._isIdentity = false; this._isIdentityDirty = true; /** * Gets or sets the internal data of the matrix */ this.m = new Float32Array(16); this._markAsUpdated(); } /** @hidden */ Matrix.prototype._markAsUpdated = function () { this.updateFlag = Matrix._updateFlagSeed++; this._isIdentityDirty = true; }; // Properties /** * Check if the current matrix is indentity * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2) * @returns true is the matrix is the identity matrix */ Matrix.prototype.isIdentity = function (considerAsTextureMatrix) { if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; } if (this._isIdentityDirty) { this._isIdentityDirty = false; if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) { this._isIdentity = false; } else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 || this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 || this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 || this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) { this._isIdentity = false; } else { this._isIdentity = true; } if (!considerAsTextureMatrix && this.m[10] !== 1.0) { this._isIdentity = false; } } return this._isIdentity; }; /** * Gets the determinant of the matrix * @returns the matrix determinant */ Matrix.prototype.determinant = function () { var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]); var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]); var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]); var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]); var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]); var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]); return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6)))); }; // Methods /** * Returns the matrix as a Float32Array * @returns the matrix underlying array */ Matrix.prototype.toArray = function () { return this.m; }; /** * Returns the matrix as a Float32Array * @returns the matrix underlying array. */ Matrix.prototype.asArray = function () { return this.toArray(); }; /** * Inverts the current matrix in place * @returns the current inverted matrix */ Matrix.prototype.invert = function () { this.invertToRef(this); return this; }; /** * Sets all the matrix elements to zero * @returns the current matrix */ Matrix.prototype.reset = function () { for (var index = 0; index < 16; index++) { this.m[index] = 0.0; } this._markAsUpdated(); return this; }; /** * Adds the current matrix with a second one * @param other defines the matrix to add * @returns a new matrix as the addition of the current matrix and the given one */ Matrix.prototype.add = function (other) { var result = new Matrix(); this.addToRef(other, result); return result; }; /** * Sets the given matrix "result" to the addition of the current matrix and the given one * @param other defines the matrix to add * @param result defines the target matrix * @returns the current matrix */ Matrix.prototype.addToRef = function (other, result) { for (var index = 0; index < 16; index++) { result.m[index] = this.m[index] + other.m[index]; } result._markAsUpdated(); return this; }; /** * Adds in place the given matrix to the current matrix * @param other defines the second operand * @returns the current updated matrix */ Matrix.prototype.addToSelf = function (other) { for (var index = 0; index < 16; index++) { this.m[index] += other.m[index]; } this._markAsUpdated(); return this; }; /** * Sets the given matrix to the current inverted Matrix * @param other defines the target matrix * @returns the unmodified current matrix */ Matrix.prototype.invertToRef = function (other) { var l1 = this.m[0]; var l2 = this.m[1]; var l3 = this.m[2]; var l4 = this.m[3]; var l5 = this.m[4]; var l6 = this.m[5]; var l7 = this.m[6]; var l8 = this.m[7]; var l9 = this.m[8]; var l10 = this.m[9]; var l11 = this.m[10]; var l12 = this.m[11]; var l13 = this.m[12]; var l14 = this.m[13]; var l15 = this.m[14]; var l16 = this.m[15]; var l17 = (l11 * l16) - (l12 * l15); var l18 = (l10 * l16) - (l12 * l14); var l19 = (l10 * l15) - (l11 * l14); var l20 = (l9 * l16) - (l12 * l13); var l21 = (l9 * l15) - (l11 * l13); var l22 = (l9 * l14) - (l10 * l13); var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19); var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21)); var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22); var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22)); var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26)); var l28 = (l7 * l16) - (l8 * l15); var l29 = (l6 * l16) - (l8 * l14); var l30 = (l6 * l15) - (l7 * l14); var l31 = (l5 * l16) - (l8 * l13); var l32 = (l5 * l15) - (l7 * l13); var l33 = (l5 * l14) - (l6 * l13); var l34 = (l7 * l12) - (l8 * l11); var l35 = (l6 * l12) - (l8 * l10); var l36 = (l6 * l11) - (l7 * l10); var l37 = (l5 * l12) - (l8 * l9); var l38 = (l5 * l11) - (l7 * l9); var l39 = (l5 * l10) - (l6 * l9); other.m[0] = l23 * l27; other.m[4] = l24 * l27; other.m[8] = l25 * l27; other.m[12] = l26 * l27; other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27; other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27; other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27; other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27; other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27; other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27; other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27; other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27; other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27; other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27; other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27; other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27; other._markAsUpdated(); return this; }; /** * Inserts the translation vector (using 3 floats) in the current matrix * @param x defines the 1st component of the translation * @param y defines the 2nd component of the translation * @param z defines the 3rd component of the translation * @returns the current updated matrix */ Matrix.prototype.setTranslationFromFloats = function (x, y, z) { this.m[12] = x; this.m[13] = y; this.m[14] = z; this._markAsUpdated(); return this; }; /** * Inserts the translation vector in the current matrix * @param vector3 defines the translation to insert * @returns the current updated matrix */ Matrix.prototype.setTranslation = function (vector3) { this.m[12] = vector3.x; this.m[13] = vector3.y; this.m[14] = vector3.z; this._markAsUpdated(); return this; }; /** * Gets the translation value of the current matrix * @returns a new Vector3 as the extracted translation from the matrix */ Matrix.prototype.getTranslation = function () { return new Vector3(this.m[12], this.m[13], this.m[14]); }; /** * Fill a Vector3 with the extracted translation from the matrix * @param result defines the Vector3 where to store the translation * @returns the current matrix */ Matrix.prototype.getTranslationToRef = function (result) { result.x = this.m[12]; result.y = this.m[13]; result.z = this.m[14]; return this; }; /** * Remove rotation and scaling part from the matrix * @returns the updated matrix */ Matrix.prototype.removeRotationAndScaling = function () { this.setRowFromFloats(0, 1, 0, 0, 0); this.setRowFromFloats(1, 0, 1, 0, 0); this.setRowFromFloats(2, 0, 0, 1, 0); return this; }; /** * Multiply two matrices * @param other defines the second operand * @returns a new matrix set with the multiplication result of the current Matrix and the given one */ Matrix.prototype.multiply = function (other) { var result = new Matrix(); this.multiplyToRef(other, result); return result; }; /** * Copy the current matrix from the given one * @param other defines the source matrix * @returns the current updated matrix */ Matrix.prototype.copyFrom = function (other) { for (var index = 0; index < 16; index++) { this.m[index] = other.m[index]; } this._markAsUpdated(); return this; }; /** * Populates the given array from the starting index with the current matrix values * @param array defines the target array * @param offset defines the offset in the target array where to start storing values * @returns the current matrix */ Matrix.prototype.copyToArray = function (array, offset) { if (offset === void 0) { offset = 0; } for (var index = 0; index < 16; index++) { array[offset + index] = this.m[index]; } return this; }; /** * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one * @param other defines the second operand * @param result defines the matrix where to store the multiplication * @returns the current matrix */ Matrix.prototype.multiplyToRef = function (other, result) { this.multiplyToArray(other, result.m, 0); result._markAsUpdated(); return this; }; /** * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one * @param other defines the second operand * @param result defines the array where to store the multiplication * @param offset defines the offset in the target array where to start storing values * @returns the current matrix */ Matrix.prototype.multiplyToArray = function (other, result, offset) { var tm0 = this.m[0]; var tm1 = this.m[1]; var tm2 = this.m[2]; var tm3 = this.m[3]; var tm4 = this.m[4]; var tm5 = this.m[5]; var tm6 = this.m[6]; var tm7 = this.m[7]; var tm8 = this.m[8]; var tm9 = this.m[9]; var tm10 = this.m[10]; var tm11 = this.m[11]; var tm12 = this.m[12]; var tm13 = this.m[13]; var tm14 = this.m[14]; var tm15 = this.m[15]; var om0 = other.m[0]; var om1 = other.m[1]; var om2 = other.m[2]; var om3 = other.m[3]; var om4 = other.m[4]; var om5 = other.m[5]; var om6 = other.m[6]; var om7 = other.m[7]; var om8 = other.m[8]; var om9 = other.m[9]; var om10 = other.m[10]; var om11 = other.m[11]; var om12 = other.m[12]; var om13 = other.m[13]; var om14 = other.m[14]; var om15 = other.m[15]; result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12; result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13; result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14; result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15; result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12; result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13; result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14; result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15; result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12; result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13; result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14; result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15; result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12; result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13; result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14; result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15; return this; }; /** * Check equality between this matrix and a second one * @param value defines the second matrix to compare * @returns true is the current matrix and the given one values are strictly equal */ Matrix.prototype.equals = function (value) { return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]); }; /** * Clone the current matrix * @returns a new matrix from the current matrix */ Matrix.prototype.clone = function () { return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]); }; /** * Returns the name of the current matrix class * @returns the string "Matrix" */ Matrix.prototype.getClassName = function () { return "Matrix"; }; /** * Gets the hash code of the current matrix * @returns the hash code */ Matrix.prototype.getHashCode = function () { var hash = this.m[0] || 0; for (var i = 1; i < 16; i++) { hash = (hash * 397) ^ (this.m[i] || 0); } return hash; }; /** * Decomposes the current Matrix into a translation, rotation and scaling components * @param scale defines the scale vector3 given as a reference to update * @param rotation defines the rotation quaternion given as a reference to update * @param translation defines the translation vector3 given as a reference to update * @returns true if operation was successful */ Matrix.prototype.decompose = function (scale, rotation, translation) { if (translation) { translation.x = this.m[12]; translation.y = this.m[13]; translation.z = this.m[14]; } scale = scale || MathTmp.Vector3[0]; scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]); scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]); scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]); if (this.determinant() <= 0) { scale.y *= -1; } if (scale.x === 0 || scale.y === 0 || scale.z === 0) { if (rotation) { rotation.x = 0; rotation.y = 0; rotation.z = 0; rotation.w = 1; } return false; } if (rotation) { Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]); Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation); } return true; }; /** * Gets specific row of the matrix * @param index defines the number of the row to get * @returns the index-th row of the current matrix as a new Vector4 */ Matrix.prototype.getRow = function (index) { if (index < 0 || index > 3) { return null; } var i = index * 4; return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]); }; /** * Sets the index-th row of the current matrix to the vector4 values * @param index defines the number of the row to set * @param row defines the target vector4 * @returns the updated current matrix */ Matrix.prototype.setRow = function (index, row) { if (index < 0 || index > 3) { return this; } var i = index * 4; this.m[i + 0] = row.x; this.m[i + 1] = row.y; this.m[i + 2] = row.z; this.m[i + 3] = row.w; this._markAsUpdated(); return this; }; /** * Compute the transpose of the matrix * @returns the new transposed matrix */ Matrix.prototype.transpose = function () { return Matrix.Transpose(this); }; /** * Compute the transpose of the matrix and store it in a given matrix * @param result defines the target matrix * @returns the current matrix */ Matrix.prototype.transposeToRef = function (result) { Matrix.TransposeToRef(this, result); return this; }; /** * Sets the index-th row of the current matrix with the given 4 x float values * @param index defines the row index * @param x defines the x component to set * @param y defines the y component to set * @param z defines the z component to set * @param w defines the w component to set * @returns the updated current matrix */ Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) { if (index < 0 || index > 3) { return this; } var i = index * 4; this.m[i + 0] = x; this.m[i + 1] = y; this.m[i + 2] = z; this.m[i + 3] = w; this._markAsUpdated(); return this; }; /** * Compute a new matrix set with the current matrix values multiplied by scale (float) * @param scale defines the scale factor * @returns a new matrix */ Matrix.prototype.scale = function (scale) { var result = new Matrix(); this.scaleToRef(scale, result); return result; }; /** * Scale the current matrix values by a factor to a given result matrix * @param scale defines the scale factor * @param result defines the matrix to store the result * @returns the current matrix */ Matrix.prototype.scaleToRef = function (scale, result) { for (var index = 0; index < 16; index++) { result.m[index] = this.m[index] * scale; } result._markAsUpdated(); return this; }; /** * Scale the current matrix values by a factor and add the result to a given matrix * @param scale defines the scale factor * @param result defines the Matrix to store the result * @returns the current matrix */ Matrix.prototype.scaleAndAddToRef = function (scale, result) { for (var index = 0; index < 16; index++) { result.m[index] += this.m[index] * scale; } result._markAsUpdated(); return this; }; /** * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column). * @param ref matrix to store the result */ Matrix.prototype.toNormalMatrix = function (ref) { this.invertToRef(ref); ref.transpose(); var m = ref.m; Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref); }; /** * Gets only rotation part of the current matrix * @returns a new matrix sets to the extracted rotation matrix from the current one */ Matrix.prototype.getRotationMatrix = function () { var result = Matrix.Identity(); this.getRotationMatrixToRef(result); return result; }; /** * Extracts the rotation matrix from the current one and sets it as the given "result" * @param result defines the target matrix to store data to * @returns the current matrix */ Matrix.prototype.getRotationMatrixToRef = function (result) { var m = this.m; var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]); var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]); var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]); if (this.determinant() <= 0) { sy *= -1; } if (sx === 0 || sy === 0 || sz === 0) { Matrix.IdentityToRef(result); } else { Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result); } return this; }; // Statics /** * Creates a matrix from an array * @param array defines the source array * @param offset defines an offset in the source array * @returns a new Matrix set from the starting index of the given array */ Matrix.FromArray = function (array, offset) { var result = new Matrix(); if (!offset) { offset = 0; } Matrix.FromArrayToRef(array, offset, result); return result; }; /** * Copy the content of an array into a given matrix * @param array defines the source array * @param offset defines an offset in the source array * @param result defines the target matrix */ Matrix.FromArrayToRef = function (array, offset, result) { for (var index = 0; index < 16; index++) { result.m[index] = array[index + offset]; } result._markAsUpdated(); }; /** * Stores an array into a matrix after having multiplied each component by a given factor * @param array defines the source array * @param offset defines the offset in the source array * @param scale defines the scaling factor * @param result defines the target matrix */ Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) { for (var index = 0; index < 16; index++) { result.m[index] = array[index + offset] * scale; } result._markAsUpdated(); }; /** * Stores a list of values (16) inside a given matrix * @param initialM11 defines 1st value of 1st row * @param initialM12 defines 2nd value of 1st row * @param initialM13 defines 3rd value of 1st row * @param initialM14 defines 4th value of 1st row * @param initialM21 defines 1st value of 2nd row * @param initialM22 defines 2nd value of 2nd row * @param initialM23 defines 3rd value of 2nd row * @param initialM24 defines 4th value of 2nd row * @param initialM31 defines 1st value of 3rd row * @param initialM32 defines 2nd value of 3rd row * @param initialM33 defines 3rd value of 3rd row * @param initialM34 defines 4th value of 3rd row * @param initialM41 defines 1st value of 4th row * @param initialM42 defines 2nd value of 4th row * @param initialM43 defines 3rd value of 4th row * @param initialM44 defines 4th value of 4th row * @param result defines the target matrix */ Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) { result.m[0] = initialM11; result.m[1] = initialM12; result.m[2] = initialM13; result.m[3] = initialM14; result.m[4] = initialM21; result.m[5] = initialM22; result.m[6] = initialM23; result.m[7] = initialM24; result.m[8] = initialM31; result.m[9] = initialM32; result.m[10] = initialM33; result.m[11] = initialM34; result.m[12] = initialM41; result.m[13] = initialM42; result.m[14] = initialM43; result.m[15] = initialM44; result._markAsUpdated(); }; Object.defineProperty(Matrix, "IdentityReadOnly", { /** * Gets an identity matrix that must not be updated */ get: function () { return Matrix._identityReadOnly; }, enumerable: true, configurable: true }); /** * Creates new matrix from a list of values (16) * @param initialM11 defines 1st value of 1st row * @param initialM12 defines 2nd value of 1st row * @param initialM13 defines 3rd value of 1st row * @param initialM14 defines 4th value of 1st row * @param initialM21 defines 1st value of 2nd row * @param initialM22 defines 2nd value of 2nd row * @param initialM23 defines 3rd value of 2nd row * @param initialM24 defines 4th value of 2nd row * @param initialM31 defines 1st value of 3rd row * @param initialM32 defines 2nd value of 3rd row * @param initialM33 defines 3rd value of 3rd row * @param initialM34 defines 4th value of 3rd row * @param initialM41 defines 1st value of 4th row * @param initialM42 defines 2nd value of 4th row * @param initialM43 defines 3rd value of 4th row * @param initialM44 defines 4th value of 4th row * @returns the new matrix */ Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) { var result = new Matrix(); result.m[0] = initialM11; result.m[1] = initialM12; result.m[2] = initialM13; result.m[3] = initialM14; result.m[4] = initialM21; result.m[5] = initialM22; result.m[6] = initialM23; result.m[7] = initialM24; result.m[8] = initialM31; result.m[9] = initialM32; result.m[10] = initialM33; result.m[11] = initialM34; result.m[12] = initialM41; result.m[13] = initialM42; result.m[14] = initialM43; result.m[15] = initialM44; return result; }; /** * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3) * @param scale defines the scale vector3 * @param rotation defines the rotation quaternion * @param translation defines the translation vector3 * @returns a new matrix */ Matrix.Compose = function (scale, rotation, translation) { var result = Matrix.Identity(); Matrix.ComposeToRef(scale, rotation, translation, result); return result; }; /** * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3) * @param scale defines the scale vector3 * @param rotation defines the rotation quaternion * @param translation defines the translation vector3 * @param result defines the target matrix */ Matrix.ComposeToRef = function (scale, rotation, translation, result) { Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]); rotation.toRotationMatrix(MathTmp.Matrix[0]); MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result); result.setTranslation(translation); }; /** * Creates a new identity matrix * @returns a new identity matrix */ Matrix.Identity = function () { return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); }; /** * Creates a new identity matrix and stores the result in a given matrix * @param result defines the target matrix */ Matrix.IdentityToRef = function (result) { Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result); }; /** * Creates a new zero matrix * @returns a new zero matrix */ Matrix.Zero = function () { return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0); }; /** * Creates a new rotation matrix for "angle" radians around the X axis * @param angle defines the angle (in radians) to use * @return the new matrix */ Matrix.RotationX = function (angle) { var result = new Matrix(); Matrix.RotationXToRef(angle, result); return result; }; /** * Creates a new matrix as the invert of a given matrix * @param source defines the source matrix * @returns the new matrix */ Matrix.Invert = function (source) { var result = new Matrix(); source.invertToRef(result); return result; }; /** * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix * @param angle defines the angle (in radians) to use * @param result defines the target matrix */ Matrix.RotationXToRef = function (angle, result) { var s = Math.sin(angle); var c = Math.cos(angle); result.m[0] = 1.0; result.m[15] = 1.0; result.m[5] = c; result.m[10] = c; result.m[9] = -s; result.m[6] = s; result.m[1] = 0.0; result.m[2] = 0.0; result.m[3] = 0.0; result.m[4] = 0.0; result.m[7] = 0.0; result.m[8] = 0.0; result.m[11] = 0.0; result.m[12] = 0.0; result.m[13] = 0.0; result.m[14] = 0.0; result._markAsUpdated(); }; /** * Creates a new rotation matrix for "angle" radians around the Y axis * @param angle defines the angle (in radians) to use * @return the new matrix */ Matrix.RotationY = function (angle) { var result = new Matrix(); Matrix.RotationYToRef(angle, result); return result; }; /** * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix * @param angle defines the angle (in radians) to use * @param result defines the target matrix */ Matrix.RotationYToRef = function (angle, result) { var s = Math.sin(angle); var c = Math.cos(angle); result.m[5] = 1.0; result.m[15] = 1.0; result.m[0] = c; result.m[2] = -s; result.m[8] = s; result.m[10] = c; result.m[1] = 0.0; result.m[3] = 0.0; result.m[4] = 0.0; result.m[6] = 0.0; result.m[7] = 0.0; result.m[9] = 0.0; result.m[11] = 0.0; result.m[12] = 0.0; result.m[13] = 0.0; result.m[14] = 0.0; result._markAsUpdated(); }; /** * Creates a new rotation matrix for "angle" radians around the Z axis * @param angle defines the angle (in radians) to use * @return the new matrix */ Matrix.RotationZ = function (angle) { var result = new Matrix(); Matrix.RotationZToRef(angle, result); return result; }; /** * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix * @param angle defines the angle (in radians) to use * @param result defines the target matrix */ Matrix.RotationZToRef = function (angle, result) { var s = Math.sin(angle); var c = Math.cos(angle); result.m[10] = 1.0; result.m[15] = 1.0; result.m[0] = c; result.m[1] = s; result.m[4] = -s; result.m[5] = c; result.m[2] = 0.0; result.m[3] = 0.0; result.m[6] = 0.0; result.m[7] = 0.0; result.m[8] = 0.0; result.m[9] = 0.0; result.m[11] = 0.0; result.m[12] = 0.0; result.m[13] = 0.0; result.m[14] = 0.0; result._markAsUpdated(); }; /** * Creates a new rotation matrix for "angle" radians around the given axis * @param axis defines the axis to use * @param angle defines the angle (in radians) to use * @return the new matrix */ Matrix.RotationAxis = function (axis, angle) { var result = Matrix.Zero(); Matrix.RotationAxisToRef(axis, angle, result); return result; }; /** * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix * @param axis defines the axis to use * @param angle defines the angle (in radians) to use * @param result defines the target matrix */ Matrix.RotationAxisToRef = function (axis, angle, result) { var s = Math.sin(-angle); var c = Math.cos(-angle); var c1 = 1 - c; axis.normalize(); result.m[0] = (axis.x * axis.x) * c1 + c; result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s); result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s); result.m[3] = 0.0; result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s); result.m[5] = (axis.y * axis.y) * c1 + c; result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s); result.m[7] = 0.0; result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s); result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s); result.m[10] = (axis.z * axis.z) * c1 + c; result.m[11] = 0.0; result.m[15] = 1.0; result._markAsUpdated(); }; /** * Creates a rotation matrix * @param yaw defines the yaw angle in radians (Y axis) * @param pitch defines the pitch angle in radians (X axis) * @param roll defines the roll angle in radians (X axis) * @returns the new rotation matrix */ Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) { var result = new Matrix(); Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result); return result; }; /** * Creates a rotation matrix and stores it in a given matrix * @param yaw defines the yaw angle in radians (Y axis) * @param pitch defines the pitch angle in radians (X axis) * @param roll defines the roll angle in radians (X axis) * @param result defines the target matrix */ Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) { Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion); this._tempQuaternion.toRotationMatrix(result); }; /** * Creates a scaling matrix * @param x defines the scale factor on X axis * @param y defines the scale factor on Y axis * @param z defines the scale factor on Z axis * @returns the new matrix */ Matrix.Scaling = function (x, y, z) { var result = Matrix.Zero(); Matrix.ScalingToRef(x, y, z, result); return result; }; /** * Creates a scaling matrix and stores it in a given matrix * @param x defines the scale factor on X axis * @param y defines the scale factor on Y axis * @param z defines the scale factor on Z axis * @param result defines the target matrix */ Matrix.ScalingToRef = function (x, y, z, result) { result.m[0] = x; result.m[1] = 0.0; result.m[2] = 0.0; result.m[3] = 0.0; result.m[4] = 0.0; result.m[5] = y; result.m[6] = 0.0; result.m[7] = 0.0; result.m[8] = 0.0; result.m[9] = 0.0; result.m[10] = z; result.m[11] = 0.0; result.m[12] = 0.0; result.m[13] = 0.0; result.m[14] = 0.0; result.m[15] = 1.0; result._markAsUpdated(); }; /** * Creates a translation matrix * @param x defines the translation on X axis * @param y defines the translation on Y axis * @param z defines the translationon Z axis * @returns the new matrix */ Matrix.Translation = function (x, y, z) { var result = Matrix.Identity(); Matrix.TranslationToRef(x, y, z, result); return result; }; /** * Creates a translation matrix and stores it in a given matrix * @param x defines the translation on X axis * @param y defines the translation on Y axis * @param z defines the translationon Z axis * @param result defines the target matrix */ Matrix.TranslationToRef = function (x, y, z, result) { Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result); }; /** * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue". * @param startValue defines the start value * @param endValue defines the end value * @param gradient defines the gradient factor * @returns the new matrix */ Matrix.Lerp = function (startValue, endValue, gradient) { var result = Matrix.Zero(); Matrix.LerpToRef(startValue, endValue, gradient, result); return result; }; /** * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue". * @param startValue defines the start value * @param endValue defines the end value * @param gradient defines the gradient factor * @param result defines the Matrix object where to store data */ Matrix.LerpToRef = function (startValue, endValue, gradient, result) { for (var index = 0; index < 16; index++) { result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient; } result._markAsUpdated(); }; /** * Builds a new matrix whose values are computed by: * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices * @param startValue defines the first matrix * @param endValue defines the second matrix * @param gradient defines the gradient between the two matrices * @returns the new matrix */ Matrix.DecomposeLerp = function (startValue, endValue, gradient) { var result = Matrix.Zero(); Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result); return result; }; /** * Update a matrix to values which are computed by: * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices * @param startValue defines the first matrix * @param endValue defines the second matrix * @param gradient defines the gradient between the two matrices * @param result defines the target matrix */ Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) { var startScale = MathTmp.Vector3[0]; var startRotation = MathTmp.Quaternion[0]; var startTranslation = MathTmp.Vector3[1]; startValue.decompose(startScale, startRotation, startTranslation); var endScale = MathTmp.Vector3[2]; var endRotation = MathTmp.Quaternion[1]; var endTranslation = MathTmp.Vector3[3]; endValue.decompose(endScale, endRotation, endTranslation); var resultScale = MathTmp.Vector3[4]; Vector3.LerpToRef(startScale, endScale, gradient, resultScale); var resultRotation = MathTmp.Quaternion[2]; Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation); var resultTranslation = MathTmp.Vector3[5]; Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation); Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result); }; /** * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up" * This function works in left handed mode * @param eye defines the final position of the entity * @param target defines where the entity should look at * @param up defines the up vector for the entity * @returns the new matrix */ Matrix.LookAtLH = function (eye, target, up) { var result = Matrix.Zero(); Matrix.LookAtLHToRef(eye, target, up, result); return result; }; /** * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up". * This function works in left handed mode * @param eye defines the final position of the entity * @param target defines where the entity should look at * @param up defines the up vector for the entity * @param result defines the target matrix */ Matrix.LookAtLHToRef = function (eye, target, up, result) { // Z axis target.subtractToRef(eye, this._zAxis); this._zAxis.normalize(); // X axis Vector3.CrossToRef(up, this._zAxis, this._xAxis); if (this._xAxis.lengthSquared() === 0) { this._xAxis.x = 1.0; } else { this._xAxis.normalize(); } // Y axis Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis); this._yAxis.normalize(); // Eye angles var ex = -Vector3.Dot(this._xAxis, eye); var ey = -Vector3.Dot(this._yAxis, eye); var ez = -Vector3.Dot(this._zAxis, eye); return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result); }; /** * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up" * This function works in right handed mode * @param eye defines the final position of the entity * @param target defines where the entity should look at * @param up defines the up vector for the entity * @returns the new matrix */ Matrix.LookAtRH = function (eye, target, up) { var result = Matrix.Zero(); Matrix.LookAtRHToRef(eye, target, up, result); return result; }; /** * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up". * This function works in right handed mode * @param eye defines the final position of the entity * @param target defines where the entity should look at * @param up defines the up vector for the entity * @param result defines the target matrix */ Matrix.LookAtRHToRef = function (eye, target, up, result) { // Z axis eye.subtractToRef(target, this._zAxis); this._zAxis.normalize(); // X axis Vector3.CrossToRef(up, this._zAxis, this._xAxis); if (this._xAxis.lengthSquared() === 0) { this._xAxis.x = 1.0; } else { this._xAxis.normalize(); } // Y axis Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis); this._yAxis.normalize(); // Eye angles var ex = -Vector3.Dot(this._xAxis, eye); var ey = -Vector3.Dot(this._yAxis, eye); var ez = -Vector3.Dot(this._zAxis, eye); return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result); }; /** * Create a left-handed orthographic projection matrix * @param width defines the viewport width * @param height defines the viewport height * @param znear defines the near clip plane * @param zfar defines the far clip plane * @returns a new matrix as a left-handed orthographic projection matrix */ Matrix.OrthoLH = function (width, height, znear, zfar) { var matrix = Matrix.Zero(); Matrix.OrthoLHToRef(width, height, znear, zfar, matrix); return matrix; }; /** * Store a left-handed orthographic projection to a given matrix * @param width defines the viewport width * @param height defines the viewport height * @param znear defines the near clip plane * @param zfar defines the far clip plane * @param result defines the target matrix */ Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) { var n = znear; var f = zfar; var a = 2.0 / width; var b = 2.0 / height; var c = 2.0 / (f - n); var d = -(f + n) / (f - n); Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result); }; /** * Create a left-handed orthographic projection matrix * @param left defines the viewport left coordinate * @param right defines the viewport right coordinate * @param bottom defines the viewport bottom coordinate * @param top defines the viewport top coordinate * @param znear defines the near clip plane * @param zfar defines the far clip plane * @returns a new matrix as a left-handed orthographic projection matrix */ Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) { var matrix = Matrix.Zero(); Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix); return matrix; }; /** * Stores a left-handed orthographic projection into a given matrix * @param left defines the viewport left coordinate * @param right defines the viewport right coordinate * @param bottom defines the viewport bottom coordinate * @param top defines the viewport top coordinate * @param znear defines the near clip plane * @param zfar defines the far clip plane * @param result defines the target matrix */ Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) { var n = znear; var f = zfar; var a = 2.0 / (right - left); var b = 2.0 / (top - bottom); var c = 2.0 / (f - n); var d = -(f + n) / (f - n); var i0 = (left + right) / (left - right); var i1 = (top + bottom) / (bottom - top); Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result); }; /** * Creates a right-handed orthographic projection matrix * @param left defines the viewport left coordinate * @param right defines the viewport right coordinate * @param bottom defines the viewport bottom coordinate * @param top defines the viewport top coordinate * @param znear defines the near clip plane * @param zfar defines the far clip plane * @returns a new matrix as a right-handed orthographic projection matrix */ Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) { var matrix = Matrix.Zero(); Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix); return matrix; }; /** * Stores a right-handed orthographic projection into a given matrix * @param left defines the viewport left coordinate * @param right defines the viewport right coordinate * @param bottom defines the viewport bottom coordinate * @param top defines the viewport top coordinate * @param znear defines the near clip plane * @param zfar defines the far clip plane * @param result defines the target matrix */ Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) { Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result); result.m[10] *= -1.0; }; /** * Creates a left-handed perspective projection matrix * @param width defines the viewport width * @param height defines the viewport height * @param znear defines the near clip plane * @param zfar defines the far clip plane * @returns a new matrix as a left-handed perspective projection matrix */ Matrix.PerspectiveLH = function (width, height, znear, zfar) { var matrix = Matrix.Zero(); var n = znear; var f = zfar; var a = 2.0 * n / width; var b = 2.0 * n / height; var c = (f + n) / (f - n); var d = -2.0 * f * n / (f - n); Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix); return matrix; }; /** * Creates a left-handed perspective projection matrix * @param fov defines the horizontal field of view * @param aspect defines the aspect ratio * @param znear defines the near clip plane * @param zfar defines the far clip plane * @returns a new matrix as a left-handed perspective projection matrix */ Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) { var matrix = Matrix.Zero(); Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix); return matrix; }; /** * Stores a left-handed perspective projection into a given matrix * @param fov defines the horizontal field of view * @param aspect defines the aspect ratio * @param znear defines the near clip plane * @param zfar defines the far clip plane * @param result defines the target matrix * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally */ Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) { if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; } var n = znear; var f = zfar; var t = 1.0 / (Math.tan(fov * 0.5)); var a = isVerticalFovFixed ? (t / aspect) : t; var b = isVerticalFovFixed ? t : (t * aspect); var c = (f + n) / (f - n); var d = -2.0 * f * n / (f - n); Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result); }; /** * Creates a right-handed perspective projection matrix * @param fov defines the horizontal field of view * @param aspect defines the aspect ratio * @param znear defines the near clip plane * @param zfar defines the far clip plane * @returns a new matrix as a right-handed perspective projection matrix */ Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) { var matrix = Matrix.Zero(); Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix); return matrix; }; /** * Stores a right-handed perspective projection into a given matrix * @param fov defines the horizontal field of view * @param aspect defines the aspect ratio * @param znear defines the near clip plane * @param zfar defines the far clip plane * @param result defines the target matrix * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally */ Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) { //alternatively this could be expressed as: // m = PerspectiveFovLHToRef // m[10] *= -1.0; // m[11] *= -1.0; if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; } var n = znear; var f = zfar; var t = 1.0 / (Math.tan(fov * 0.5)); var a = isVerticalFovFixed ? (t / aspect) : t; var b = isVerticalFovFixed ? t : (t * aspect); var c = -(f + n) / (f - n); var d = -2 * f * n / (f - n); Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result); }; /** * Stores a perspective projection for WebVR info a given matrix * @param fov defines the field of view * @param znear defines the near clip plane * @param zfar defines the far clip plane * @param result defines the target matrix * @param rightHanded defines if the matrix must be in right-handed mode (false by default) */ Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) { if (rightHanded === void 0) { rightHanded = false; } var rightHandedFactor = rightHanded ? -1 : 1; var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0); var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0); var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0); var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0); var xScale = 2.0 / (leftTan + rightTan); var yScale = 2.0 / (upTan + downTan); result.m[0] = xScale; result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0; result.m[5] = yScale; result.m[6] = result.m[7] = 0.0; result.m[8] = ((leftTan - rightTan) * xScale * 0.5); result.m[9] = -((upTan - downTan) * yScale * 0.5); result.m[10] = -zfar / (znear - zfar); result.m[11] = 1.0 * rightHandedFactor; result.m[12] = result.m[13] = result.m[15] = 0.0; result.m[14] = -(2.0 * zfar * znear) / (zfar - znear); result._markAsUpdated(); }; /** * Computes a complete transformation matrix * @param viewport defines the viewport to use * @param world defines the world matrix * @param view defines the view matrix * @param projection defines the projection matrix * @param zmin defines the near clip plane * @param zmax defines the far clip plane * @returns the transformation matrix */ Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) { var cw = viewport.width; var ch = viewport.height; var cx = viewport.x; var cy = viewport.y; var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1); return world.multiply(view).multiply(projection).multiply(viewportMatrix); }; /** * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array * @param matrix defines the matrix to use * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix */ Matrix.GetAsMatrix2x2 = function (matrix) { return new Float32Array([ matrix.m[0], matrix.m[1], matrix.m[4], matrix.m[5] ]); }; /** * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array * @param matrix defines the matrix to use * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix */ Matrix.GetAsMatrix3x3 = function (matrix) { return new Float32Array([ matrix.m[0], matrix.m[1], matrix.m[2], matrix.m[4], matrix.m[5], matrix.m[6], matrix.m[8], matrix.m[9], matrix.m[10] ]); }; /** * Compute the transpose of a given matrix * @param matrix defines the matrix to transpose * @returns the new matrix */ Matrix.Transpose = function (matrix) { var result = new Matrix(); Matrix.TransposeToRef(matrix, result); return result; }; /** * Compute the transpose of a matrix and store it in a target matrix * @param matrix defines the matrix to transpose * @param result defines the target matrix */ Matrix.TransposeToRef = function (matrix, result) { result.m[0] = matrix.m[0]; result.m[1] = matrix.m[4]; result.m[2] = matrix.m[8]; result.m[3] = matrix.m[12]; result.m[4] = matrix.m[1]; result.m[5] = matrix.m[5]; result.m[6] = matrix.m[9]; result.m[7] = matrix.m[13]; result.m[8] = matrix.m[2]; result.m[9] = matrix.m[6]; result.m[10] = matrix.m[10]; result.m[11] = matrix.m[14]; result.m[12] = matrix.m[3]; result.m[13] = matrix.m[7]; result.m[14] = matrix.m[11]; result.m[15] = matrix.m[15]; }; /** * Computes a reflection matrix from a plane * @param plane defines the reflection plane * @returns a new matrix */ Matrix.Reflection = function (plane) { var matrix = new Matrix(); Matrix.ReflectionToRef(plane, matrix); return matrix; }; /** * Computes a reflection matrix from a plane * @param plane defines the reflection plane * @param result defines the target matrix */ Matrix.ReflectionToRef = function (plane, result) { plane.normalize(); var x = plane.normal.x; var y = plane.normal.y; var z = plane.normal.z; var temp = -2 * x; var temp2 = -2 * y; var temp3 = -2 * z; result.m[0] = (temp * x) + 1; result.m[1] = temp2 * x; result.m[2] = temp3 * x; result.m[3] = 0.0; result.m[4] = temp * y; result.m[5] = (temp2 * y) + 1; result.m[6] = temp3 * y; result.m[7] = 0.0; result.m[8] = temp * z; result.m[9] = temp2 * z; result.m[10] = (temp3 * z) + 1; result.m[11] = 0.0; result.m[12] = temp * plane.d; result.m[13] = temp2 * plane.d; result.m[14] = temp3 * plane.d; result.m[15] = 1.0; result._markAsUpdated(); }; /** * Sets the given matrix as a rotation matrix composed from the 3 left handed axes * @param xaxis defines the value of the 1st axis * @param yaxis defines the value of the 2nd axis * @param zaxis defines the value of the 3rd axis * @param result defines the target matrix */ Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) { result.m[0] = xaxis.x; result.m[1] = xaxis.y; result.m[2] = xaxis.z; result.m[3] = 0.0; result.m[4] = yaxis.x; result.m[5] = yaxis.y; result.m[6] = yaxis.z; result.m[7] = 0.0; result.m[8] = zaxis.x; result.m[9] = zaxis.y; result.m[10] = zaxis.z; result.m[11] = 0.0; result.m[12] = 0.0; result.m[13] = 0.0; result.m[14] = 0.0; result.m[15] = 1.0; result._markAsUpdated(); }; /** * Creates a rotation matrix from a quaternion and stores it in a target matrix * @param quat defines the quaternion to use * @param result defines the target matrix */ Matrix.FromQuaternionToRef = function (quat, result) { var xx = quat.x * quat.x; var yy = quat.y * quat.y; var zz = quat.z * quat.z; var xy = quat.x * quat.y; var zw = quat.z * quat.w; var zx = quat.z * quat.x; var yw = quat.y * quat.w; var yz = quat.y * quat.z; var xw = quat.x * quat.w; result.m[0] = 1.0 - (2.0 * (yy + zz)); result.m[1] = 2.0 * (xy + zw); result.m[2] = 2.0 * (zx - yw); result.m[3] = 0.0; result.m[4] = 2.0 * (xy - zw); result.m[5] = 1.0 - (2.0 * (zz + xx)); result.m[6] = 2.0 * (yz + xw); result.m[7] = 0.0; result.m[8] = 2.0 * (zx + yw); result.m[9] = 2.0 * (yz - xw); result.m[10] = 1.0 - (2.0 * (yy + xx)); result.m[11] = 0.0; result.m[12] = 0.0; result.m[13] = 0.0; result.m[14] = 0.0; result.m[15] = 1.0; result._markAsUpdated(); }; Matrix._tempQuaternion = new Quaternion(); Matrix._xAxis = Vector3.Zero(); Matrix._yAxis = Vector3.Zero(); Matrix._zAxis = Vector3.Zero(); Matrix._updateFlagSeed = 0; Matrix._identityReadOnly = Matrix.Identity(); return Matrix; }()); BABYLON.Matrix = Matrix; var Plane = /** @class */ (function () { /** * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0 */ function Plane(a, b, c, d) { this.normal = new Vector3(a, b, c); this.d = d; } /** * Returns the plane coordinates as a new array of 4 elements [a, b, c, d]. */ Plane.prototype.asArray = function () { return [this.normal.x, this.normal.y, this.normal.z, this.d]; }; // Methods /** * Returns a new plane copied from the current Plane. */ Plane.prototype.clone = function () { return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d); }; /** * Returns the string "Plane". */ Plane.prototype.getClassName = function () { return "Plane"; }; /** * Returns the Plane hash code. */ Plane.prototype.getHashCode = function () { var hash = this.normal.getHashCode(); hash = (hash * 397) ^ (this.d || 0); return hash; }; /** * Normalize the current Plane in place. * Returns the updated Plane. */ Plane.prototype.normalize = function () { var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z))); var magnitude = 0.0; if (norm !== 0) { magnitude = 1.0 / norm; } this.normal.x *= magnitude; this.normal.y *= magnitude; this.normal.z *= magnitude; this.d *= magnitude; return this; }; /** * Returns a new Plane as the result of the transformation of the current Plane by the given matrix. */ Plane.prototype.transform = function (transformation) { var transposedMatrix = Matrix.Transpose(transformation); var x = this.normal.x; var y = this.normal.y; var z = this.normal.z; var d = this.d; var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]); var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]); var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]); var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]); return new Plane(normalX, normalY, normalZ, finalD); }; /** * Returns the dot product (float) of the point coordinates and the plane normal. */ Plane.prototype.dotCoordinate = function (point) { return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d); }; /** * Updates the current Plane from the plane defined by the three given points. * Returns the updated Plane. */ Plane.prototype.copyFromPoints = function (point1, point2, point3) { var x1 = point2.x - point1.x; var y1 = point2.y - point1.y; var z1 = point2.z - point1.z; var x2 = point3.x - point1.x; var y2 = point3.y - point1.y; var z2 = point3.z - point1.z; var yz = (y1 * z2) - (z1 * y2); var xz = (z1 * x2) - (x1 * z2); var xy = (x1 * y2) - (y1 * x2); var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy))); var invPyth; if (pyth !== 0) { invPyth = 1.0 / pyth; } else { invPyth = 0.0; } this.normal.x = yz * invPyth; this.normal.y = xz * invPyth; this.normal.z = xy * invPyth; this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z)); return this; }; /** * Boolean : True is the vector "direction" is the same side than the plane normal. */ Plane.prototype.isFrontFacingTo = function (direction, epsilon) { var dot = Vector3.Dot(this.normal, direction); return (dot <= epsilon); }; /** * Returns the signed distance (float) from the given point to the Plane. */ Plane.prototype.signedDistanceTo = function (point) { return Vector3.Dot(point, this.normal) + this.d; }; // Statics /** * Returns a new Plane from the given array. */ Plane.FromArray = function (array) { return new Plane(array[0], array[1], array[2], array[3]); }; /** * Returns a new Plane defined by the three given points. */ Plane.FromPoints = function (point1, point2, point3) { var result = new Plane(0.0, 0.0, 0.0, 0.0); result.copyFromPoints(point1, point2, point3); return result; }; /** * Returns a new Plane the normal vector to this plane at the given origin point. * Note : the vector "normal" is updated because normalized. */ Plane.FromPositionAndNormal = function (origin, normal) { var result = new Plane(0.0, 0.0, 0.0, 0.0); normal.normalize(); result.normal = normal; result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z); return result; }; /** * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point. */ Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) { var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z); return Vector3.Dot(point, normal) + d; }; return Plane; }()); BABYLON.Plane = Plane; var Viewport = /** @class */ (function () { /** * Creates a Viewport object located at (x, y) and sized (width, height). */ function Viewport(x, y, width, height) { this.x = x; this.y = y; this.width = width; this.height = height; } Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) { if (renderWidthOrEngine.getRenderWidth) { var engine = renderWidthOrEngine; return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight()); } var renderWidth = renderWidthOrEngine; return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight); }; /** * Returns a new Viewport copied from the current one. */ Viewport.prototype.clone = function () { return new Viewport(this.x, this.y, this.width, this.height); }; return Viewport; }()); BABYLON.Viewport = Viewport; var Frustum = /** @class */ (function () { function Frustum() { } /** * Returns a new array of 6 Frustum planes computed by the given transformation matrix. */ Frustum.GetPlanes = function (transform) { var frustumPlanes = []; for (var index = 0; index < 6; index++) { frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0)); } Frustum.GetPlanesToRef(transform, frustumPlanes); return frustumPlanes; }; Frustum.GetNearPlaneToRef = function (transform, frustumPlane) { frustumPlane.normal.x = transform.m[3] + transform.m[2]; frustumPlane.normal.y = transform.m[7] + transform.m[6]; frustumPlane.normal.z = transform.m[11] + transform.m[10]; frustumPlane.d = transform.m[15] + transform.m[14]; frustumPlane.normalize(); }; Frustum.GetFarPlaneToRef = function (transform, frustumPlane) { frustumPlane.normal.x = transform.m[3] - transform.m[2]; frustumPlane.normal.y = transform.m[7] - transform.m[6]; frustumPlane.normal.z = transform.m[11] - transform.m[10]; frustumPlane.d = transform.m[15] - transform.m[14]; frustumPlane.normalize(); }; Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) { frustumPlane.normal.x = transform.m[3] + transform.m[0]; frustumPlane.normal.y = transform.m[7] + transform.m[4]; frustumPlane.normal.z = transform.m[11] + transform.m[8]; frustumPlane.d = transform.m[15] + transform.m[12]; frustumPlane.normalize(); }; Frustum.GetRightPlaneToRef = function (transform, frustumPlane) { frustumPlane.normal.x = transform.m[3] - transform.m[0]; frustumPlane.normal.y = transform.m[7] - transform.m[4]; frustumPlane.normal.z = transform.m[11] - transform.m[8]; frustumPlane.d = transform.m[15] - transform.m[12]; frustumPlane.normalize(); }; Frustum.GetTopPlaneToRef = function (transform, frustumPlane) { frustumPlane.normal.x = transform.m[3] - transform.m[1]; frustumPlane.normal.y = transform.m[7] - transform.m[5]; frustumPlane.normal.z = transform.m[11] - transform.m[9]; frustumPlane.d = transform.m[15] - transform.m[13]; frustumPlane.normalize(); }; Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) { frustumPlane.normal.x = transform.m[3] + transform.m[1]; frustumPlane.normal.y = transform.m[7] + transform.m[5]; frustumPlane.normal.z = transform.m[11] + transform.m[9]; frustumPlane.d = transform.m[15] + transform.m[13]; frustumPlane.normalize(); }; /** * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix. */ Frustum.GetPlanesToRef = function (transform, frustumPlanes) { // Near Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]); // Far Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]); // Left Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]); // Right Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]); // Top Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]); // Bottom Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]); }; return Frustum; }()); BABYLON.Frustum = Frustum; /** Defines supported spaces */ var Space; (function (Space) { /** Local (object) space */ Space[Space["LOCAL"] = 0] = "LOCAL"; /** World space */ Space[Space["WORLD"] = 1] = "WORLD"; /** Bone space */ Space[Space["BONE"] = 2] = "BONE"; })(Space = BABYLON.Space || (BABYLON.Space = {})); /** Defines the 3 main axes */ var Axis = /** @class */ (function () { function Axis() { } /** X axis */ Axis.X = new Vector3(1.0, 0.0, 0.0); /** Y axis */ Axis.Y = new Vector3(0.0, 1.0, 0.0); /** Z axis */ Axis.Z = new Vector3(0.0, 0.0, 1.0); return Axis; }()); BABYLON.Axis = Axis; ; var BezierCurve = /** @class */ (function () { function BezierCurve() { } /** * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats. */ BezierCurve.interpolate = function (t, x1, y1, x2, y2) { // Extract X (which is equal to time here) var f0 = 1 - 3 * x2 + 3 * x1; var f1 = 3 * x2 - 6 * x1; var f2 = 3 * x1; var refinedT = t; for (var i = 0; i < 5; i++) { var refinedT2 = refinedT * refinedT; var refinedT3 = refinedT2 * refinedT; var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT; var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2); refinedT -= (x - t) * slope; refinedT = Math.min(1, Math.max(0, refinedT)); } // Resolve cubic bezier for the given x return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3); }; return BezierCurve; }()); BABYLON.BezierCurve = BezierCurve; /** * Defines potential orientation for back face culling */ var Orientation; (function (Orientation) { /** * Clockwise */ Orientation[Orientation["CW"] = 0] = "CW"; /** Counter clockwise */ Orientation[Orientation["CCW"] = 1] = "CCW"; })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {})); /** * Defines angle representation */ var Angle = /** @class */ (function () { /** * Creates an Angle object of "radians" radians (float). */ function Angle(radians) { this._radians = radians; if (this._radians < 0.0) this._radians += (2.0 * Math.PI); } /** * Get value in degrees * @returns the Angle value in degrees (float) */ Angle.prototype.degrees = function () { return this._radians * 180.0 / Math.PI; }; /** * Get value in radians * @returns the Angle value in radians (float) */ Angle.prototype.radians = function () { return this._radians; }; /** * Gets a new Angle object valued with the angle value in radians between the two given vectors * @param a defines first vector * @param b defines second vector * @returns a new Angle */ Angle.BetweenTwoPoints = function (a, b) { var delta = b.subtract(a); var theta = Math.atan2(delta.y, delta.x); return new Angle(theta); }; /** * Gets a new Angle object from the given float in radians * @param radians defines the angle value in radians * @returns a new Angle */ Angle.FromRadians = function (radians) { return new Angle(radians); }; /** * Gets a new Angle object from the given float in degrees * @param degrees defines the angle value in degrees * @returns a new Angle */ Angle.FromDegrees = function (degrees) { return new Angle(degrees * Math.PI / 180.0); }; return Angle; }()); BABYLON.Angle = Angle; var Arc2 = /** @class */ (function () { /** * Creates an Arc object from the three given points : start, middle and end. */ function Arc2(startPoint, midPoint, endPoint) { this.startPoint = startPoint; this.midPoint = midPoint; this.endPoint = endPoint; var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2); var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.; var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.; var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y); this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det); this.radius = this.centerPoint.subtract(this.startPoint).length(); this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint); var a1 = this.startAngle.degrees(); var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees(); var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees(); // angles correction if (a2 - a1 > +180.0) a2 -= 360.0; if (a2 - a1 < -180.0) a2 += 360.0; if (a3 - a2 > +180.0) a3 -= 360.0; if (a3 - a2 < -180.0) a3 += 360.0; this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW; this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1); } return Arc2; }()); BABYLON.Arc2 = Arc2; var Path2 = /** @class */ (function () { /** * Creates a Path2 object from the starting 2D coordinates x and y. */ function Path2(x, y) { this._points = new Array(); this._length = 0.0; this.closed = false; this._points.push(new Vector2(x, y)); } /** * Adds a new segment until the given coordinates (x, y) to the current Path2. * Returns the updated Path2. */ Path2.prototype.addLineTo = function (x, y) { if (this.closed) { return this; } var newPoint = new Vector2(x, y); var previousPoint = this._points[this._points.length - 1]; this._points.push(newPoint); this._length += newPoint.subtract(previousPoint).length(); return this; }; /** * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2. * Returns the updated Path2. */ Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) { if (numberOfSegments === void 0) { numberOfSegments = 36; } if (this.closed) { return this; } var startPoint = this._points[this._points.length - 1]; var midPoint = new Vector2(midX, midY); var endPoint = new Vector2(endX, endY); var arc = new Arc2(startPoint, midPoint, endPoint); var increment = arc.angle.radians() / numberOfSegments; if (arc.orientation === Orientation.CW) increment *= -1; var currentAngle = arc.startAngle.radians() + increment; for (var i = 0; i < numberOfSegments; i++) { var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x; var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y; this.addLineTo(x, y); currentAngle += increment; } return this; }; /** * Closes the Path2. * Returns the Path2. */ Path2.prototype.close = function () { this.closed = true; return this; }; /** * Returns the Path2 total length (float). */ Path2.prototype.length = function () { var result = this._length; if (!this.closed) { var lastPoint = this._points[this._points.length - 1]; var firstPoint = this._points[0]; result += (firstPoint.subtract(lastPoint).length()); } return result; }; /** * Returns the Path2 internal array of points. */ Path2.prototype.getPoints = function () { return this._points; }; /** * Returns a new Vector2 located at a percentage of the Path2 total length on this path. */ Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) { if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) { return Vector2.Zero(); } var lengthPosition = normalizedLengthPosition * this.length(); var previousOffset = 0; for (var i = 0; i < this._points.length; i++) { var j = (i + 1) % this._points.length; var a = this._points[i]; var b = this._points[j]; var bToA = b.subtract(a); var nextOffset = (bToA.length() + previousOffset); if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) { var dir = bToA.normalize(); var localOffset = lengthPosition - previousOffset; return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset)); } previousOffset = nextOffset; } return Vector2.Zero(); }; /** * Returns a new Path2 starting at the coordinates (x, y). */ Path2.StartingAt = function (x, y) { return new Path2(x, y); }; return Path2; }()); BABYLON.Path2 = Path2; var Path3D = /** @class */ (function () { /** * new Path3D(path, normal, raw) * Creates a Path3D. A Path3D is a logical math object, so not a mesh. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D * path : an array of Vector3, the curve axis of the Path3D * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed. */ function Path3D(path, firstNormal, raw) { if (firstNormal === void 0) { firstNormal = null; } this.path = path; this._curve = new Array(); this._distances = new Array(); this._tangents = new Array(); this._normals = new Array(); this._binormals = new Array(); for (var p = 0; p < path.length; p++) { this._curve[p] = path[p].clone(); // hard copy } this._raw = raw || false; this._compute(firstNormal); } /** * Returns the Path3D array of successive Vector3 designing its curve. */ Path3D.prototype.getCurve = function () { return this._curve; }; /** * Returns an array populated with tangent vectors on each Path3D curve point. */ Path3D.prototype.getTangents = function () { return this._tangents; }; /** * Returns an array populated with normal vectors on each Path3D curve point. */ Path3D.prototype.getNormals = function () { return this._normals; }; /** * Returns an array populated with binormal vectors on each Path3D curve point. */ Path3D.prototype.getBinormals = function () { return this._binormals; }; /** * Returns an array populated with distances (float) of the i-th point from the first curve point. */ Path3D.prototype.getDistances = function () { return this._distances; }; /** * Forces the Path3D tangent, normal, binormal and distance recomputation. * Returns the same object updated. */ Path3D.prototype.update = function (path, firstNormal) { if (firstNormal === void 0) { firstNormal = null; } for (var p = 0; p < path.length; p++) { this._curve[p].x = path[p].x; this._curve[p].y = path[p].y; this._curve[p].z = path[p].z; } this._compute(firstNormal); return this; }; // private function compute() : computes tangents, normals and binormals Path3D.prototype._compute = function (firstNormal) { var l = this._curve.length; // first and last tangents this._tangents[0] = this._getFirstNonNullVector(0); if (!this._raw) { this._tangents[0].normalize(); } this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]); if (!this._raw) { this._tangents[l - 1].normalize(); } // normals and binormals at first point : arbitrary vector with _normalVector() var tg0 = this._tangents[0]; var pp0 = this._normalVector(this._curve[0], tg0, firstNormal); this._normals[0] = pp0; if (!this._raw) { this._normals[0].normalize(); } this._binormals[0] = Vector3.Cross(tg0, this._normals[0]); if (!this._raw) { this._binormals[0].normalize(); } this._distances[0] = 0.0; // normals and binormals : next points var prev; // previous vector (segment) var cur; // current vector (segment) var curTang; // current tangent // previous normal var prevBinor; // previous binormal for (var i = 1; i < l; i++) { // tangents prev = this._getLastNonNullVector(i); if (i < l - 1) { cur = this._getFirstNonNullVector(i); this._tangents[i] = prev.add(cur); this._tangents[i].normalize(); } this._distances[i] = this._distances[i - 1] + prev.length(); // normals and binormals // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html curTang = this._tangents[i]; prevBinor = this._binormals[i - 1]; this._normals[i] = Vector3.Cross(prevBinor, curTang); if (!this._raw) { this._normals[i].normalize(); } this._binormals[i] = Vector3.Cross(curTang, this._normals[i]); if (!this._raw) { this._binormals[i].normalize(); } } }; // private function getFirstNonNullVector(index) // returns the first non null vector from index : curve[index + N].subtract(curve[index]) Path3D.prototype._getFirstNonNullVector = function (index) { var i = 1; var nNVector = this._curve[index + i].subtract(this._curve[index]); while (nNVector.length() === 0 && index + i + 1 < this._curve.length) { i++; nNVector = this._curve[index + i].subtract(this._curve[index]); } return nNVector; }; // private function getLastNonNullVector(index) // returns the last non null vector from index : curve[index].subtract(curve[index - N]) Path3D.prototype._getLastNonNullVector = function (index) { var i = 1; var nLVector = this._curve[index].subtract(this._curve[index - i]); while (nLVector.length() === 0 && index > i + 1) { i++; nLVector = this._curve[index].subtract(this._curve[index - i]); } return nLVector; }; // private function normalVector(v0, vt, va) : // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0 Path3D.prototype._normalVector = function (v0, vt, va) { var normal0; var tgl = vt.length(); if (tgl === 0.0) { tgl = 1.0; } if (va === undefined || va === null) { var point; if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane point = new Vector3(0.0, -1.0, 0.0); } else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) { point = new Vector3(1.0, 0.0, 0.0); } else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) { point = new Vector3(0.0, 0.0, 1.0); } else { point = Vector3.Zero(); } normal0 = Vector3.Cross(vt, point); } else { normal0 = Vector3.Cross(vt, va); Vector3.CrossToRef(normal0, vt, normal0); } normal0.normalize(); return normal0; }; return Path3D; }()); BABYLON.Path3D = Path3D; var Curve3 = /** @class */ (function () { /** * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space. * A Curve3 is designed from a series of successive Vector3. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object */ function Curve3(points) { this._length = 0.0; this._points = points; this._length = this._computeLength(points); } /** * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve * @param v0 (Vector3) the origin point of the Quadratic Bezier * @param v1 (Vector3) the control point * @param v2 (Vector3) the end point of the Quadratic Bezier * @param nbPoints (integer) the wanted number of points in the curve */ Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) { nbPoints = nbPoints > 2 ? nbPoints : 3; var bez = new Array(); var equation = function (t, val0, val1, val2) { var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2; return res; }; for (var i = 0; i <= nbPoints; i++) { bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z))); } return new Curve3(bez); }; /** * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve * @param v0 (Vector3) the origin point of the Cubic Bezier * @param v1 (Vector3) the first control point * @param v2 (Vector3) the second control point * @param v3 (Vector3) the end point of the Cubic Bezier * @param nbPoints (integer) the wanted number of points in the curve */ Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) { nbPoints = nbPoints > 3 ? nbPoints : 4; var bez = new Array(); var equation = function (t, val0, val1, val2, val3) { var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3; return res; }; for (var i = 0; i <= nbPoints; i++) { bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z))); } return new Curve3(bez); }; /** * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline * @param p1 (Vector3) the origin point of the Hermite Spline * @param t1 (Vector3) the tangent vector at the origin point * @param p2 (Vector3) the end point of the Hermite Spline * @param t2 (Vector3) the tangent vector at the end point * @param nbPoints (integer) the wanted number of points in the curve */ Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) { var hermite = new Array(); var step = 1.0 / nbPoints; for (var i = 0; i <= nbPoints; i++) { hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step)); } return new Curve3(hermite); }; /** * Returns a Curve3 object along a CatmullRom Spline curve : * @param points (array of Vector3) the points the spline must pass through. At least, four points required * @param nbPoints (integer) the wanted number of points between each curve control points * @param closed (boolean) optional with default false, when true forms a closed loop from the points */ Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) { var catmullRom = new Array(); var step = 1.0 / nbPoints; var amount = 0.0; if (closed) { var pointsCount = points.length; for (var i = 0; i < pointsCount; i++) { amount = 0; for (var c = 0; c < nbPoints; c++) { catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount)); amount += step; } } catmullRom.push(catmullRom[0]); } else { var totalPoints = new Array(); totalPoints.push(points[0].clone()); Array.prototype.push.apply(totalPoints, points); totalPoints.push(points[points.length - 1].clone()); for (var i = 0; i < totalPoints.length - 3; i++) { amount = 0; for (var c = 0; c < nbPoints; c++) { catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount)); amount += step; } } i--; catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount)); } return new Curve3(catmullRom); }; /** * Returns the Curve3 stored array of successive Vector3 */ Curve3.prototype.getPoints = function () { return this._points; }; /** * Returns the computed length (float) of the curve. */ Curve3.prototype.length = function () { return this._length; }; /** * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB); * This new Curve3 is built by translating and sticking the curveB at the end of the curveA. * curveA and curveB keep unchanged. */ Curve3.prototype.continue = function (curve) { var lastPoint = this._points[this._points.length - 1]; var continuedPoints = this._points.slice(); var curvePoints = curve.getPoints(); for (var i = 1; i < curvePoints.length; i++) { continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint)); } var continuedCurve = new Curve3(continuedPoints); return continuedCurve; }; Curve3.prototype._computeLength = function (path) { var l = 0; for (var i = 1; i < path.length; i++) { l += (path[i].subtract(path[i - 1])).length(); } return l; }; return Curve3; }()); BABYLON.Curve3 = Curve3; // Vertex formats var PositionNormalVertex = /** @class */ (function () { function PositionNormalVertex(position, normal) { if (position === void 0) { position = Vector3.Zero(); } if (normal === void 0) { normal = Vector3.Up(); } this.position = position; this.normal = normal; } PositionNormalVertex.prototype.clone = function () { return new PositionNormalVertex(this.position.clone(), this.normal.clone()); }; return PositionNormalVertex; }()); BABYLON.PositionNormalVertex = PositionNormalVertex; var PositionNormalTextureVertex = /** @class */ (function () { function PositionNormalTextureVertex(position, normal, uv) { if (position === void 0) { position = Vector3.Zero(); } if (normal === void 0) { normal = Vector3.Up(); } if (uv === void 0) { uv = Vector2.Zero(); } this.position = position; this.normal = normal; this.uv = uv; } PositionNormalTextureVertex.prototype.clone = function () { return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone()); }; return PositionNormalTextureVertex; }()); BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex; // Temporary pre-allocated objects for engine internal use // usage in any internal function : // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3 // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix var Tmp = /** @class */ (function () { function Tmp() { } Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()]; Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(), Matrix.Zero(), Matrix.Zero(), Matrix.Zero(), Matrix.Zero(), Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough return Tmp; }()); BABYLON.Tmp = Tmp; // Same as Tmp but not exported to keep it only for math functions to avoid conflicts var MathTmp = /** @class */ (function () { function MathTmp() { } MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()]; MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()]; return MathTmp; }()); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.math.js.map var BABYLON; (function (BABYLON) { var Scalar = /** @class */ (function () { function Scalar() { } /** * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45) */ Scalar.WithinEpsilon = function (a, b, epsilon) { if (epsilon === void 0) { epsilon = 1.401298E-45; } var num = a - b; return -epsilon <= num && num <= epsilon; }; /** * Returns a string : the upper case translation of the number i to hexadecimal. */ Scalar.ToHex = function (i) { var str = i.toString(16); if (i <= 15) { return ("0" + str).toUpperCase(); } return str.toUpperCase(); }; /** * Returns -1 if value is negative and +1 is value is positive. * Returns the value itself if it's equal to zero. */ Scalar.Sign = function (value) { value = +value; // convert to a number if (value === 0 || isNaN(value)) return value; return value > 0 ? 1 : -1; }; /** * Returns the value itself if it's between min and max. * Returns min if the value is lower than min. * Returns max if the value is greater than max. */ Scalar.Clamp = function (value, min, max) { if (min === void 0) { min = 0; } if (max === void 0) { max = 1; } return Math.min(max, Math.max(min, value)); }; /** * Returns the log2 of value. */ Scalar.Log2 = function (value) { return Math.log(value) * Math.LOG2E; }; /** * Loops the value, so that it is never larger than length and never smaller than 0. * * This is similar to the modulo operator but it works with floating point numbers. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5. * With t = 5 and length = 2.5, the result would be 0.0. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator */ Scalar.Repeat = function (value, length) { return value - Math.floor(value / length) * length; }; /** * Normalize the value between 0.0 and 1.0 using min and max values */ Scalar.Normalize = function (value, min, max) { return (value - min) / (max - min); }; /** * Denormalize the value from 0.0 and 1.0 using min and max values */ Scalar.Denormalize = function (normalized, min, max) { return (normalized * (max - min) + min); }; /** * Calculates the shortest difference between two given angles given in degrees. */ Scalar.DeltaAngle = function (current, target) { var num = Scalar.Repeat(target - current, 360.0); if (num > 180.0) { num -= 360.0; } return num; }; /** * PingPongs the value t, so that it is never larger than length and never smaller than 0. * * The returned value will move back and forth between 0 and length */ Scalar.PingPong = function (tx, length) { var t = Scalar.Repeat(tx, length * 2.0); return length - Math.abs(t - length); }; /** * Interpolates between min and max with smoothing at the limits. * * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions. */ Scalar.SmoothStep = function (from, to, tx) { var t = Scalar.Clamp(tx); t = -2.0 * t * t * t + 3.0 * t * t; return to * t + from * (1.0 - t); }; /** * Moves a value current towards target. * * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta. * Negative values of maxDelta pushes the value away from target. */ Scalar.MoveTowards = function (current, target, maxDelta) { var result = 0; if (Math.abs(target - current) <= maxDelta) { result = target; } else { result = current + Scalar.Sign(target - current) * maxDelta; } return result; }; /** * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees. * * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead. */ Scalar.MoveTowardsAngle = function (current, target, maxDelta) { var num = Scalar.DeltaAngle(current, target); var result = 0; if (-maxDelta < num && num < maxDelta) { result = target; } else { target = current + num; result = Scalar.MoveTowards(current, target, maxDelta); } return result; }; /** * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar. */ Scalar.Lerp = function (start, end, amount) { return start + ((end - start) * amount); }; /** * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees. */ Scalar.LerpAngle = function (start, end, amount) { var num = Scalar.Repeat(end - start, 360.0); if (num > 180.0) { num -= 360.0; } return start + num * Scalar.Clamp(amount); }; /** * Calculates the linear parameter t that produces the interpolant value within the range [a, b]. */ Scalar.InverseLerp = function (a, b, value) { var result = 0; if (a != b) { result = Scalar.Clamp((value - a) / (b - a)); } else { result = 0.0; } return result; }; /** * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2". */ Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) { var squared = amount * amount; var cubed = amount * squared; var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0; var part2 = (-2.0 * cubed) + (3.0 * squared); var part3 = (cubed - (2.0 * squared)) + amount; var part4 = cubed - squared; return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4); }; /** * Returns a random float number between and min and max values */ Scalar.RandomRange = function (min, max) { if (min === max) return min; return ((Math.random() * (max - min)) + min); }; /** * This function returns percentage of a number in a given range. * * RangeToPercent(40,20,60) will return 0.5 (50%) * RangeToPercent(34,0,100) will return 0.34 (34%) */ Scalar.RangeToPercent = function (number, min, max) { return ((number - min) / (max - min)); }; /** * This function returns number that corresponds to the percentage in a given range. * * PercentToRange(0.34,0,100) will return 34. */ Scalar.PercentToRange = function (percent, min, max) { return ((max - min) * percent + min); }; /** * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians. * @param angle The angle to normalize in radian. * @return The converted angle. */ Scalar.NormalizeRadians = function (angle) { // More precise but slower version kept for reference. // angle = angle % Tools.TwoPi; // angle = (angle + Tools.TwoPi) % Tools.TwoPi; //if (angle > Math.PI) { // angle -= Tools.TwoPi; //} angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi)); return angle; }; /** * Two pi constants convenient for computation. */ Scalar.TwoPi = Math.PI * 2; return Scalar; }()); BABYLON.Scalar = Scalar; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.math.scalar.js.map //# sourceMappingURL=babylon.mixins.js.map // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800 // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/ // Definitions by: Nico Kemnitz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped //# sourceMappingURL=babylon.webgl2.js.map var BABYLON; (function (BABYLON) { var __decoratorInitialStore = {}; var __mergedStore = {}; var _copySource = function (creationFunction, source, instanciate) { var destination = creationFunction(); // Tags if (BABYLON.Tags) { BABYLON.Tags.AddTagsTo(destination, source.tags); } var classStore = getMergedStore(destination); // Properties for (var property in classStore) { var propertyDescriptor = classStore[property]; var sourceProperty = source[property]; var propertyType = propertyDescriptor.type; if (sourceProperty !== undefined && sourceProperty !== null) { switch (propertyType) { case 0: // Value case 6: // Mesh reference case 11: // Camera reference destination[property] = sourceProperty; break; case 1: // Texture destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone(); break; case 2: // Color3 case 3: // FresnelParameters case 4: // Vector2 case 5: // Vector3 case 7: // Color Curves case 10: // Quaternion destination[property] = instanciate ? sourceProperty : sourceProperty.clone(); break; } } } return destination; }; function getDirectStore(target) { var classKey = target.getClassName(); if (!__decoratorInitialStore[classKey]) { __decoratorInitialStore[classKey] = {}; } return __decoratorInitialStore[classKey]; } /** * Return the list of properties flagged as serializable * @param target: host object */ function getMergedStore(target) { var classKey = target.getClassName(); if (__mergedStore[classKey]) { return __mergedStore[classKey]; } __mergedStore[classKey] = {}; var store = __mergedStore[classKey]; var currentTarget = target; var currentKey = classKey; while (currentKey) { var initialStore = __decoratorInitialStore[currentKey]; for (var property in initialStore) { store[property] = initialStore[property]; } var parent_1 = void 0; var done = false; do { parent_1 = Object.getPrototypeOf(currentTarget); if (!parent_1.getClassName) { done = true; break; } if (parent_1.getClassName() !== currentKey) { break; } currentTarget = parent_1; } while (parent_1); if (done) { break; } currentKey = parent_1.getClassName(); currentTarget = parent_1; } return store; } function generateSerializableMember(type, sourceName) { return function (target, propertyKey) { var classStore = getDirectStore(target); if (!classStore[propertyKey]) { classStore[propertyKey] = { type: type, sourceName: sourceName }; } }; } function generateExpandMember(setCallback, targetKey) { if (targetKey === void 0) { targetKey = null; } return function (target, propertyKey) { var key = targetKey || ("_" + propertyKey); Object.defineProperty(target, propertyKey, { get: function () { return this[key]; }, set: function (value) { if (this[key] === value) { return; } this[key] = value; target[setCallback].apply(this); }, enumerable: true, configurable: true }); }; } function expandToProperty(callback, targetKey) { if (targetKey === void 0) { targetKey = null; } return generateExpandMember(callback, targetKey); } BABYLON.expandToProperty = expandToProperty; function serialize(sourceName) { return generateSerializableMember(0, sourceName); // value member } BABYLON.serialize = serialize; function serializeAsTexture(sourceName) { return generateSerializableMember(1, sourceName); // texture member } BABYLON.serializeAsTexture = serializeAsTexture; function serializeAsColor3(sourceName) { return generateSerializableMember(2, sourceName); // color3 member } BABYLON.serializeAsColor3 = serializeAsColor3; function serializeAsFresnelParameters(sourceName) { return generateSerializableMember(3, sourceName); // fresnel parameters member } BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters; function serializeAsVector2(sourceName) { return generateSerializableMember(4, sourceName); // vector2 member } BABYLON.serializeAsVector2 = serializeAsVector2; function serializeAsVector3(sourceName) { return generateSerializableMember(5, sourceName); // vector3 member } BABYLON.serializeAsVector3 = serializeAsVector3; function serializeAsMeshReference(sourceName) { return generateSerializableMember(6, sourceName); // mesh reference member } BABYLON.serializeAsMeshReference = serializeAsMeshReference; function serializeAsColorCurves(sourceName) { return generateSerializableMember(7, sourceName); // color curves } BABYLON.serializeAsColorCurves = serializeAsColorCurves; function serializeAsColor4(sourceName) { return generateSerializableMember(8, sourceName); // color 4 } BABYLON.serializeAsColor4 = serializeAsColor4; function serializeAsImageProcessingConfiguration(sourceName) { return generateSerializableMember(9, sourceName); // image processing } BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration; function serializeAsQuaternion(sourceName) { return generateSerializableMember(10, sourceName); // quaternion member } BABYLON.serializeAsQuaternion = serializeAsQuaternion; /** * Decorator used to define property that can be serialized as reference to a camera * @param sourceName defines the name of the property to decorate */ function serializeAsCameraReference(sourceName) { return generateSerializableMember(11, sourceName); // camera reference member } BABYLON.serializeAsCameraReference = serializeAsCameraReference; var SerializationHelper = /** @class */ (function () { function SerializationHelper() { } SerializationHelper.Serialize = function (entity, serializationObject) { if (!serializationObject) { serializationObject = {}; } // Tags if (BABYLON.Tags) { serializationObject.tags = BABYLON.Tags.GetTags(entity); } var serializedProperties = getMergedStore(entity); // Properties for (var property in serializedProperties) { var propertyDescriptor = serializedProperties[property]; var targetPropertyName = propertyDescriptor.sourceName || property; var propertyType = propertyDescriptor.type; var sourceProperty = entity[property]; if (sourceProperty !== undefined && sourceProperty !== null) { switch (propertyType) { case 0: // Value serializationObject[targetPropertyName] = sourceProperty; break; case 1: // Texture serializationObject[targetPropertyName] = sourceProperty.serialize(); break; case 2: // Color3 serializationObject[targetPropertyName] = sourceProperty.asArray(); break; case 3: // FresnelParameters serializationObject[targetPropertyName] = sourceProperty.serialize(); break; case 4: // Vector2 serializationObject[targetPropertyName] = sourceProperty.asArray(); break; case 5: // Vector3 serializationObject[targetPropertyName] = sourceProperty.asArray(); break; case 6: // Mesh reference serializationObject[targetPropertyName] = sourceProperty.id; break; case 7: // Color Curves serializationObject[targetPropertyName] = sourceProperty.serialize(); break; case 8: // Color 4 serializationObject[targetPropertyName] = sourceProperty.asArray(); break; case 9: // Image Processing serializationObject[targetPropertyName] = sourceProperty.serialize(); break; case 10: // Quaternion serializationObject[targetPropertyName] = sourceProperty.asArray(); break; case 11: // Camera reference serializationObject[targetPropertyName] = sourceProperty.id; break; } } } return serializationObject; }; SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) { if (rootUrl === void 0) { rootUrl = null; } var destination = creationFunction(); if (!rootUrl) { rootUrl = ""; } // Tags if (BABYLON.Tags) { BABYLON.Tags.AddTagsTo(destination, source.tags); } var classStore = getMergedStore(destination); // Properties for (var property in classStore) { var propertyDescriptor = classStore[property]; var sourceProperty = source[propertyDescriptor.sourceName || property]; var propertyType = propertyDescriptor.type; if (sourceProperty !== undefined && sourceProperty !== null) { var dest = destination; switch (propertyType) { case 0: // Value dest[property] = sourceProperty; break; case 1: // Texture if (scene) { dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl); } break; case 2: // Color3 dest[property] = BABYLON.Color3.FromArray(sourceProperty); break; case 3: // FresnelParameters dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty); break; case 4: // Vector2 dest[property] = BABYLON.Vector2.FromArray(sourceProperty); break; case 5: // Vector3 dest[property] = BABYLON.Vector3.FromArray(sourceProperty); break; case 6: // Mesh reference if (scene) { dest[property] = scene.getLastMeshByID(sourceProperty); } break; case 7: // Color Curves dest[property] = BABYLON.ColorCurves.Parse(sourceProperty); break; case 8: // Color 4 dest[property] = BABYLON.Color4.FromArray(sourceProperty); break; case 9: // Image Processing dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty); break; case 10: // Quaternion dest[property] = BABYLON.Quaternion.FromArray(sourceProperty); break; case 11: // Camera reference if (scene) { dest[property] = scene.getCameraByID(sourceProperty); } break; } } } return destination; }; SerializationHelper.Clone = function (creationFunction, source) { return _copySource(creationFunction, source, false); }; SerializationHelper.Instanciate = function (creationFunction, source) { return _copySource(creationFunction, source, true); }; return SerializationHelper; }()); BABYLON.SerializationHelper = SerializationHelper; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.decorators.js.map var BABYLON; (function (BABYLON) { /** * Wrapper class for promise with external resolve and reject. */ var Deferred = /** @class */ (function () { /** * Constructor for this deferred object. */ function Deferred() { var _this = this; this.promise = new Promise(function (resolve, reject) { _this._resolve = resolve; _this._reject = reject; }); } Object.defineProperty(Deferred.prototype, "resolve", { /** * The resolve method of the promise associated with this deferred object. */ get: function () { return this._resolve; }, enumerable: true, configurable: true }); Object.defineProperty(Deferred.prototype, "reject", { /** * The reject method of the promise associated with this deferred object. */ get: function () { return this._reject; }, enumerable: true, configurable: true }); return Deferred; }()); BABYLON.Deferred = Deferred; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.deferred.js.map var BABYLON; (function (BABYLON) { /** * A class serves as a medium between the observable and its observers */ var EventState = /** @class */ (function () { /** * Create a new EventState * @param mask defines the mask associated with this state * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true * @param target defines the original target of the state * @param currentTarget defines the current target of the state */ function EventState(mask, skipNextObservers, target, currentTarget) { if (skipNextObservers === void 0) { skipNextObservers = false; } this.initalize(mask, skipNextObservers, target, currentTarget); } /** * Initialize the current event state * @param mask defines the mask associated with this state * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true * @param target defines the original target of the state * @param currentTarget defines the current target of the state * @returns the current event state */ EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) { if (skipNextObservers === void 0) { skipNextObservers = false; } this.mask = mask; this.skipNextObservers = skipNextObservers; this.target = target; this.currentTarget = currentTarget; return this; }; return EventState; }()); BABYLON.EventState = EventState; /** * Represent an Observer registered to a given Observable object. */ var Observer = /** @class */ (function () { /** * Creates a new observer * @param callback defines the callback to call when the observer is notified * @param mask defines the mask of the observer (used to filter notifications) * @param scope defines the current scope used to restore the JS context */ function Observer( /** * Defines the callback to call when the observer is notified */ callback, /** * Defines the mask of the observer (used to filter notifications) */ mask, /** * Defines the current scope used to restore the JS context */ scope) { if (scope === void 0) { scope = null; } this.callback = callback; this.mask = mask; this.scope = scope; /** @hidden */ this._willBeUnregistered = false; /** * Gets or sets a property defining that the observer as to be unregistered after the next notification */ this.unregisterOnNextCall = false; } return Observer; }()); BABYLON.Observer = Observer; /** * Represent a list of observers registered to multiple Observables object. */ var MultiObserver = /** @class */ (function () { function MultiObserver() { } /** * Release associated resources */ MultiObserver.prototype.dispose = function () { if (this._observers && this._observables) { for (var index = 0; index < this._observers.length; index++) { this._observables[index].remove(this._observers[index]); } } this._observers = null; this._observables = null; }; /** * Raise a callback when one of the observable will notify * @param observables defines a list of observables to watch * @param callback defines the callback to call on notification * @param mask defines the mask used to filter notifications * @param scope defines the current scope used to restore the JS context * @returns the new MultiObserver */ MultiObserver.Watch = function (observables, callback, mask, scope) { if (mask === void 0) { mask = -1; } if (scope === void 0) { scope = null; } var result = new MultiObserver(); result._observers = new Array(); result._observables = observables; for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) { var observable = observables_1[_i]; var observer = observable.add(callback, mask, false, scope); if (observer) { result._observers.push(observer); } } return result; }; return MultiObserver; }()); BABYLON.MultiObserver = MultiObserver; /** * The Observable class is a simple implementation of the Observable pattern. * * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified. * This enable a more fine grained execution without having to rely on multiple different Observable objects. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08). * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right. */ var Observable = /** @class */ (function () { /** * Creates a new observable * @param onObserverAdded defines a callback to call when a new observer is added */ function Observable(onObserverAdded) { this._observers = new Array(); this._eventState = new EventState(0); if (onObserverAdded) { this._onObserverAdded = onObserverAdded; } } /** * Create a new Observer with the specified callback * @param callback the callback that will be executed for that Observer * @param mask the mask used to filter observers * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present. * @param scope optional scope for the callback to be called from * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification * @returns the new observer created for the callback */ Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) { if (mask === void 0) { mask = -1; } if (insertFirst === void 0) { insertFirst = false; } if (scope === void 0) { scope = null; } if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; } if (!callback) { return null; } var observer = new Observer(callback, mask, scope); observer.unregisterOnNextCall = unregisterOnFirstCall; if (insertFirst) { this._observers.unshift(observer); } else { this._observers.push(observer); } if (this._onObserverAdded) { this._onObserverAdded(observer); } return observer; }; /** * Create a new Observer with the specified callback and unregisters after the next notification * @param callback the callback that will be executed for that Observer * @returns the new observer created for the callback */ Observable.prototype.addOnce = function (callback) { return this.add(callback, undefined, undefined, undefined, true); }; /** * Remove an Observer from the Observable object * @param observer the instance of the Observer to remove * @returns false if it doesn't belong to this Observable */ Observable.prototype.remove = function (observer) { if (!observer) { return false; } var index = this._observers.indexOf(observer); if (index !== -1) { this._observers.splice(index, 1); return true; } return false; }; /** * Remove a callback from the Observable object * @param callback the callback to remove * @param scope optional scope. If used only the callbacks with this scope will be removed * @returns false if it doesn't belong to this Observable */ Observable.prototype.removeCallback = function (callback, scope) { for (var index = 0; index < this._observers.length; index++) { if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) { this._observers.splice(index, 1); return true; } } return false; }; Observable.prototype._deferUnregister = function (observer) { var _this = this; observer.unregisterOnNextCall = false; observer._willBeUnregistered = true; BABYLON.Tools.SetImmediate(function () { _this.remove(observer); }); }; /** * Notify all Observers by calling their respective callback with the given data * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute * @param eventData defines the data to send to all observers * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified) * @param target defines the original target of the state * @param currentTarget defines the current target of the state * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true) */ Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) { if (mask === void 0) { mask = -1; } if (!this._observers.length) { return true; } var state = this._eventState; state.mask = mask; state.target = target; state.currentTarget = currentTarget; state.skipNextObservers = false; state.lastReturnValue = eventData; for (var _i = 0, _a = this._observers; _i < _a.length; _i++) { var obs = _a[_i]; if (obs._willBeUnregistered) { continue; } if (obs.mask & mask) { if (obs.scope) { state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]); } else { state.lastReturnValue = obs.callback(eventData, state); } if (obs.unregisterOnNextCall) { this._deferUnregister(obs); } } if (state.skipNextObservers) { return false; } } return true; }; /** * Calling this will execute each callback, expecting it to be a promise or return a value. * If at any point in the chain one function fails, the promise will fail and the execution will not continue. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object * and it is crucial that all callbacks will be executed. * The order of the callbacks is kept, callbacks are not executed parallel. * * @param eventData The data to be sent to each callback * @param mask is used to filter observers defaults to -1 * @param target defines the callback target (see EventState) * @param currentTarget defines he current object in the bubbling phase * @returns {Promise} will return a Promise than resolves when all callbacks executed successfully. */ Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) { var _this = this; if (mask === void 0) { mask = -1; } // create an empty promise var p = Promise.resolve(eventData); // no observers? return this promise. if (!this._observers.length) { return p; } var state = this._eventState; state.mask = mask; state.target = target; state.currentTarget = currentTarget; state.skipNextObservers = false; // execute one callback after another (not using Promise.all, the order is important) this._observers.forEach(function (obs) { if (state.skipNextObservers) { return; } if (obs._willBeUnregistered) { return; } if (obs.mask & mask) { if (obs.scope) { p = p.then(function (lastReturnedValue) { state.lastReturnValue = lastReturnedValue; return obs.callback.apply(obs.scope, [eventData, state]); }); } else { p = p.then(function (lastReturnedValue) { state.lastReturnValue = lastReturnedValue; return obs.callback(eventData, state); }); } if (obs.unregisterOnNextCall) { _this._deferUnregister(obs); } } }); // return the eventData return p.then(function () { return eventData; }); }; /** * Notify a specific observer * @param observer defines the observer to notify * @param eventData defines the data to be sent to each callback * @param mask is used to filter observers defaults to -1 */ Observable.prototype.notifyObserver = function (observer, eventData, mask) { if (mask === void 0) { mask = -1; } var state = this._eventState; state.mask = mask; state.skipNextObservers = false; observer.callback(eventData, state); }; /** * Gets a boolean indicating if the observable has at least one observer * @returns true is the Observable has at least one Observer registered */ Observable.prototype.hasObservers = function () { return this._observers.length > 0; }; /** * Clear the list of observers */ Observable.prototype.clear = function () { this._observers = new Array(); this._onObserverAdded = null; }; /** * Clone the current observable * @returns a new observable */ Observable.prototype.clone = function () { var result = new Observable(); result._observers = this._observers.slice(0); return result; }; /** * Does this observable handles observer registered with a given mask * @param mask defines the mask to be tested * @return whether or not one observer registered with the given mask is handeled **/ Observable.prototype.hasSpecificMask = function (mask) { if (mask === void 0) { mask = -1; } for (var _i = 0, _a = this._observers; _i < _a.length; _i++) { var obs = _a[_i]; if (obs.mask & mask || obs.mask === mask) { return true; } } return false; }; return Observable; }()); BABYLON.Observable = Observable; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.observable.js.map var BABYLON; (function (BABYLON) { var SmartArray = /** @class */ (function () { function SmartArray(capacity) { this.length = 0; this.data = new Array(capacity); this._id = SmartArray._GlobalId++; } SmartArray.prototype.push = function (value) { this.data[this.length++] = value; if (this.length > this.data.length) { this.data.length *= 2; } }; SmartArray.prototype.forEach = function (func) { for (var index = 0; index < this.length; index++) { func(this.data[index]); } }; SmartArray.prototype.sort = function (compareFn) { this.data.sort(compareFn); }; SmartArray.prototype.reset = function () { this.length = 0; }; SmartArray.prototype.dispose = function () { this.reset(); if (this.data) { this.data.length = 0; this.data = []; } }; SmartArray.prototype.concat = function (array) { if (array.length === 0) { return; } if (this.length + array.length > this.data.length) { this.data.length = (this.length + array.length) * 2; } for (var index = 0; index < array.length; index++) { this.data[this.length++] = (array.data || array)[index]; } }; SmartArray.prototype.indexOf = function (value) { var position = this.data.indexOf(value); if (position >= this.length) { return -1; } return position; }; SmartArray.prototype.contains = function (value) { return this.data.indexOf(value) !== -1; }; // Statics SmartArray._GlobalId = 0; return SmartArray; }()); BABYLON.SmartArray = SmartArray; var SmartArrayNoDuplicate = /** @class */ (function (_super) { __extends(SmartArrayNoDuplicate, _super); function SmartArrayNoDuplicate() { var _this = _super !== null && _super.apply(this, arguments) || this; _this._duplicateId = 0; return _this; } SmartArrayNoDuplicate.prototype.push = function (value) { _super.prototype.push.call(this, value); if (!value.__smartArrayFlags) { value.__smartArrayFlags = {}; } value.__smartArrayFlags[this._id] = this._duplicateId; }; SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) { if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) { return false; } this.push(value); return true; }; SmartArrayNoDuplicate.prototype.reset = function () { _super.prototype.reset.call(this); this._duplicateId++; }; SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) { if (array.length === 0) { return; } if (this.length + array.length > this.data.length) { this.data.length = (this.length + array.length) * 2; } for (var index = 0; index < array.length; index++) { var item = (array.data || array)[index]; this.pushNoDuplicate(item); } }; return SmartArrayNoDuplicate; }(SmartArray)); BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.smartArray.js.map var BABYLON; (function (BABYLON) { // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work var LoadFileError = /** @class */ (function (_super) { __extends(LoadFileError, _super); function LoadFileError(message, request) { var _this = _super.call(this, message) || this; _this.request = request; _this.name = "LoadFileError"; LoadFileError._setPrototypeOf(_this, LoadFileError.prototype); return _this; } // Polyfill for Object.setPrototypeOf if necessary. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; }); return LoadFileError; }(Error)); BABYLON.LoadFileError = LoadFileError; var RetryStrategy = /** @class */ (function () { function RetryStrategy() { } RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) { if (maxRetries === void 0) { maxRetries = 3; } if (baseInterval === void 0) { baseInterval = 500; } return function (url, request, retryIndex) { if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) { return -1; } return Math.pow(2, retryIndex) * baseInterval; }; }; return RetryStrategy; }()); BABYLON.RetryStrategy = RetryStrategy; // Screenshots var screenshotCanvas; var cloneValue = function (source, destinationObject) { if (!source) return null; if (source instanceof BABYLON.Mesh) { return null; } if (source instanceof BABYLON.SubMesh) { return source.clone(destinationObject); } else if (source.clone) { return source.clone(); } return null; }; var Tools = /** @class */ (function () { function Tools() { } /** * Interpolates between a and b via alpha * @param a The lower value (returned when alpha = 0) * @param b The upper value (returned when alpha = 1) * @param alpha The interpolation-factor * @return The mixed value */ Tools.Mix = function (a, b, alpha) { return a * (1 - alpha) + b * alpha; }; Tools.Instantiate = function (className) { if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) { return Tools.RegisteredExternalClasses[className]; } var arr = className.split("."); var fn = (window || this); for (var i = 0, len = arr.length; i < len; i++) { fn = fn[arr[i]]; } if (typeof fn !== "function") { return null; } return fn; }; /** * Provides a slice function that will work even on IE * @param data defines the array to slice * @param start defines the start of the data (optional) * @param end defines the end of the data (optional) * @returns the new sliced array */ Tools.Slice = function (data, start, end) { if (data.slice) { return data.slice(start, end); } return Array.prototype.slice.call(data, start, end); }; Tools.SetImmediate = function (action) { if (window.setImmediate) { window.setImmediate(action); } else { setTimeout(action, 1); } }; Tools.IsExponentOfTwo = function (value) { var count = 1; do { count *= 2; } while (count < value); return count === value; }; /** * Returns the nearest 32-bit single precision float representation of a Number * @param value A Number. If the parameter is of a different type, it will get converted * to a number or to NaN if it cannot be converted * @returns number */ Tools.FloatRound = function (value) { if (Math.fround) { return Math.fround(value); } return (Tools._tmpFloatArray[0] = value); }; /** * Find the next highest power of two. * @param x Number to start search from. * @return Next highest power of two. */ Tools.CeilingPOT = function (x) { x--; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; x++; return x; }; /** * Find the next lowest power of two. * @param x Number to start search from. * @return Next lowest power of two. */ Tools.FloorPOT = function (x) { x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); x = x | (x >> 8); x = x | (x >> 16); return x - (x >> 1); }; /** * Find the nearest power of two. * @param x Number to start search from. * @return Next nearest power of two. */ Tools.NearestPOT = function (x) { var c = Tools.CeilingPOT(x); var f = Tools.FloorPOT(x); return (c - x) > (x - f) ? f : c; }; Tools.GetExponentOfTwo = function (value, max, mode) { if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; } var pot; switch (mode) { case BABYLON.Engine.SCALEMODE_FLOOR: pot = Tools.FloorPOT(value); break; case BABYLON.Engine.SCALEMODE_NEAREST: pot = Tools.NearestPOT(value); break; case BABYLON.Engine.SCALEMODE_CEILING: default: pot = Tools.CeilingPOT(value); break; } return Math.min(pot, max); }; Tools.GetFilename = function (path) { var index = path.lastIndexOf("/"); if (index < 0) return path; return path.substring(index + 1); }; /** * Extracts the "folder" part of a path (everything before the filename). * @param uri The URI to extract the info from * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present * @returns The "folder" part of the path */ Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) { if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; } var index = uri.lastIndexOf("/"); if (index < 0) { if (returnUnchangedIfNoSlash) { return uri; } return ""; } return uri.substring(0, index + 1); }; Tools.GetDOMTextContent = function (element) { var result = ""; var child = element.firstChild; while (child) { if (child.nodeType === 3) { result += child.textContent; } child = child.nextSibling; } return result; }; Tools.ToDegrees = function (angle) { return angle * 180 / Math.PI; }; Tools.ToRadians = function (angle) { return angle * Math.PI / 180; }; Tools.EncodeArrayBufferTobase64 = function (buffer) { var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; var bytes = new Uint8Array(buffer); while (i < bytes.length) { chr1 = bytes[i++]; chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output += keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); } return "data:image/png;base64," + output; }; Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) { if (bias === void 0) { bias = null; } var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); for (var index = indexStart; index < indexStart + indexCount; index++) { var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]); minimum = BABYLON.Vector3.Minimize(current, minimum); maximum = BABYLON.Vector3.Maximize(current, maximum); } if (bias) { minimum.x -= minimum.x * bias.x + bias.y; minimum.y -= minimum.y * bias.x + bias.y; minimum.z -= minimum.z * bias.x + bias.y; maximum.x += maximum.x * bias.x + bias.y; maximum.y += maximum.y * bias.x + bias.y; maximum.z += maximum.z * bias.x + bias.y; } return { minimum: minimum, maximum: maximum }; }; Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) { if (bias === void 0) { bias = null; } var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); if (!stride) { stride = 3; } for (var index = start; index < start + count; index++) { var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]); minimum = BABYLON.Vector3.Minimize(current, minimum); maximum = BABYLON.Vector3.Maximize(current, maximum); } if (bias) { minimum.x -= minimum.x * bias.x + bias.y; minimum.y -= minimum.y * bias.x + bias.y; minimum.z -= minimum.z * bias.x + bias.y; maximum.x += maximum.x * bias.x + bias.y; maximum.y += maximum.y * bias.x + bias.y; maximum.z += maximum.z * bias.x + bias.y; } return { minimum: minimum, maximum: maximum }; }; Tools.Vector2ArrayFeeder = function (array) { return function (index) { var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined); var length = isFloatArray ? array.length / 2 : array.length; if (index >= length) { return null; } if (isFloatArray) { var fa = array; return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]); } var a = array; return a[index]; }; }; Tools.ExtractMinAndMaxVector2 = function (feeder, bias) { if (bias === void 0) { bias = null; } var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE); var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE); var i = 0; var cur = feeder(i++); while (cur) { minimum = BABYLON.Vector2.Minimize(cur, minimum); maximum = BABYLON.Vector2.Maximize(cur, maximum); cur = feeder(i++); } if (bias) { minimum.x -= minimum.x * bias.x + bias.y; minimum.y -= minimum.y * bias.x + bias.y; maximum.x += maximum.x * bias.x + bias.y; maximum.y += maximum.y * bias.x + bias.y; } return { minimum: minimum, maximum: maximum }; }; Tools.MakeArray = function (obj, allowsNullUndefined) { if (allowsNullUndefined !== true && (obj === undefined || obj == null)) return null; return Array.isArray(obj) ? obj : [obj]; }; // Misc. Tools.GetPointerPrefix = function () { var eventPrefix = "pointer"; // Check if pointer events are supported if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) { eventPrefix = "mouse"; } return eventPrefix; }; /** * @param func - the function to be called * @param requester - the object that will request the next frame. Falls back to window. */ Tools.QueueNewFrame = function (func, requester) { if (!Tools.IsWindowObjectExist()) { return setTimeout(func, 16); } if (!requester) { requester = window; } if (requester.requestAnimationFrame) { return requester.requestAnimationFrame(func); } else if (requester.msRequestAnimationFrame) { return requester.msRequestAnimationFrame(func); } else if (requester.webkitRequestAnimationFrame) { return requester.webkitRequestAnimationFrame(func); } else if (requester.mozRequestAnimationFrame) { return requester.mozRequestAnimationFrame(func); } else if (requester.oRequestAnimationFrame) { return requester.oRequestAnimationFrame(func); } else { return window.setTimeout(func, 16); } }; Tools.RequestFullscreen = function (element) { var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen; if (!requestFunction) return; requestFunction.call(element); }; Tools.ExitFullscreen = function () { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); } else if (document.msCancelFullScreen) { document.msCancelFullScreen(); } }; Tools.SetCorsBehavior = function (url, element) { if (url && url.indexOf("data:") === 0) { return; } if (Tools.CorsBehavior) { if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) { element.crossOrigin = Tools.CorsBehavior; } else { var result = Tools.CorsBehavior(url); if (result) { element.crossOrigin = result; } } } }; // External files Tools.CleanUrl = function (url) { url = url.replace(/#/mg, "%23"); return url; }; /** * Loads an image as an HTMLImageElement. * @param input url string, ArrayBuffer, or Blob to load * @param onLoad callback called when the image successfully loads * @param onError callback called when the image fails to load * @param database database for caching * @returns the HTMLImageElement of the loaded image */ Tools.LoadImage = function (input, onLoad, onError, database) { var url; var usingObjectURL = false; if (input instanceof ArrayBuffer) { url = URL.createObjectURL(new Blob([input])); usingObjectURL = true; } else if (input instanceof Blob) { url = URL.createObjectURL(input); usingObjectURL = true; } else { url = Tools.CleanUrl(input); url = Tools.PreprocessUrl(input); } var img = new Image(); Tools.SetCorsBehavior(url, img); var loadHandler = function () { if (usingObjectURL && img.src) { URL.revokeObjectURL(img.src); } img.removeEventListener("load", loadHandler); img.removeEventListener("error", errorHandler); onLoad(img); }; var errorHandler = function (err) { if (usingObjectURL && img.src) { URL.revokeObjectURL(img.src); } img.removeEventListener("load", loadHandler); img.removeEventListener("error", errorHandler); Tools.Error("Error while trying to load image: " + input); if (onError) { onError("Error while trying to load image: " + input, err); } }; img.addEventListener("load", loadHandler); img.addEventListener("error", errorHandler); var noIndexedDB = function () { img.src = url; }; var loadFromIndexedDB = function () { if (database) { database.loadImageFromDB(url, img); } }; //ANY database to do! if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) { database.openAsync(loadFromIndexedDB, noIndexedDB); } else { if (url.indexOf("file:") !== -1) { var textureName = decodeURIComponent(url.substring(5).toLowerCase()); if (BABYLON.FilesInput.FilesToLoad[textureName]) { try { var blobURL; try { blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true }); } catch (ex) { // Chrome doesn't support oneTimeOnly parameter blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]); } img.src = blobURL; usingObjectURL = true; } catch (e) { img.src = ""; } return img; } } noIndexedDB(); } return img; }; Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) { url = Tools.CleanUrl(url); url = Tools.PreprocessUrl(url); // If file and file input are set if (url.indexOf("file:") !== -1) { var fileName = decodeURIComponent(url.substring(5).toLowerCase()); if (BABYLON.FilesInput.FilesToLoad[fileName]) { return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer); } } var loadUrl = Tools.BaseUrl + url; var aborted = false; var fileRequest = { onCompleteObservable: new BABYLON.Observable(), abort: function () { return aborted = true; }, }; var requestFile = function () { var request = new XMLHttpRequest(); var retryHandle = null; fileRequest.abort = function () { aborted = true; if (request.readyState !== (XMLHttpRequest.DONE || 4)) { request.abort(); } if (retryHandle !== null) { clearTimeout(retryHandle); retryHandle = null; } }; var retryLoop = function (retryIndex) { request.open('GET', loadUrl, true); if (useArrayBuffer) { request.responseType = "arraybuffer"; } if (onProgress) { request.addEventListener("progress", onProgress); } var onLoadEnd = function () { request.removeEventListener("loadend", onLoadEnd); fileRequest.onCompleteObservable.notifyObservers(fileRequest); fileRequest.onCompleteObservable.clear(); }; request.addEventListener("loadend", onLoadEnd); var onReadyStateChange = function () { if (aborted) { return; } // In case of undefined state in some browsers. if (request.readyState === (XMLHttpRequest.DONE || 4)) { // Some browsers have issues where onreadystatechange can be called multiple times with the same value. request.removeEventListener("readystatechange", onReadyStateChange); if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) { onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL); return; } var retryStrategy = Tools.DefaultRetryStrategy; if (retryStrategy) { var waitTime = retryStrategy(loadUrl, request, retryIndex); if (waitTime !== -1) { // Prevent the request from completing for retry. request.removeEventListener("loadend", onLoadEnd); request = new XMLHttpRequest(); retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime); return; } } var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request); if (onError) { onError(request, e); } else { throw e; } } }; request.addEventListener("readystatechange", onReadyStateChange); request.send(); }; retryLoop(0); }; // Caching all files if (database && database.enableSceneOffline) { var noIndexedDB_1 = function () { if (!aborted) { requestFile(); } }; var loadFromIndexedDB = function () { // TODO: database needs to support aborting and should return a IFileRequest if (aborted) { return; } if (database) { database.loadFileFromDB(url, function (data) { if (!aborted) { onSuccess(data); } fileRequest.onCompleteObservable.notifyObservers(fileRequest); }, onProgress ? function (event) { if (!aborted) { onProgress(event); } } : undefined, noIndexedDB_1, useArrayBuffer); } }; database.openAsync(loadFromIndexedDB, noIndexedDB_1); } else { requestFile(); } return fileRequest; }; /** * Load a script (identified by an url). When the url returns, the * content of this file is added into a new script element, attached to the DOM (body element) */ Tools.LoadScript = function (scriptUrl, onSuccess, onError) { var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = scriptUrl; script.onload = function () { if (onSuccess) { onSuccess(); } }; script.onerror = function (e) { if (onError) { onError("Unable to load script '" + scriptUrl + "'", e); } }; head.appendChild(script); }; Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) { var reader = new FileReader(); var request = { onCompleteObservable: new BABYLON.Observable(), abort: function () { return reader.abort(); }, }; reader.onloadend = function (e) { request.onCompleteObservable.notifyObservers(request); }; reader.onload = function (e) { //target doesn't have result from ts 1.3 callback(e.target['result']); }; reader.onprogress = progressCallback; reader.readAsDataURL(fileToLoad); return request; }; Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) { var reader = new FileReader(); var request = { onCompleteObservable: new BABYLON.Observable(), abort: function () { return reader.abort(); }, }; reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); }; reader.onerror = function (e) { Tools.Log("Error while reading file: " + fileToLoad.name); callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] })); }; reader.onload = function (e) { //target doesn't have result from ts 1.3 callback(e.target['result']); }; if (progressCallBack) { reader.onprogress = progressCallBack; } if (!useArrayBuffer) { // Asynchronous read reader.readAsText(fileToLoad); } else { reader.readAsArrayBuffer(fileToLoad); } return request; }; //returns a downloadable url to a file content. Tools.FileAsURL = function (content) { var fileBlob = new Blob([content]); var url = window.URL || window.webkitURL; var link = url.createObjectURL(fileBlob); return link; }; // Misc. Tools.Format = function (value, decimals) { if (decimals === void 0) { decimals = 2; } return value.toFixed(decimals); }; Tools.CheckExtends = function (v, min, max) { if (v.x < min.x) min.x = v.x; if (v.y < min.y) min.y = v.y; if (v.z < min.z) min.z = v.z; if (v.x > max.x) max.x = v.x; if (v.y > max.y) max.y = v.y; if (v.z > max.z) max.z = v.z; }; Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) { for (var prop in source) { if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) { continue; } if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) { continue; } var sourceValue = source[prop]; var typeOfSourceValue = typeof sourceValue; if (typeOfSourceValue === "function") { continue; } try { if (typeOfSourceValue === "object") { if (sourceValue instanceof Array) { destination[prop] = []; if (sourceValue.length > 0) { if (typeof sourceValue[0] == "object") { for (var index = 0; index < sourceValue.length; index++) { var clonedValue = cloneValue(sourceValue[index], destination); if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done destination[prop].push(clonedValue); } } } else { destination[prop] = sourceValue.slice(0); } } } else { destination[prop] = cloneValue(sourceValue, destination); } } else { destination[prop] = sourceValue; } } catch (e) { // Just ignore error (it could be because of a read-only property) } } }; Tools.IsEmpty = function (obj) { for (var i in obj) { if (obj.hasOwnProperty(i)) { return false; } } return true; }; Tools.RegisterTopRootEvents = function (events) { for (var index = 0; index < events.length; index++) { var event = events[index]; window.addEventListener(event.name, event.handler, false); try { if (window.parent) { window.parent.addEventListener(event.name, event.handler, false); } } catch (e) { // Silently fails... } } }; Tools.UnregisterTopRootEvents = function (events) { for (var index = 0; index < events.length; index++) { var event = events[index]; window.removeEventListener(event.name, event.handler); try { if (window.parent) { window.parent.removeEventListener(event.name, event.handler); } } catch (e) { // Silently fails... } } }; Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) { if (mimeType === void 0) { mimeType = "image/png"; } // Read the contents of the framebuffer var numberOfChannelsByLine = width * 4; var halfHeight = height / 2; //Reading datas from WebGL var data = engine.readPixels(0, 0, width, height); //To flip image on Y axis. for (var i = 0; i < halfHeight; i++) { for (var j = 0; j < numberOfChannelsByLine; j++) { var currentCell = j + i * numberOfChannelsByLine; var targetLine = height - i - 1; var targetCell = j + targetLine * numberOfChannelsByLine; var temp = data[currentCell]; data[currentCell] = data[targetCell]; data[targetCell] = temp; } } // Create a 2D canvas to store the result if (!screenshotCanvas) { screenshotCanvas = document.createElement('canvas'); } screenshotCanvas.width = width; screenshotCanvas.height = height; var context = screenshotCanvas.getContext('2d'); if (context) { // Copy the pixels to a 2D canvas var imageData = context.createImageData(width, height); var castData = (imageData.data); castData.set(data); context.putImageData(imageData, 0, 0); Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName); } }; Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) { if (mimeType === void 0) { mimeType = "image/png"; } var base64Image = screenshotCanvas.toDataURL(mimeType); if (successCallback) { successCallback(base64Image); } else { // We need HTMLCanvasElement.toBlob for HD screenshots if (!screenshotCanvas.toBlob) { // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob) screenshotCanvas.toBlob = function (callback, type, quality) { var _this = this; setTimeout(function () { var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len); for (var i = 0; i < len; i++) { arr[i] = binStr.charCodeAt(i); } callback(new Blob([arr], { type: type || 'image/png' })); }); }; } screenshotCanvas.toBlob(function (blob) { //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image. if (("download" in document.createElement("a"))) { if (!fileName) { var date = new Date(); var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2); fileName = "screenshot_" + stringDate + ".png"; } Tools.Download(blob, fileName); } else { var url = URL.createObjectURL(blob); var newWindow = window.open(""); if (!newWindow) return; var img = newWindow.document.createElement("img"); img.onload = function () { // no longer need to read the blob so it's revoked URL.revokeObjectURL(url); }; img.src = url; newWindow.document.body.appendChild(img); } }); } }; /** * Downloads a blob in the browser * @param blob defines the blob to download * @param fileName defines the name of the downloaded file */ Tools.Download = function (blob, fileName) { var url = window.URL.createObjectURL(blob); var a = document.createElement("a"); document.body.appendChild(a); a.style.display = "none"; a.href = url; a.download = fileName; a.addEventListener("click", function () { if (a.parentElement) { a.parentElement.removeChild(a); } }); a.click(); window.URL.revokeObjectURL(url); }; Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) { if (mimeType === void 0) { mimeType = "image/png"; } var width; var height; // If a precision value is specified if (size.precision) { width = Math.round(engine.getRenderWidth() * size.precision); height = Math.round(width / engine.getAspectRatio(camera)); } else if (size.width && size.height) { width = size.width; height = size.height; } //If passing only width, computing height to keep display canvas ratio. else if (size.width && !size.height) { width = size.width; height = Math.round(width / engine.getAspectRatio(camera)); } //If passing only height, computing width to keep display canvas ratio. else if (size.height && !size.width) { height = size.height; width = Math.round(height * engine.getAspectRatio(camera)); } //Assuming here that "size" parameter is a number else if (!isNaN(size)) { height = size; width = size; } else { Tools.Error("Invalid 'size' parameter !"); return; } if (!screenshotCanvas) { screenshotCanvas = document.createElement('canvas'); } screenshotCanvas.width = width; screenshotCanvas.height = height; var renderContext = screenshotCanvas.getContext("2d"); var ratio = engine.getRenderWidth() / engine.getRenderHeight(); var newWidth = width; var newHeight = newWidth / ratio; if (newHeight > height) { newHeight = height; newWidth = newHeight * ratio; } var offsetX = Math.max(0, width - newWidth) / 2; var offsetY = Math.max(0, height - newHeight) / 2; var renderingCanvas = engine.getRenderingCanvas(); if (renderContext && renderingCanvas) { renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight); } Tools.EncodeScreenshotCanvasData(successCallback, mimeType); }; /** * Generates an image screenshot from the specified camera. * * @param engine The engine to use for rendering * @param camera The camera to use for rendering * @param size This parameter can be set to a single number or to an object with the * following (optional) properties: precision, width, height. If a single number is passed, * it will be used for both width and height. If an object is passed, the screenshot size * will be derived from the parameters. The precision property is a multiplier allowing * rendering at a higher or lower resolution. * @param successCallback The callback receives a single parameter which contains the * screenshot as a string of base64-encoded characters. This string can be assigned to the * src parameter of an to display it. * @param mimeType The MIME type of the screenshot image (default: image/png). * Check your browser for supported MIME types. * @param samples Texture samples (default: 1) * @param antialiasing Whether antialiasing should be turned on or not (default: false) * @param fileName A name for for the downloaded file. * @constructor */ Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) { if (mimeType === void 0) { mimeType = "image/png"; } if (samples === void 0) { samples = 1; } if (antialiasing === void 0) { antialiasing = false; } var width; var height; //If a precision value is specified if (size.precision) { width = Math.round(engine.getRenderWidth() * size.precision); height = Math.round(width / engine.getAspectRatio(camera)); size = { width: width, height: height }; } else if (size.width && size.height) { width = size.width; height = size.height; } //If passing only width, computing height to keep display canvas ratio. else if (size.width && !size.height) { width = size.width; height = Math.round(width / engine.getAspectRatio(camera)); size = { width: width, height: height }; } //If passing only height, computing width to keep display canvas ratio. else if (size.height && !size.width) { height = size.height; width = Math.round(height * engine.getAspectRatio(camera)); size = { width: width, height: height }; } //Assuming here that "size" parameter is a number else if (!isNaN(size)) { height = size; width = size; } else { Tools.Error("Invalid 'size' parameter !"); return; } var scene = camera.getScene(); var previousCamera = null; if (scene.activeCamera !== camera) { previousCamera = scene.activeCamera; scene.activeCamera = camera; } //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method) var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE); texture.renderList = null; texture.samples = samples; if (antialiasing) { texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera)); } texture.onAfterRenderObservable.add(function () { Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName); }); scene.incrementRenderId(); scene.resetCachedMaterial(); texture.render(true); texture.dispose(); if (previousCamera) { scene.activeCamera = previousCamera; } camera.getProjectionMatrix(true); // Force cache refresh; }; // XHR response validator for local file scenario Tools.ValidateXHRData = function (xhr, dataType) { // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all if (dataType === void 0) { dataType = 7; } try { if (dataType & 1) { if (xhr.responseText && xhr.responseText.length > 0) { return true; } else if (dataType === 1) { return false; } } if (dataType & 2) { // Check header width and height since there is no "TGA" magic number var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response); if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) { return true; } else if (dataType === 2) { return false; } } if (dataType & 4) { // Check for the "DDS" magic number var ddsHeader = new Uint8Array(xhr.response, 0, 3); if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) { return true; } else { return false; } } } catch (e) { // Global protection } return false; }; /** * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523 * Be aware Math.random() could cause collisions, but: * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide" */ Tools.RandomId = function () { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); }; /** * Test if the given uri is a base64 string. * @param uri The uri to test * @return True if the uri is a base64 string or false otherwise. */ Tools.IsBase64 = function (uri) { return uri.length < 5 ? false : uri.substr(0, 5) === "data:"; }; /** * Decode the given base64 uri. * @param uri The uri to decode * @return The decoded base64 data. */ Tools.DecodeBase64 = function (uri) { var decodedString = atob(uri.split(",")[1]); var bufferLength = decodedString.length; var bufferView = new Uint8Array(new ArrayBuffer(bufferLength)); for (var i = 0; i < bufferLength; i++) { bufferView[i] = decodedString.charCodeAt(i); } return bufferView.buffer; }; Object.defineProperty(Tools, "NoneLogLevel", { get: function () { return Tools._NoneLogLevel; }, enumerable: true, configurable: true }); Object.defineProperty(Tools, "MessageLogLevel", { get: function () { return Tools._MessageLogLevel; }, enumerable: true, configurable: true }); Object.defineProperty(Tools, "WarningLogLevel", { get: function () { return Tools._WarningLogLevel; }, enumerable: true, configurable: true }); Object.defineProperty(Tools, "ErrorLogLevel", { get: function () { return Tools._ErrorLogLevel; }, enumerable: true, configurable: true }); Object.defineProperty(Tools, "AllLogLevel", { get: function () { return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel; }, enumerable: true, configurable: true }); Tools._AddLogEntry = function (entry) { Tools._LogCache = entry + Tools._LogCache; if (Tools.OnNewCacheEntry) { Tools.OnNewCacheEntry(entry); } }; Tools._FormatMessage = function (message) { var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; }; var date = new Date(); return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message; }; Tools._LogDisabled = function (message) { // nothing to do }; Tools._LogEnabled = function (message) { var formattedMessage = Tools._FormatMessage(message); console.log("BJS - " + formattedMessage); var entry = "
" + formattedMessage + "

"; Tools._AddLogEntry(entry); }; Tools._WarnDisabled = function (message) { // nothing to do }; Tools._WarnEnabled = function (message) { var formattedMessage = Tools._FormatMessage(message); console.warn("BJS - " + formattedMessage); var entry = "
" + formattedMessage + "

"; Tools._AddLogEntry(entry); }; Tools._ErrorDisabled = function (message) { // nothing to do }; Tools._ErrorEnabled = function (message) { Tools.errorsCount++; var formattedMessage = Tools._FormatMessage(message); console.error("BJS - " + formattedMessage); var entry = "
" + formattedMessage + "

"; Tools._AddLogEntry(entry); }; Object.defineProperty(Tools, "LogCache", { get: function () { return Tools._LogCache; }, enumerable: true, configurable: true }); Tools.ClearLogCache = function () { Tools._LogCache = ""; Tools.errorsCount = 0; }; Object.defineProperty(Tools, "LogLevels", { set: function (level) { if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) { Tools.Log = Tools._LogEnabled; } else { Tools.Log = Tools._LogDisabled; } if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) { Tools.Warn = Tools._WarnEnabled; } else { Tools.Warn = Tools._WarnDisabled; } if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) { Tools.Error = Tools._ErrorEnabled; } else { Tools.Error = Tools._ErrorDisabled; } }, enumerable: true, configurable: true }); Tools.IsWindowObjectExist = function () { return (typeof window) !== "undefined"; }; Object.defineProperty(Tools, "PerformanceNoneLogLevel", { get: function () { return Tools._PerformanceNoneLogLevel; }, enumerable: true, configurable: true }); Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", { get: function () { return Tools._PerformanceUserMarkLogLevel; }, enumerable: true, configurable: true }); Object.defineProperty(Tools, "PerformanceConsoleLogLevel", { get: function () { return Tools._PerformanceConsoleLogLevel; }, enumerable: true, configurable: true }); Object.defineProperty(Tools, "PerformanceLogLevel", { set: function (level) { if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) { Tools.StartPerformanceCounter = Tools._StartUserMark; Tools.EndPerformanceCounter = Tools._EndUserMark; return; } if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) { Tools.StartPerformanceCounter = Tools._StartPerformanceConsole; Tools.EndPerformanceCounter = Tools._EndPerformanceConsole; return; } Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled; Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled; }, enumerable: true, configurable: true }); Tools._StartPerformanceCounterDisabled = function (counterName, condition) { }; Tools._EndPerformanceCounterDisabled = function (counterName, condition) { }; Tools._StartUserMark = function (counterName, condition) { if (condition === void 0) { condition = true; } if (!Tools._performance) { if (!Tools.IsWindowObjectExist()) { return; } Tools._performance = window.performance; } if (!condition || !Tools._performance.mark) { return; } Tools._performance.mark(counterName + "-Begin"); }; Tools._EndUserMark = function (counterName, condition) { if (condition === void 0) { condition = true; } if (!condition || !Tools._performance.mark) { return; } Tools._performance.mark(counterName + "-End"); Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End"); }; Tools._StartPerformanceConsole = function (counterName, condition) { if (condition === void 0) { condition = true; } if (!condition) { return; } Tools._StartUserMark(counterName, condition); if (console.time) { console.time(counterName); } }; Tools._EndPerformanceConsole = function (counterName, condition) { if (condition === void 0) { condition = true; } if (!condition) { return; } Tools._EndUserMark(counterName, condition); if (console.time) { console.timeEnd(counterName); } }; Object.defineProperty(Tools, "Now", { get: function () { if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) { return window.performance.now(); } return Date.now(); }, enumerable: true, configurable: true }); /** * This method will return the name of the class used to create the instance of the given object. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator. * @param object the object to get the class name from * @return the name of the class, will be "object" for a custom data type not using the @className decorator */ Tools.GetClassName = function (object, isType) { if (isType === void 0) { isType = false; } var name = null; if (!isType && object.getClassName) { name = object.getClassName(); } else { if (object instanceof Object) { var classObj = isType ? object : Object.getPrototypeOf(object); name = classObj.constructor["__bjsclassName__"]; } if (!name) { name = typeof object; } } return name; }; Tools.First = function (array, predicate) { for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { var el = array_1[_i]; if (predicate(el)) { return el; } } return null; }; /** * This method will return the name of the full name of the class, including its owning module (if any). * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified). * @param object the object to get the class name from * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified. */ Tools.getFullClassName = function (object, isType) { if (isType === void 0) { isType = false; } var className = null; var moduleName = null; if (!isType && object.getClassName) { className = object.getClassName(); } else { if (object instanceof Object) { var classObj = isType ? object : Object.getPrototypeOf(object); className = classObj.constructor["__bjsclassName__"]; moduleName = classObj.constructor["__bjsmoduleName__"]; } if (!className) { className = typeof object; } } if (!className) { return null; } return ((moduleName != null) ? (moduleName + ".") : "") + className; }; /** * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method. * @param array */ Tools.arrayOrStringFeeder = function (array) { return function (index) { if (index >= array.length) { return null; } var val = array.charCodeAt ? array.charCodeAt(index) : array[index]; if (val && val.getHashCode) { val = val.getHashCode(); } if (typeof val === "string") { return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val)); } return val; }; }; /** * Compute the hashCode of a stream of number * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code. * @return the hash code computed */ Tools.hashCodeFromStream = function (feeder) { // Based from here: http://stackoverflow.com/a/7616484/802124 var hash = 0; var index = 0; var chr = feeder(index++); while (chr != null) { hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer chr = feeder(index++); } return hash; }; /** * Returns a promise that resolves after the given amount of time. * @param delay Number of milliseconds to delay * @returns Promise that resolves after the given amount of time */ Tools.DelayAsync = function (delay) { return new Promise(function (resolve) { setTimeout(function () { resolve(); }, delay); }); }; Tools.BaseUrl = ""; Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff(); /** * Default behaviour for cors in the application. * It can be a string if the expected behavior is identical in the entire app. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance) */ Tools.CorsBehavior = "anonymous"; Tools.UseFallbackTexture = true; /** * Use this object to register external classes like custom textures or material * to allow the laoders to instantiate them */ Tools.RegisteredExternalClasses = {}; // Used in case of a texture loading problem Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoA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4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z"; Tools._tmpFloatArray = new Float32Array(1); Tools.PreprocessUrl = function (url) { return url; }; // Logs Tools._NoneLogLevel = 0; Tools._MessageLogLevel = 1; Tools._WarningLogLevel = 2; Tools._ErrorLogLevel = 4; Tools._LogCache = ""; Tools.errorsCount = 0; Tools.Log = Tools._LogEnabled; Tools.Warn = Tools._WarnEnabled; Tools.Error = Tools._ErrorEnabled; // Performances Tools._PerformanceNoneLogLevel = 0; Tools._PerformanceUserMarkLogLevel = 1; Tools._PerformanceConsoleLogLevel = 2; Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled; Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled; return Tools; }()); BABYLON.Tools = Tools; /** * This class is used to track a performance counter which is number based. * The user has access to many properties which give statistics of different nature * * The implementer can track two kinds of Performance Counter: time and count * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor. */ var PerfCounter = /** @class */ (function () { function PerfCounter() { this._startMonitoringTime = 0; this._min = 0; this._max = 0; this._average = 0; this._lastSecAverage = 0; this._current = 0; this._totalValueCount = 0; this._totalAccumulated = 0; this._lastSecAccumulated = 0; this._lastSecTime = 0; this._lastSecValueCount = 0; } Object.defineProperty(PerfCounter.prototype, "min", { /** * Returns the smallest value ever */ get: function () { return this._min; }, enumerable: true, configurable: true }); Object.defineProperty(PerfCounter.prototype, "max", { /** * Returns the biggest value ever */ get: function () { return this._max; }, enumerable: true, configurable: true }); Object.defineProperty(PerfCounter.prototype, "average", { /** * Returns the average value since the performance counter is running */ get: function () { return this._average; }, enumerable: true, configurable: true }); Object.defineProperty(PerfCounter.prototype, "lastSecAverage", { /** * Returns the average value of the last second the counter was monitored */ get: function () { return this._lastSecAverage; }, enumerable: true, configurable: true }); Object.defineProperty(PerfCounter.prototype, "current", { /** * Returns the current value */ get: function () { return this._current; }, enumerable: true, configurable: true }); Object.defineProperty(PerfCounter.prototype, "total", { get: function () { return this._totalAccumulated; }, enumerable: true, configurable: true }); Object.defineProperty(PerfCounter.prototype, "count", { get: function () { return this._totalValueCount; }, enumerable: true, configurable: true }); /** * Call this method to start monitoring a new frame. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count. */ PerfCounter.prototype.fetchNewFrame = function () { this._totalValueCount++; this._current = 0; this._lastSecValueCount++; }; /** * Call this method to monitor a count of something (e.g. mesh drawn in viewport count) * @param newCount the count value to add to the monitored count * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics. */ PerfCounter.prototype.addCount = function (newCount, fetchResult) { if (!PerfCounter.Enabled) { return; } this._current += newCount; if (fetchResult) { this._fetchResult(); } }; /** * Start monitoring this performance counter */ PerfCounter.prototype.beginMonitoring = function () { if (!PerfCounter.Enabled) { return; } this._startMonitoringTime = Tools.Now; }; /** * Compute the time lapsed since the previous beginMonitoring() call. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter */ PerfCounter.prototype.endMonitoring = function (newFrame) { if (newFrame === void 0) { newFrame = true; } if (!PerfCounter.Enabled) { return; } if (newFrame) { this.fetchNewFrame(); } var currentTime = Tools.Now; this._current = currentTime - this._startMonitoringTime; if (newFrame) { this._fetchResult(); } }; PerfCounter.prototype._fetchResult = function () { this._totalAccumulated += this._current; this._lastSecAccumulated += this._current; // Min/Max update this._min = Math.min(this._min, this._current); this._max = Math.max(this._max, this._current); this._average = this._totalAccumulated / this._totalValueCount; // Reset last sec? var now = Tools.Now; if ((now - this._lastSecTime) > 1000) { this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount; this._lastSecTime = now; this._lastSecAccumulated = 0; this._lastSecValueCount = 0; } }; PerfCounter.Enabled = true; return PerfCounter; }()); BABYLON.PerfCounter = PerfCounter; /** * Use this className as a decorator on a given class definition to add it a name and optionally its module. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified * @param name The name of the class, case should be preserved * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved. */ function className(name, module) { return function (target) { target["__bjsclassName__"] = name; target["__bjsmoduleName__"] = (module != null) ? module : null; }; } BABYLON.className = className; /** * An implementation of a loop for asynchronous functions. */ var AsyncLoop = /** @class */ (function () { /** * Constroctor. * @param iterations the number of iterations. * @param _fn the function to run each iteration * @param _successCallback the callback that will be called upon succesful execution * @param offset starting offset. */ function AsyncLoop(iterations, _fn, _successCallback, offset) { if (offset === void 0) { offset = 0; } this.iterations = iterations; this._fn = _fn; this._successCallback = _successCallback; this.index = offset - 1; this._done = false; } /** * Execute the next iteration. Must be called after the last iteration was finished. */ AsyncLoop.prototype.executeNext = function () { if (!this._done) { if (this.index + 1 < this.iterations) { ++this.index; this._fn(this); } else { this.breakLoop(); } } }; /** * Break the loop and run the success callback. */ AsyncLoop.prototype.breakLoop = function () { this._done = true; this._successCallback(); }; /** * Helper function */ AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) { if (offset === void 0) { offset = 0; } var loop = new AsyncLoop(iterations, _fn, _successCallback, offset); loop.executeNext(); return loop; }; /** * A for-loop that will run a given number of iterations synchronous and the rest async. * @param iterations total number of iterations * @param syncedIterations number of synchronous iterations in each async iteration. * @param fn the function to call each iteration. * @param callback a success call back that will be called when iterating stops. * @param breakFunction a break condition (optional) * @param timeout timeout settings for the setTimeout function. default - 0. * @constructor */ AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) { if (timeout === void 0) { timeout = 0; } AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) { if (breakFunction && breakFunction()) loop.breakLoop(); else { setTimeout(function () { for (var i = 0; i < syncedIterations; ++i) { var iteration = (loop.index * syncedIterations) + i; if (iteration >= iterations) break; fn(iteration); if (breakFunction && breakFunction()) { loop.breakLoop(); break; } } loop.executeNext(); }, timeout); } }, callback); }; return AsyncLoop; }()); BABYLON.AsyncLoop = AsyncLoop; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.tools.js.map var BABYLON; (function (BABYLON) { var PromiseStates; (function (PromiseStates) { PromiseStates[PromiseStates["Pending"] = 0] = "Pending"; PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled"; PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected"; })(PromiseStates || (PromiseStates = {})); var FulFillmentAgregator = /** @class */ (function () { function FulFillmentAgregator() { this.count = 0; this.target = 0; this.results = []; } return FulFillmentAgregator; }()); var InternalPromise = /** @class */ (function () { function InternalPromise(resolver) { var _this = this; this._state = PromiseStates.Pending; this._children = new Array(); this._rejectWasConsumed = false; if (!resolver) { return; } try { resolver(function (value) { _this._resolve(value); }, function (reason) { _this._reject(reason); }); } catch (e) { this._reject(e); } } Object.defineProperty(InternalPromise.prototype, "_result", { get: function () { return this._resultValue; }, set: function (value) { this._resultValue = value; if (this._parent && this._parent._result === undefined) { this._parent._result = value; } }, enumerable: true, configurable: true }); InternalPromise.prototype.catch = function (onRejected) { return this.then(undefined, onRejected); }; InternalPromise.prototype.then = function (onFulfilled, onRejected) { var _this = this; var newPromise = new InternalPromise(); newPromise._onFulfilled = onFulfilled; newPromise._onRejected = onRejected; // Composition this._children.push(newPromise); newPromise._parent = this; if (this._state !== PromiseStates.Pending) { BABYLON.Tools.SetImmediate(function () { if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) { var returnedValue = newPromise._resolve(_this._result); if (returnedValue !== undefined && returnedValue !== null) { if (returnedValue._state !== undefined) { var returnedPromise = returnedValue; newPromise._children.push(returnedPromise); returnedPromise._parent = newPromise; newPromise = returnedPromise; } else { newPromise._result = returnedValue; } } } else { newPromise._reject(_this._reason); } }); } return newPromise; }; InternalPromise.prototype._moveChildren = function (children) { var _this = this; (_a = this._children).push.apply(_a, children.splice(0, children.length)); this._children.forEach(function (child) { child._parent = _this; }); if (this._state === PromiseStates.Fulfilled) { for (var _i = 0, _b = this._children; _i < _b.length; _i++) { var child = _b[_i]; child._resolve(this._result); } } else if (this._state === PromiseStates.Rejected) { for (var _c = 0, _d = this._children; _c < _d.length; _c++) { var child = _d[_c]; child._reject(this._reason); } } var _a; }; InternalPromise.prototype._resolve = function (value) { try { this._state = PromiseStates.Fulfilled; var returnedValue = null; if (this._onFulfilled) { returnedValue = this._onFulfilled(value); } if (returnedValue !== undefined && returnedValue !== null) { if (returnedValue._state !== undefined) { // Transmit children var returnedPromise = returnedValue; returnedPromise._parent = this; returnedPromise._moveChildren(this._children); value = returnedPromise._result; } else { value = returnedValue; } } this._result = value; for (var _i = 0, _a = this._children; _i < _a.length; _i++) { var child = _a[_i]; child._resolve(value); } this._children.length = 0; delete this._onFulfilled; delete this._onRejected; } catch (e) { this._reject(e, true); } }; InternalPromise.prototype._reject = function (reason, onLocalThrow) { if (onLocalThrow === void 0) { onLocalThrow = false; } this._state = PromiseStates.Rejected; this._reason = reason; if (this._onRejected && !onLocalThrow) { try { this._onRejected(reason); this._rejectWasConsumed = true; } catch (e) { reason = e; } } for (var _i = 0, _a = this._children; _i < _a.length; _i++) { var child = _a[_i]; if (this._rejectWasConsumed) { child._resolve(null); } else { child._reject(reason); } } this._children.length = 0; delete this._onFulfilled; delete this._onRejected; }; InternalPromise.resolve = function (value) { var newPromise = new InternalPromise(); newPromise._resolve(value); return newPromise; }; InternalPromise._RegisterForFulfillment = function (promise, agregator, index) { promise.then(function (value) { agregator.results[index] = value; agregator.count++; if (agregator.count === agregator.target) { agregator.rootPromise._resolve(agregator.results); } return null; }, function (reason) { if (agregator.rootPromise._state !== PromiseStates.Rejected) { agregator.rootPromise._reject(reason); } }); }; InternalPromise.all = function (promises) { var newPromise = new InternalPromise(); var agregator = new FulFillmentAgregator(); agregator.target = promises.length; agregator.rootPromise = newPromise; if (promises.length) { for (var index = 0; index < promises.length; index++) { InternalPromise._RegisterForFulfillment(promises[index], agregator, index); } } else { newPromise._resolve([]); } return newPromise; }; InternalPromise.race = function (promises) { var newPromise = new InternalPromise(); if (promises.length) { for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) { var promise = promises_1[_i]; promise.then(function (value) { if (newPromise) { newPromise._resolve(value); newPromise = null; } return null; }, function (reason) { if (newPromise) { newPromise._reject(reason); newPromise = null; } }); } } return newPromise; }; return InternalPromise; }()); /** * Helper class that provides a small promise polyfill */ var PromisePolyfill = /** @class */ (function () { function PromisePolyfill() { } /** * Static function used to check if the polyfill is required * If this is the case then the function will inject the polyfill to window.Promise * @param force defines a boolean used to force the injection (mostly for testing purposes) */ PromisePolyfill.Apply = function (force) { if (force === void 0) { force = false; } if (force || typeof Promise === 'undefined') { var root = window; root.Promise = InternalPromise; } }; return PromisePolyfill; }()); BABYLON.PromisePolyfill = PromisePolyfill; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.promise.js.map /// var BABYLON; (function (BABYLON) { /** * Helper class to push actions to a pool of workers. */ var WorkerPool = /** @class */ (function () { /** * Constructor * @param workers Array of workers to use for actions */ function WorkerPool(workers) { this._pendingActions = new Array(); this._workerInfos = workers.map(function (worker) { return ({ worker: worker, active: false }); }); } /** * Terminates all workers and clears any pending actions. */ WorkerPool.prototype.dispose = function () { for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) { var workerInfo = _a[_i]; workerInfo.worker.terminate(); } delete this._workerInfos; delete this._pendingActions; }; /** * Pushes an action to the worker pool. If all the workers are active, the action will be * pended until a worker has completed its action. * @param action The action to perform. Call onComplete when the action is complete. */ WorkerPool.prototype.push = function (action) { for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) { var workerInfo = _a[_i]; if (!workerInfo.active) { this._execute(workerInfo, action); return; } } this._pendingActions.push(action); }; WorkerPool.prototype._execute = function (workerInfo, action) { var _this = this; workerInfo.active = true; action(workerInfo.worker, function () { workerInfo.active = false; var nextAction = _this._pendingActions.shift(); if (nextAction) { _this._execute(workerInfo, nextAction); } }); }; return WorkerPool; }()); BABYLON.WorkerPool = WorkerPool; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.workerPool.js.map var BABYLON; (function (BABYLON) { /** * @hidden **/ var _AlphaState = /** @class */ (function () { /** * Initializes the state. */ function _AlphaState() { this._isAlphaBlendDirty = false; this._isBlendFunctionParametersDirty = false; this._isBlendEquationParametersDirty = false; this._isBlendConstantsDirty = false; this._alphaBlend = false; this._blendFunctionParameters = new Array(4); this._blendEquationParameters = new Array(2); this._blendConstants = new Array(4); this.reset(); } Object.defineProperty(_AlphaState.prototype, "isDirty", { get: function () { return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty; }, enumerable: true, configurable: true }); Object.defineProperty(_AlphaState.prototype, "alphaBlend", { get: function () { return this._alphaBlend; }, set: function (value) { if (this._alphaBlend === value) { return; } this._alphaBlend = value; this._isAlphaBlendDirty = true; }, enumerable: true, configurable: true }); _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) { if (this._blendConstants[0] === r && this._blendConstants[1] === g && this._blendConstants[2] === b && this._blendConstants[3] === a) { return; } this._blendConstants[0] = r; this._blendConstants[1] = g; this._blendConstants[2] = b; this._blendConstants[3] = a; this._isBlendConstantsDirty = true; }; _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) { if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) { return; } this._blendFunctionParameters[0] = value0; this._blendFunctionParameters[1] = value1; this._blendFunctionParameters[2] = value2; this._blendFunctionParameters[3] = value3; this._isBlendFunctionParametersDirty = true; }; _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) { if (this._blendEquationParameters[0] === rgb && this._blendEquationParameters[1] === alpha) { return; } this._blendEquationParameters[0] = rgb; this._blendEquationParameters[1] = alpha; this._isBlendEquationParametersDirty = true; }; _AlphaState.prototype.reset = function () { this._alphaBlend = false; this._blendFunctionParameters[0] = null; this._blendFunctionParameters[1] = null; this._blendFunctionParameters[2] = null; this._blendFunctionParameters[3] = null; this._blendEquationParameters[0] = null; this._blendEquationParameters[1] = null; this._blendConstants[0] = null; this._blendConstants[1] = null; this._blendConstants[2] = null; this._blendConstants[3] = null; this._isAlphaBlendDirty = true; this._isBlendFunctionParametersDirty = false; this._isBlendEquationParametersDirty = false; this._isBlendConstantsDirty = false; }; _AlphaState.prototype.apply = function (gl) { if (!this.isDirty) { return; } // Alpha blend if (this._isAlphaBlendDirty) { if (this._alphaBlend) { gl.enable(gl.BLEND); } else { gl.disable(gl.BLEND); } this._isAlphaBlendDirty = false; } // Alpha function if (this._isBlendFunctionParametersDirty) { gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]); this._isBlendFunctionParametersDirty = false; } // Alpha equation if (this._isBlendEquationParametersDirty) { gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]); this._isBlendEquationParametersDirty = false; } // Constants if (this._isBlendConstantsDirty) { gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]); this._isBlendConstantsDirty = false; } }; return _AlphaState; }()); BABYLON._AlphaState = _AlphaState; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.alphaCullingState.js.map var BABYLON; (function (BABYLON) { /** * @hidden **/ var _DepthCullingState = /** @class */ (function () { /** * Initializes the state. */ function _DepthCullingState() { this._isDepthTestDirty = false; this._isDepthMaskDirty = false; this._isDepthFuncDirty = false; this._isCullFaceDirty = false; this._isCullDirty = false; this._isZOffsetDirty = false; this._isFrontFaceDirty = false; this.reset(); } Object.defineProperty(_DepthCullingState.prototype, "isDirty", { get: function () { return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty; }, enumerable: true, configurable: true }); Object.defineProperty(_DepthCullingState.prototype, "zOffset", { get: function () { return this._zOffset; }, set: function (value) { if (this._zOffset === value) { return; } this._zOffset = value; this._isZOffsetDirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(_DepthCullingState.prototype, "cullFace", { get: function () { return this._cullFace; }, set: function (value) { if (this._cullFace === value) { return; } this._cullFace = value; this._isCullFaceDirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(_DepthCullingState.prototype, "cull", { get: function () { return this._cull; }, set: function (value) { if (this._cull === value) { return; } this._cull = value; this._isCullDirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(_DepthCullingState.prototype, "depthFunc", { get: function () { return this._depthFunc; }, set: function (value) { if (this._depthFunc === value) { return; } this._depthFunc = value; this._isDepthFuncDirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(_DepthCullingState.prototype, "depthMask", { get: function () { return this._depthMask; }, set: function (value) { if (this._depthMask === value) { return; } this._depthMask = value; this._isDepthMaskDirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(_DepthCullingState.prototype, "depthTest", { get: function () { return this._depthTest; }, set: function (value) { if (this._depthTest === value) { return; } this._depthTest = value; this._isDepthTestDirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(_DepthCullingState.prototype, "frontFace", { get: function () { return this._frontFace; }, set: function (value) { if (this._frontFace === value) { return; } this._frontFace = value; this._isFrontFaceDirty = true; }, enumerable: true, configurable: true }); _DepthCullingState.prototype.reset = function () { this._depthMask = true; this._depthTest = true; this._depthFunc = null; this._cullFace = null; this._cull = null; this._zOffset = 0; this._frontFace = null; this._isDepthTestDirty = true; this._isDepthMaskDirty = true; this._isDepthFuncDirty = false; this._isCullFaceDirty = false; this._isCullDirty = false; this._isZOffsetDirty = false; this._isFrontFaceDirty = false; }; _DepthCullingState.prototype.apply = function (gl) { if (!this.isDirty) { return; } // Cull if (this._isCullDirty) { if (this.cull) { gl.enable(gl.CULL_FACE); } else { gl.disable(gl.CULL_FACE); } this._isCullDirty = false; } // Cull face if (this._isCullFaceDirty) { gl.cullFace(this.cullFace); this._isCullFaceDirty = false; } // Depth mask if (this._isDepthMaskDirty) { gl.depthMask(this.depthMask); this._isDepthMaskDirty = false; } // Depth test if (this._isDepthTestDirty) { if (this.depthTest) { gl.enable(gl.DEPTH_TEST); } else { gl.disable(gl.DEPTH_TEST); } this._isDepthTestDirty = false; } // Depth func if (this._isDepthFuncDirty) { gl.depthFunc(this.depthFunc); this._isDepthFuncDirty = false; } // zOffset if (this._isZOffsetDirty) { if (this.zOffset) { gl.enable(gl.POLYGON_OFFSET_FILL); gl.polygonOffset(this.zOffset, 0); } else { gl.disable(gl.POLYGON_OFFSET_FILL); } this._isZOffsetDirty = false; } // Front face if (this._isFrontFaceDirty) { gl.frontFace(this.frontFace); this._isFrontFaceDirty = false; } }; return _DepthCullingState; }()); BABYLON._DepthCullingState = _DepthCullingState; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.depthCullingState.js.map var BABYLON; (function (BABYLON) { /** * @hidden **/ var _StencilState = /** @class */ (function () { function _StencilState() { this._isStencilTestDirty = false; this._isStencilMaskDirty = false; this._isStencilFuncDirty = false; this._isStencilOpDirty = false; this.reset(); } Object.defineProperty(_StencilState.prototype, "isDirty", { get: function () { return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty; }, enumerable: true, configurable: true }); Object.defineProperty(_StencilState.prototype, "stencilFunc", { get: function () { return this._stencilFunc; }, set: function (value) { if (this._stencilFunc === value) { return; } this._stencilFunc = value; this._isStencilFuncDirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(_StencilState.prototype, "stencilFuncRef", { get: function () { return this._stencilFuncRef; }, set: function (value) { if (this._stencilFuncRef === value) { return; } this._stencilFuncRef = value; this._isStencilFuncDirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(_StencilState.prototype, "stencilFuncMask", { get: function () { return this._stencilFuncMask; }, set: function (value) { if (this._stencilFuncMask === value) { return; } this._stencilFuncMask = value; this._isStencilFuncDirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", { get: function () { return this._stencilOpStencilFail; }, set: function (value) { if (this._stencilOpStencilFail === value) { return; } this._stencilOpStencilFail = value; this._isStencilOpDirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", { get: function () { return this._stencilOpDepthFail; }, set: function (value) { if (this._stencilOpDepthFail === value) { return; } this._stencilOpDepthFail = value; this._isStencilOpDirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", { get: function () { return this._stencilOpStencilDepthPass; }, set: function (value) { if (this._stencilOpStencilDepthPass === value) { return; } this._stencilOpStencilDepthPass = value; this._isStencilOpDirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(_StencilState.prototype, "stencilMask", { get: function () { return this._stencilMask; }, set: function (value) { if (this._stencilMask === value) { return; } this._stencilMask = value; this._isStencilMaskDirty = true; }, enumerable: true, configurable: true }); Object.defineProperty(_StencilState.prototype, "stencilTest", { get: function () { return this._stencilTest; }, set: function (value) { if (this._stencilTest === value) { return; } this._stencilTest = value; this._isStencilTestDirty = true; }, enumerable: true, configurable: true }); _StencilState.prototype.reset = function () { this._stencilTest = false; this._stencilMask = 0xFF; this._stencilFunc = BABYLON.Engine.ALWAYS; this._stencilFuncRef = 1; this._stencilFuncMask = 0xFF; this._stencilOpStencilFail = BABYLON.Engine.KEEP; this._stencilOpDepthFail = BABYLON.Engine.KEEP; this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE; this._isStencilTestDirty = true; this._isStencilMaskDirty = true; this._isStencilFuncDirty = true; this._isStencilOpDirty = true; }; _StencilState.prototype.apply = function (gl) { if (!this.isDirty) { return; } // Stencil test if (this._isStencilTestDirty) { if (this.stencilTest) { gl.enable(gl.STENCIL_TEST); } else { gl.disable(gl.STENCIL_TEST); } this._isStencilTestDirty = false; } // Stencil mask if (this._isStencilMaskDirty) { gl.stencilMask(this.stencilMask); this._isStencilMaskDirty = false; } // Stencil func if (this._isStencilFuncDirty) { gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask); this._isStencilFuncDirty = false; } // Stencil op if (this._isStencilOpDirty) { gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass); this._isStencilOpDirty = false; } }; return _StencilState; }()); BABYLON._StencilState = _StencilState; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.stencilState.js.map var __assign = (this && this.__assign) || Object.assign || function(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; }; var BABYLON; (function (BABYLON) { var compileShader = function (gl, source, type, defines, shaderVersion) { return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type); }; var compileRawShader = function (gl, source, type) { var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER); gl.shaderSource(shader, source); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { var log = gl.getShaderInfoLog(shader); if (log) { throw new Error(log); } } if (!shader) { throw new Error("Something went wrong while compile the shader."); } return shader; }; var getSamplingParameters = function (samplingMode, generateMipMaps, gl) { var magFilter = gl.NEAREST; var minFilter = gl.NEAREST; switch (samplingMode) { case BABYLON.Texture.BILINEAR_SAMPLINGMODE: magFilter = gl.LINEAR; if (generateMipMaps) { minFilter = gl.LINEAR_MIPMAP_NEAREST; } else { minFilter = gl.LINEAR; } break; case BABYLON.Texture.TRILINEAR_SAMPLINGMODE: magFilter = gl.LINEAR; if (generateMipMaps) { minFilter = gl.LINEAR_MIPMAP_LINEAR; } else { minFilter = gl.LINEAR; } break; case BABYLON.Texture.NEAREST_SAMPLINGMODE: magFilter = gl.NEAREST; if (generateMipMaps) { minFilter = gl.NEAREST_MIPMAP_LINEAR; } else { minFilter = gl.NEAREST; } break; case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST: magFilter = gl.NEAREST; if (generateMipMaps) { minFilter = gl.NEAREST_MIPMAP_NEAREST; } else { minFilter = gl.NEAREST; } break; case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST: magFilter = gl.NEAREST; if (generateMipMaps) { minFilter = gl.LINEAR_MIPMAP_NEAREST; } else { minFilter = gl.LINEAR; } break; case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR: magFilter = gl.NEAREST; if (generateMipMaps) { minFilter = gl.LINEAR_MIPMAP_LINEAR; } else { minFilter = gl.LINEAR; } break; case BABYLON.Texture.NEAREST_LINEAR: magFilter = gl.NEAREST; minFilter = gl.LINEAR; break; case BABYLON.Texture.NEAREST_NEAREST: magFilter = gl.NEAREST; minFilter = gl.NEAREST; break; case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST: magFilter = gl.LINEAR; if (generateMipMaps) { minFilter = gl.NEAREST_MIPMAP_NEAREST; } else { minFilter = gl.NEAREST; } break; case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR: magFilter = gl.LINEAR; if (generateMipMaps) { minFilter = gl.NEAREST_MIPMAP_LINEAR; } else { minFilter = gl.NEAREST; } break; case BABYLON.Texture.LINEAR_LINEAR: magFilter = gl.LINEAR; minFilter = gl.LINEAR; break; case BABYLON.Texture.LINEAR_NEAREST: magFilter = gl.LINEAR; minFilter = gl.NEAREST; break; } return { min: minFilter, mag: magFilter }; }; var 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 = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null); if (scene) { scene._addPendingData(img); } }; var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) { if (onError === void 0) { onError = null; } var loadedImages = []; loadedImages._internalCount = 0; for (var index = 0; index < 6; index++) { partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError); } }; var BufferPointer = /** @class */ (function () { function BufferPointer() { } return BufferPointer; }()); /** * Interface for attribute information associated with buffer instanciation */ var InstancingAttributeInfo = /** @class */ (function () { function InstancingAttributeInfo() { } return InstancingAttributeInfo; }()); BABYLON.InstancingAttributeInfo = InstancingAttributeInfo; /** * Define options used to create a render target texture */ var RenderTargetCreationOptions = /** @class */ (function () { function RenderTargetCreationOptions() { } return RenderTargetCreationOptions; }()); BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions; /** * Define options used to create a depth texture */ var DepthTextureCreationOptions = /** @class */ (function () { function DepthTextureCreationOptions() { } return DepthTextureCreationOptions; }()); BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions; /** * Class used to describe the capabilities of the engine relatively to the current browser */ var EngineCapabilities = /** @class */ (function () { function EngineCapabilities() { } return EngineCapabilities; }()); BABYLON.EngineCapabilities = 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 * @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 (Babylon.js will always consider the database is up to date) **/ this.disableManifestCheck = false; /** * Gets the list of created scenes */ this.scenes = new Array(); /** * Gets the list of created postprocesses */ this.postProcesses = new Array(); // Observables /** * Observable event triggered each time the rendering canvas is resized */ this.onResizeObservable = new BABYLON.Observable(); /** * Observable event triggered each time the canvas loses focus */ this.onCanvasBlurObservable = new BABYLON.Observable(); /** * Observable event triggered each time the canvas gains focus */ this.onCanvasFocusObservable = new BABYLON.Observable(); /** * Observable event triggered each time the canvas receives pointerout event */ this.onCanvasPointerOutObservable = new BABYLON.Observable(); /** * Observable event triggered before each texture is initialized */ this.onBeforeTextureInitObservable = new BABYLON.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 BABYLON.Observable(); /** * Observable raised when the engine ends the current frame */ this.onEndFrameObservable = new BABYLON.Observable(); /** * Observable raised when the engine is about to compile a shader */ this.onBeforeShaderCompilationObservable = new BABYLON.Observable(); /** * Observable raised when the engine has jsut compiled a shader */ this.onAfterShaderCompilationObservable = new BABYLON.Observable(); this._windowIsBackground = false; this._webGLVersion = 1.0; /** @hidden */ this._badOS = false; /** @hidden */ this._badDesktopOS = false; /** * Gets or sets a value indicating if we want to disable texture binding optmization. * This could be required on some buggy drivers which wants to have textures bound in a progressive order. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is */ this.disableTextureBindingOptimization = false; /** * Observable signaled when VR display mode changes */ this.onVRDisplayChangedObservable = new BABYLON.Observable(); /** * Observable signaled when VR request present is complete */ this.onVRRequestPresentComplete = new BABYLON.Observable(); /** * Observable signaled when VR request present starts */ this.onVRRequestPresentStart = new BABYLON.Observable(); this._colorWrite = true; /** @hidden */ this._drawCalls = new BABYLON.PerfCounter(); /** @hidden */ this._textureCollisions = new BABYLON.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 BABYLON.Observable(); /** * Observable signaled when a context restored event is raised */ this.onContextRestoredObservable = new BABYLON.Observable(); this._contextWasLost = false; this._doNotHandleContextLost = false; // FPS this._performanceMonitor = new BABYLON.PerformanceMonitor(); this._fps = 60; this._deltaTime = 0; /** * Turn this value on if you want to pause FPS computation when in background */ this.disablePerformanceMonitorInBackground = false; // States /** @hidden */ this._depthCullingState = new BABYLON._DepthCullingState(); /** @hidden */ this._stencilState = new BABYLON._StencilState(); /** @hidden */ this._alphaState = new BABYLON._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(); this._currentBufferPointers = new Array(); this._currentInstanceLocations = new Array(); this._currentInstanceBuffers = new Array(); this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker(); this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker(); 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._onVRFullScreenTriggered = function () { if (_this._vrDisplay && _this._vrDisplay.isPresenting) { //get the old size before we change _this._oldSize = new BABYLON.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._boundUniforms = {}; // Register promises BABYLON.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; if (ua.indexOf(key) > -1) { 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 "textureBindingOptimization": this.disableTextureBindingOptimization = 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; } } 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"); } 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); }; 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; BABYLON.Tools.Warn("WebGL context lost."); _this.onContextLostObservable.notifyObservers(_this); }; this._onContextRestored = function (evt) { // 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); BABYLON.Tools.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); } } else { this._gl = canvasOrContext; this._renderingCanvas = this._gl.canvas; if (this._gl.renderbufferStorageMultisample) { this._webGLVersion = 2.0; } options.stencil = this._gl.getContextAttributes().stencil; } // Viewport var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0; this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0; this.resize(); this._isStencilEnable = options.stencil ? true : false; this._initGLContext(); if (canvas) { // Fullscreen this._onFullscreenChange = function () { if (document.fullscreen !== undefined) { _this.isFullscreen = document.fullscreen; } else if (document.mozFullScreen !== undefined) { _this.isFullscreen = document.mozFullScreen; } else if (document.webkitIsFullScreen !== undefined) { _this.isFullscreen = document.webkitIsFullScreen; } else if (document.msIsFullScreen !== undefined) { _this.isFullscreen = document.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 = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.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 () { document.exitPointerLock(); }; window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false); window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false); } if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) { Engine.audioEngine = new BABYLON.AudioEngine(); } // Prepare buffer pointers for (var i = 0; i < this._caps.maxVertexAttribs; i++) { this._currentBufferPointers[i] = new BufferPointer(); } this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker); // 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 engine (v" + Engine.Version + ") launched"); this.enableOfflineSupport = (BABYLON.Database !== undefined); } Object.defineProperty(Engine, "LastCreatedEngine", { /** * Gets the latest created engine */ get: function () { if (Engine.Instances.length === 0) { return null; } return Engine.Instances[Engine.Instances.length - 1]; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "LastCreatedScene", { /** * Gets the latest created scene */ get: function () { var lastCreatedEngine = Engine.LastCreatedEngine; if (!lastCreatedEngine) { return null; } if (lastCreatedEngine.scenes.length === 0) { return null; } return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1]; }, 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, "NEVER", { /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */ get: function () { return Engine._NEVER; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "ALWAYS", { /** 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 */ get: function () { return Engine._ALWAYS; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "LESS", { /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */ get: function () { return Engine._LESS; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "EQUAL", { /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */ get: function () { return Engine._EQUAL; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "LEQUAL", { /** 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 */ get: function () { return Engine._LEQUAL; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "GREATER", { /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */ get: function () { return Engine._GREATER; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "GEQUAL", { /** 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 */ get: function () { return Engine._GEQUAL; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "NOTEQUAL", { /** 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 */ get: function () { return Engine._NOTEQUAL; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "KEEP", { /** Passed to stencilOperation to specify that stencil value must be kept */ get: function () { return Engine._KEEP; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "REPLACE", { /** Passed to stencilOperation to specify that stencil value must be replaced */ get: function () { return Engine._REPLACE; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "INCR", { /** Passed to stencilOperation to specify that stencil value must be incremented */ get: function () { return Engine._INCR; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "DECR", { /** Passed to stencilOperation to specify that stencil value must be decremented */ get: function () { return Engine._DECR; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "INVERT", { /** Passed to stencilOperation to specify that stencil value must be inverted */ get: function () { return Engine._INVERT; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "INCR_WRAP", { /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */ get: function () { return Engine._INCR_WRAP; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "DECR_WRAP", { /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */ get: function () { return Engine._DECR_WRAP; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "ALPHA_DISABLE", { // Alpha /** Defines that alpha blending is disabled */ get: function () { return Engine._ALPHA_DISABLE; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "ALPHA_ONEONE", { /** Defines that alpha blending to SRC + DEST */ get: function () { return Engine._ALPHA_ONEONE; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "ALPHA_ADD", { /** Defines that alpha blending to SRC ALPHA * SRC + DEST */ get: function () { return Engine._ALPHA_ADD; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "ALPHA_COMBINE", { /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */ get: function () { return Engine._ALPHA_COMBINE; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "ALPHA_SUBTRACT", { /** Defines that alpha blending to DEST - SRC * DEST */ get: function () { return Engine._ALPHA_SUBTRACT; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "ALPHA_MULTIPLY", { /** Defines that alpha blending to SRC * DEST */ get: function () { return Engine._ALPHA_MULTIPLY; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "ALPHA_MAXIMIZED", { /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */ get: function () { return Engine._ALPHA_MAXIMIZED; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", { /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */ get: function () { return Engine._ALPHA_PREMULTIPLIED; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", { /** * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA */ get: function () { return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "ALPHA_INTERPOLATE", { /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */ get: function () { return Engine._ALPHA_INTERPOLATE; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "ALPHA_SCREENMODE", { /** * Defines that alpha blending to SRC + (1 - SRC) * DEST * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA */ get: function () { return Engine._ALPHA_SCREENMODE; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", { // Delays /** Defines that the ressource is not delayed*/ get: function () { return Engine._DELAYLOADSTATE_NONE; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", { /** Defines that the ressource was successfully delay loaded */ get: function () { return Engine._DELAYLOADSTATE_LOADED; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", { /** Defines that the ressource is currently delay loading */ get: function () { return Engine._DELAYLOADSTATE_LOADING; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", { /** Defines that the ressource is delayed and has not started loading */ get: function () { return Engine._DELAYLOADSTATE_NOTLOADED; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", { /** ALPHA */ get: function () { return Engine._TEXTUREFORMAT_ALPHA; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", { /** LUMINANCE */ get: function () { return Engine._TEXTUREFORMAT_LUMINANCE; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "TEXTUREFORMAT_R", { /** * R */ get: function () { return Engine._TEXTUREFORMAT_R; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "TEXTUREFORMAT_RG", { /** * RG */ get: function () { return Engine._TEXTUREFORMAT_RG; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", { /** LUMINANCE_ALPHA */ get: function () { return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", { /** RGB */ get: function () { return Engine._TEXTUREFORMAT_RGB; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", { /** RGBA */ get: function () { return Engine._TEXTUREFORMAT_RGBA; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", { /** UNSIGNED_INT */ get: function () { return Engine._TEXTURETYPE_UNSIGNED_INT; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", { /** FLOAT */ get: function () { return Engine._TEXTURETYPE_FLOAT; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", { /** HALF_FLOAT */ get: function () { return Engine._TEXTURETYPE_HALF_FLOAT; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "SCALEMODE_FLOOR", { /** Defines that texture rescaling will use a floor to find the closer power of 2 size */ get: function () { return Engine._SCALEMODE_FLOOR; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "SCALEMODE_NEAREST", { /** Defines that texture rescaling will look for the nearest power of 2 size */ get: function () { return Engine._SCALEMODE_NEAREST; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "SCALEMODE_CEILING", { /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */ get: function () { return Engine._SCALEMODE_CEILING; }, enumerable: true, configurable: true }); Object.defineProperty(Engine, "Version", { /** * Returns the current version of the framework */ get: function () { return "3.3.0-alpha.6"; }, enumerable: true, configurable: true }); 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, "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, BABYLON.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, BABYLON.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, BABYLON.Texture.NEAREST_SAMPLINGMODE); } return this._emptyCubeTexture; }, enumerable: true, configurable: true }); 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(); } BABYLON.Effect.ResetCache(); }; 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 = true; 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; // 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; } } // 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._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 highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT); if (highp) { this._caps.highPrecisionShaderSupported = 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; } var boundTexture = this._boundTexturesCache[key]; if (boundTexture) { this._removeDesignatedSlot(boundTexture); } this._boundTexturesCache[key] = null; } if (!this.disableTextureBindingOptimization) { this._nextFreeTextureSlots = []; for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) { this._nextFreeTextureSlots.push(slot); } } 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; }; Object.defineProperty(Engine.prototype, "drawCalls", { /** @hidden */ get: function () { BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class"); return 0; }, enumerable: true, configurable: true }); Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", { /** @hidden */ get: function () { BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class"); return null; }, enumerable: true, configurable: true }); /** * 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; }; /** * 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 var requester = null; if (this._vrDisplay && this._vrDisplay.isPresenting) requester = this._vrDisplay; this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester); } 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 = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction); } }; /** * Toggle full screen mode * @param requestPointerLock defines if a pointer lock should be requested from the user * @param options defines an option object to be sent to the requestFullscreen function */ Engine.prototype.switchFullscreen = function (requestPointerLock) { if (this.isFullscreen) { BABYLON.Tools.ExitFullscreen(); } else { this._pointerLockRequested = requestPointerLock; if (this._renderingCanvas) { BABYLON.Tools.RequestFullscreen(this._renderingCanvas); } } }; /** * 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) { var gl = this._gl; // Save state var curScissor = gl.getParameter(gl.SCISSOR_TEST); var curScissorBox = gl.getParameter(gl.SCISSOR_BOX); // Change state gl.enable(gl.SCISSOR_TEST); gl.scissor(x, y, width, height); // Clear this.clear(clearColor, true, true, true); // Restore state gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]); if (curScissor === true) { gl.enable(gl.SCISSOR_TEST); } else { gl.disable(gl.SCISSOR_TEST); } }; /** * 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._gl.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._gl.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. this._vrDisplay.submitFrame(); } 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 = BABYLON.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, rej) { 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); } } gl.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 { data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, 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 ? BABYLON.Material.TriangleFillMode : BABYLON.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(BABYLON.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 ? BABYLON.Material.TriangleFillMode : BABYLON.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 BABYLON.Material.TriangleFillMode: return this._gl.TRIANGLES; case BABYLON.Material.PointFillMode: return this._gl.POINTS; case BABYLON.Material.WireFrameFillMode: return this._gl.LINES; // Draw modes case BABYLON.Material.PointListDrawMode: return this._gl.POINTS; case BABYLON.Material.LineListDrawMode: return this._gl.LINES; case BABYLON.Material.LineLoopDrawMode: return this._gl.LINE_LOOP; case BABYLON.Material.LineStripDrawMode: return this._gl.LINE_STRIP; case BABYLON.Material.TriangleStripDrawMode: return this._gl.TRIANGLE_STRIP; case BABYLON.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 BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters); effect._key = name; this._compiledEffects[name] = effect; return effect; }; /** * Create an effect to use with particle systems * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx) * @param uniformsNames defines a list of attribute names * @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 * @returns the new Effect */ Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) { if (uniformsNames === void 0) { uniformsNames = []; } if (samplers === void 0) { samplers = []; } if (defines === void 0) { defines = ""; } return this.createEffect({ vertex: "particles", fragmentElement: fragmentName }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError); }; /** * 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 = compileRawShader(context, vertexCode, "vertex"); var fragmentShader = compileRawShader(context, 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 = compileShader(context, vertexCode, "vertex", defines, shaderVersion); var fragmentShader = compileShader(context, 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"); } 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); } var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS); if (!linked) { context.validateProgram(shaderProgram); var error = context.getProgramInfoLog(shaderProgram); if (error) { throw new Error(error); } } context.deleteShader(vertexShader); context.deleteShader(fragmentShader); return shaderProgram; }; /** * 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) { return; } // Use program this.bindSamplers(effect); this._currentEffect = effect; if (effect.onBind) { effect.onBind(effect); } 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 BABYLON.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 /** * 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; if (bruteForce) { this.resetTextureCache(); this._currentProgram = null; this._stencilState.reset(); this._depthCullingState.reset(); this.setDepthFunctionToLessOrEqual(); this._alphaState.reset(); } 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; }; /** @hidden */ Engine.prototype._createTexture = function () { var texture = this._gl.createTexture(); if (!texture) { throw new Error("Unable to create texture"); } return texture; }; /** * Usually called from BABYLON.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. Ignored for compressed textures. Must be flipped in the file * @param scene needed for loading to the correct scene * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.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 * @returns a InternalTexture for assignment back into BABYLON.Texture */ Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) { var _this = this; if (samplingMode === void 0) { samplingMode = BABYLON.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; } 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 BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL); // establish the file extension, if possible var lastDot = url.lastIndexOf('.'); var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : ""; var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0); var isTGA = (extension.indexOf(".tga") === 0); // determine if a ktx file should be substituted var isKTX = false; if (this._textureFormatInUse && !isBase64 && !fallback) { url = url.substring(0, lastDot) + this._textureFormatInUse; isKTX = true; } 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 onerror = function (message, exception) { if (scene) { scene._removePendingData(texture); } if (onLoadObserver) { texture.onLoadedObservable.remove(onLoadObserver); } // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type if (isKTX) { _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture); } else if (BABYLON.Tools.UseFallbackTexture) { _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture); } if (onError) { onError(message || "Unknown error", exception); } }; var callback = null; // processing for non-image formats if (isKTX || isTGA || isDDS) { if (isKTX) { callback = function (data) { var ktx = new BABYLON.KhronosTextureContainer(data, 1); _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () { ktx.uploadLevels(_this._gl, !noMipmap); return false; }, samplingMode); }; } else if (isTGA) { callback = function (arrayBuffer) { var data = new Uint8Array(arrayBuffer); var header = BABYLON.TGATools.GetTGAHeader(data); _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () { BABYLON.TGATools.UploadContent(_this._gl, data); return false; }, samplingMode); }; } else if (isDDS) { callback = function (data) { var info = BABYLON.DDSTools.GetDDSInfo(data); var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1); _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () { BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1); return false; }, samplingMode); }; } if (!buffer) { this._loadFile(url, function (data) { if (callback) { callback(data); } }, undefined, scene ? scene.database : undefined, true, function (request, exception) { onerror("Unable to load " + (request ? request.responseURL : url, exception)); }); } else { if (callback) { callback(buffer); } } // image format processing } 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, 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; } // Using shaders to rescale because canvas.drawImage is lossy var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP); _this._bindTextureDirectly(gl.TEXTURE_2D, source, 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, texture, scene, internalFormat, function () { _this._releaseTexture(source); _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true); continuationCallback(); }); return true; }, samplingMode); }; if (!fromData || isBase64) { if (buffer instanceof HTMLImageElement) { onload(buffer); } else { BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null); } } else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) { BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : 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: BABYLON.Texture.BILINEAR_SAMPLINGMODE, generateDepthBuffer: false, generateStencilBuffer: false }); if (!this._rescalePostProcess) { this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT); } 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 (BABYLON.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._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0)); 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 (BABYLON.Texture.NEAREST_SAMPLINGMODE by default) * @param compression defines the compression used (null by default) * @param type defines the type fo the data (BABYLON.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 BABYLON.InternalTexture(this, BABYLON.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 = getSamplingParameters(samplingMode, generateMipMaps, this._gl); 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; }; /** * 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 (BABYLON.Texture.NEAREST_SAMPLINGMODE by default) * @returns the dynamic texture inside an InternalTexture */ Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) { var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC); texture.baseWidth = width; texture.baseHeight = height; if (generateMipMaps) { width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width; height = this.needPOTTextures ? BABYLON.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 = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl); 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 */ Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) { if (premulAlpha === void 0) { premulAlpha = false; } if (!texture) { return; } this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true); this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0); 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; } this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true); this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // 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); } 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) { BABYLON.Tools.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 ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.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 = getSamplingParameters(internalTexture.samplingMode, false, gl); 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 BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE); if (!this._caps.depthTextureExtension) { BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware."); return internalTexture; } var internalOptions = __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 BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN); internalTexture.isCube = true; if (this.webGLVersion === 1) { BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1."); return internalTexture; } var internalOptions = __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 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 ? BABYLON.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 = BABYLON.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 = BABYLON.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 = BABYLON.Texture.NEAREST_SAMPLINGMODE; } var gl = this._gl; var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET); this._bindTextureDirectly(gl.TEXTURE_2D, texture, true); var width = size.width || size; var height = size.height || size; var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl); if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) { fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT; BABYLON.Tools.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._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 = BABYLON.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 = BABYLON.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 = BABYLON.Texture.NEAREST_SAMPLINGMODE; } var filters = getSamplingParameters(samplingMode, generateMipMaps, gl); if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) { type = Engine.TEXTURETYPE_UNSIGNED_INT; BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type"); } var texture = new BABYLON.InternalTexture(this, BABYLON.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 BABYLON.InternalTexture(this, BABYLON.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._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) { this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data); }; /** @hidden */ Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) { this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data); }; /** @hidden */ Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) { 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); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, texture.invertY ? 1 : 0); var target = gl.TEXTURE_2D; if (texture.isCube) { var 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 = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.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 = BABYLON.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 = BABYLON.Texture.NEAREST_SAMPLINGMODE; } var gl = this._gl; var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET); this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl); if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) { fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT; BABYLON.Tools.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._generateDepthBuffer = fullOptions.generateDepthBuffer; texture._generateStencilBuffer = fullOptions.generateStencilBuffer; this._internalTexturesCache.push(texture); return texture; }; /** * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection) * @param rootUrl defines the url where the file to load is located * @param scene defines the current scene * @param lodScale defines scale to apply to the mip map selection * @param lodOffset defines offset to apply to the mip map selection * @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 defines wheter or not to create polynomails harmonics for the texture * @returns the cube texture as an InternalTexture */ Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) { 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 = true; } var callback = function (loadData) { if (!loadData) { if (onLoad) { onLoad(null); } return; } var texture = loadData.texture; if (!createPolynomials) { texture._sphericalPolynomial = new BABYLON.SphericalPolynomial(); } else if (loadData.info.sphericalPolynomial) { texture._sphericalPolynomial = loadData.info.sphericalPolynomial; } texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED; if (_this._caps.textureLOD) { // Do not add extra process if texture lod is supported. if (onLoad) { onLoad(texture); } return; } var mipSlices = 3; var gl = _this._gl; var width = loadData.width; if (!width) { return; } var textures = []; for (var i = 0; i < mipSlices; i++) { //compute LOD from even spacing in smoothness (matching shader calculation) var smoothness = i / (mipSlices - 1); var roughness = 1 - smoothness; var minLODIndex = lodOffset; // roughness = 0 var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1 var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness; var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex)); var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP); glTextureFromLod.isCube = true; _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); if (loadData.isDDS) { var info = loadData.info; var data = loadData.data; gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0); BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex); } else { BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far."); } _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); // Wrap in a base texture for easy binding. var lodTexture = new BABYLON.BaseTexture(scene); lodTexture.isCube = true; lodTexture._texture = glTextureFromLod; glTextureFromLod.isReady = true; textures.push(lodTexture); } texture._lodTextureHigh = textures[2]; texture._lodTextureMid = textures[1]; texture._lodTextureLow = textures[0]; if (onLoad) { onLoad(texture); } }; return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset); }; /** * 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 * @returns the cube texture as an InternalTexture */ Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset) { 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; } var gl = this._gl; var texture = new BABYLON.InternalTexture(this, BABYLON.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 isKTX = false; var isDDS = false; var isEnv = false; var lastDot = rootUrl.lastIndexOf('.'); var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : ""); if (this._textureFormatInUse) { extension = this._textureFormatInUse; rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse; isKTX = true; } else { isDDS = (extension === ".dds"); isEnv = (extension === ".env"); } var onerror = function (request, exception) { if (onError && request) { onError(request.status + " " + request.statusText, exception); } }; if (isKTX) { this._loadFile(rootUrl, function (data) { var ktx = new BABYLON.KhronosTextureContainer(data, 6); var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap; _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1); ktx.uploadLevels(_this._gl, !noMipmap); _this.setCubeMapTextureParams(gl, loadMipmap); texture.width = ktx.pixelWidth; texture.height = ktx.pixelHeight; texture.isReady = true; }, undefined, undefined, true, onerror); } else if (isEnv) { this._loadFile(rootUrl, function (data) { data = data; var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data); if (info) { texture.width = info.width; texture.height = info.width; BABYLON.EnvironmentTextureTools.UploadPolynomials(texture, data, info); BABYLON.EnvironmentTextureTools.UploadLevelsAsync(texture, data, info).then(function () { texture.isReady = true; if (onLoad) { onLoad(); } }); } else if (onError) { onError("Can not parse the environment file", null); } }, undefined, undefined, true, onerror); } else if (isDDS) { if (files && files.length === 6) { this._cascadeLoadFiles(scene, function (imgs) { var info; var loadMipmap = false; var width = 0; for (var index = 0; index < imgs.length; index++) { var data = imgs[index]; info = BABYLON.DDSTools.GetDDSInfo(data); loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap; _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0); BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index); if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) { gl.generateMipmap(gl.TEXTURE_CUBE_MAP); } texture.width = info.width; texture.height = info.height; texture.type = info.textureType; width = info.width; } _this.setCubeMapTextureParams(gl, loadMipmap); texture.isReady = true; if (onLoad) { onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture }); } }, files, onError); } else { this._loadFile(rootUrl, function (data) { var info = BABYLON.DDSTools.GetDDSInfo(data); if (createPolynomials) { info.sphericalPolynomial = new BABYLON.SphericalPolynomial(); } var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap; _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0); BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6); if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) { gl.generateMipmap(gl.TEXTURE_CUBE_MAP); } _this.setCubeMapTextureParams(gl, loadMipmap); texture.width = info.width; texture.height = info.height; texture.isReady = true; texture.type = info.textureType; if (onLoad) { onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture }); } }, undefined, undefined, true, onerror); } } else { if (!files) { throw new Error("Cannot load cubemap because files were not defined"); } cascadeLoadImgs(rootUrl, scene, function (imgs) { var width = _this.needPOTTextures ? BABYLON.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); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0); var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA; for (var index = 0; index < faces.length; index++) { _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); } if (!noMipmap) { gl.generateMipmap(gl.TEXTURE_CUBE_MAP); } _this.setCubeMapTextureParams(gl, !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; }; Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) { 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 (BABYLON.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); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0)); 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 || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.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 fo the data (like BABYLON.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 BABYLON.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 BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW); texture.isCube = true; texture.generateMipMaps = generateMipMaps; 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; } var width = size; var height = width; texture.width = width; texture.height = height; // Double check on POT to generate Mips. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.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); } if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) { gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST); } else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) { gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST); } else { var filters = getSamplingParameters(samplingMode, generateMipMaps, gl); 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); 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 BABYLON.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 BABYLON.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 = BABYLON.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); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0); 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 { texture.generateMipMaps = !noMipmap; _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.database, 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._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0)); 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 BABYLON.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 BABYLON.InternalTexture(this, BABYLON.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 = getSamplingParameters(samplingMode, generateMipMaps, this._gl); 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 = getSamplingParameters(samplingMode, !noMipmap, gl); 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 = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; } var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width; var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().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); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0)); 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._moveBoundTextureOnTop = function (internalTexture) { if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) { return; } // Remove this._linkTrackers(internalTexture.previous, internalTexture.next); // Bind last to it this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture); // Bind to dummy this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker); }; Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) { if (!internalTexture) { return -1; } internalTexture._initialSlot = channel; if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel if (channel !== internalTexture._designatedSlot) { this._textureCollisions.addCount(1, false); } } else { if (channel !== internalTexture._designatedSlot) { if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot return internalTexture._designatedSlot; } else { // No slot for this texture, let's pick a new one (if we find a free slot) if (this._nextFreeTextureSlots.length) { return this._nextFreeTextureSlots[0]; } // We need to recycle the oldest bound texture, sorry. this._textureCollisions.addCount(1, false); return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next); } } } return channel; }; Engine.prototype._linkTrackers = function (previous, next) { previous.next = next; next.previous = previous; }; Engine.prototype._removeDesignatedSlot = function (internalTexture) { var currentSlot = internalTexture._designatedSlot; if (currentSlot === -1) { return -1; } internalTexture._designatedSlot = -1; if (this.disableTextureBindingOptimization) { return -1; } // Remove from bound list this._linkTrackers(internalTexture.previous, internalTexture.next); // Free the slot this._boundTexturesCache[currentSlot] = null; this._nextFreeTextureSlots.push(currentSlot); return currentSlot; }; 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; } if (forTextureDataUpdate && texture && texture._designatedSlot > -1) { this._activeChannel = texture._designatedSlot; } var currentTextureBound = this._boundTexturesCache[this._activeChannel]; var isTextureForRendering = texture && texture._initialSlot > -1; if (currentTextureBound !== texture || force) { if (currentTextureBound) { this._removeDesignatedSlot(currentTextureBound); } this._activateCurrentTexture(); this._gl.bindTexture(target, texture ? texture._webGLTexture : null); this._boundTexturesCache[this._activeChannel] = texture; if (texture) { if (!this.disableTextureBindingOptimization) { var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel); if (slotIndex > -1) { this._nextFreeTextureSlots.splice(slotIndex, 1); } this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture); this._linkTrackers(texture, this._lastBoundInternalTextureTracker); } texture._designatedSlot = this._activeChannel; } } else if (forTextureDataUpdate) { this._activateCurrentTexture(); } if (isTextureForRendering && !forTextureDataUpdate) { this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel); } }; /** @hidden */ Engine.prototype._bindTexture = function (channel, texture) { if (channel < 0) { return; } if (texture) { channel = this._getCorrectTextureChannel(channel, texture); } 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 BABYLON.Texture.WRAP_ADDRESSMODE: return this._gl.REPEAT; case BABYLON.Texture.CLAMP_ADDRESSMODE: return this._gl.CLAMP_TO_EDGE; case BABYLON.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) { channel = this._getCorrectTextureChannel(channel, internalTexture); } var needToBind = true; if (this._boundTexturesCache[channel] === internalTexture) { this._moveBoundTextureOnTop(internalTexture); if (!isPartOfTextureArray) { this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel); } needToBind = false; } this._activeChannel = channel; 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 !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.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++) { this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture()); } 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 !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR && internalTexture.samplingMode !== BABYLON.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 BABYLON.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 BABYLON.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 BABYLON.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 BABYLON.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(); // 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.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 (BABYLON.Tools.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(); BABYLON.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 (!BABYLON.Tools.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 (!BABYLON.Tools.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 && BABYLON.DefaultLoadingScreen && this._renderingCanvas) this._loadingScreen = new BABYLON.DefaultLoadingScreen(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) { if (faceIndex === void 0) { faceIndex = -1; } if (level === void 0) { level = 0; } 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; var buffer; switch (readType) { case gl.UNSIGNED_BYTE: buffer = new Uint8Array(4 * width * height); readType = gl.UNSIGNED_BYTE; break; default: 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 (type === Engine.TEXTURETYPE_FLOAT) { return this._gl.FLOAT; } else if (type === Engine.TEXTURETYPE_HALF_FLOAT) { // Add Half Float Constant. return this._gl.HALF_FLOAT_OES; } 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_RGB: internalFormat = this._gl.RGB; break; case Engine.TEXTUREFORMAT_RGBA: internalFormat = this._gl.RGBA; break; case Engine.TEXTUREFORMAT_R: internalFormat = this._gl.RED; break; case Engine.TEXTUREFORMAT_RG: internalFormat = this._gl.RG; break; } return internalFormat; }; /** @hidden */ Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) { if (this._webGLVersion === 1) { if (format !== undefined) { switch (format) { case Engine.TEXTUREFORMAT_LUMINANCE: return this._gl.LUMINANCE; case Engine.TEXTUREFORMAT_ALPHA: return this._gl.ALPHA; } } return this._gl.RGBA; } if (type === Engine.TEXTURETYPE_FLOAT) { if (format !== undefined) { switch (format) { case Engine.TEXTUREFORMAT_R: return this._gl.R32F; case Engine.TEXTUREFORMAT_RG: return this._gl.RG32F; case Engine.TEXTUREFORMAT_RGB: return this._gl.RGB32F; } } return this._gl.RGBA32F; } if (type === Engine.TEXTURETYPE_HALF_FLOAT) { if (format) { switch (format) { case Engine.TEXTUREFORMAT_R: return this._gl.R16F; case Engine.TEXTUREFORMAT_RG: return this._gl.RG16F; case Engine.TEXTUREFORMAT_RGB: return this._gl.RGB16F; } } return this._gl.RGBA16F; } if (format !== undefined) { switch (format) { case Engine.TEXTUREFORMAT_LUMINANCE: return this._gl.LUMINANCE; case Engine.TEXTUREFORMAT_RGB: return this._gl.RGB; case Engine.TEXTUREFORMAT_R: return this._gl.R8; case Engine.TEXTUREFORMAT_RG: return this._gl.RG8; case Engine.TEXTUREFORMAT_ALPHA: return this._gl.ALPHA; } } return this._gl.RGBA; }; ; /** @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; }; ; /** * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function) * @return the new query */ Engine.prototype.createQuery = function () { return this._gl.createQuery(); }; /** * Delete and release a webGL query * @param query defines the query to delete * @return the current engine */ Engine.prototype.deleteQuery = function (query) { this._gl.deleteQuery(query); return this; }; /** * Check if a given query has resolved and got its value * @param query defines the query to check * @returns true if the query got its value */ Engine.prototype.isQueryResultAvailable = function (query) { return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE); }; /** * Gets the value of a given query * @param query defines the query to check * @returns the value of the query */ Engine.prototype.getQueryResult = function (query) { return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT); }; /** * Initiates an occlusion query * @param algorithmType defines the algorithm to use * @param query defines the query to use * @returns the current engine * @see http://doc.babylonjs.com/features/occlusionquery */ Engine.prototype.beginOcclusionQuery = function (algorithmType, query) { var glAlgorithm = this.getGlAlgorithmType(algorithmType); this._gl.beginQuery(glAlgorithm, query); return this; }; /** * Ends an occlusion query * @see http://doc.babylonjs.com/features/occlusionquery * @param algorithmType defines the algorithm to use * @returns the current engine */ Engine.prototype.endOcclusionQuery = function (algorithmType) { var glAlgorithm = this.getGlAlgorithmType(algorithmType); this._gl.endQuery(glAlgorithm); return this; }; /* Time queries */ Engine.prototype._createTimeQuery = function () { var timerQuery = this._caps.timerQuery; if (timerQuery.createQueryEXT) { return timerQuery.createQueryEXT(); } return this.createQuery(); }; Engine.prototype._deleteTimeQuery = function (query) { var timerQuery = this._caps.timerQuery; if (timerQuery.deleteQueryEXT) { timerQuery.deleteQueryEXT(query); return; } this.deleteQuery(query); }; Engine.prototype._getTimeQueryResult = function (query) { var timerQuery = this._caps.timerQuery; if (timerQuery.getQueryObjectEXT) { return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT); } return this.getQueryResult(query); }; Engine.prototype._getTimeQueryAvailability = function (query) { var timerQuery = this._caps.timerQuery; if (timerQuery.getQueryObjectEXT) { return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT); } return this.isQueryResultAvailable(query); }; /** * Starts a time query (used to measure time spent by the GPU on a specific frame) * Please note that only one query can be issued at a time * @returns a time token used to track the time span */ Engine.prototype.startTimeQuery = function () { var timerQuery = this._caps.timerQuery; if (!timerQuery) { return null; } var token = new BABYLON._TimeToken(); this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT); if (this._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; }; /** * Ends a time query * @param token defines the token used to measure the time span * @returns the time spent (in ns) */ Engine.prototype.endTimeQuery = function (token) { var timerQuery = this._caps.timerQuery; if (!timerQuery || !token) { return -1; } if (this._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 (this._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; }; Engine.prototype.getGlAlgorithmType = function (algorithmType) { return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED; }; // Transform feedback /** * Creates a webGL transform feedback object * Please makes sure to check webGLVersion property to check if you are running webGL 2+ * @returns the webGL transform feedback object */ Engine.prototype.createTransformFeedback = function () { return this._gl.createTransformFeedback(); }; /** * Delete a webGL transform feedback object * @param value defines the webGL transform feedback object to delete */ Engine.prototype.deleteTransformFeedback = function (value) { this._gl.deleteTransformFeedback(value); }; /** * Bind a webGL transform feedback object to the webgl context * @param value defines the webGL transform feedback object to bind */ Engine.prototype.bindTransformFeedback = function (value) { this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value); }; /** * Begins a transform feedback operation * @param usePoints defines if points or triangles must be used */ Engine.prototype.beginTransformFeedback = function (usePoints) { if (usePoints === void 0) { usePoints = true; } this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES); }; /** * Ends a transform feedback operation */ Engine.prototype.endTransformFeedback = function () { this._gl.endTransformFeedback(); }; /** * Specify the varyings to use with transform feedback * @param program defines the associated webGL program * @param value defines the list of strings representing the varying names */ Engine.prototype.setTranformFeedbackVaryings = function (program, value) { this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS); }; /** * Bind a webGL buffer for a transform feedback operation * @param value defines the webGL buffer to bind */ Engine.prototype.bindTransformFeedbackBuffer = function (value) { this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value); }; /** @hidden */ Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) { var _this = this; var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, 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, database, useArrayBuffer) { var _this = this; return new Promise(function (resolve, reject) { _this._loadFile(url, function (data) { resolve(data); }, undefined, database, useArrayBuffer, function (request, exception) { reject(exception); }); }); }; Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, 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, scene, 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: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }, { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }, { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] } ]; /** Gets the list of created engines */ Engine.Instances = new Array(); // Const statics Engine._ALPHA_DISABLE = 0; Engine._ALPHA_ADD = 1; Engine._ALPHA_COMBINE = 2; Engine._ALPHA_SUBTRACT = 3; Engine._ALPHA_MULTIPLY = 4; Engine._ALPHA_MAXIMIZED = 5; Engine._ALPHA_ONEONE = 6; Engine._ALPHA_PREMULTIPLIED = 7; Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8; Engine._ALPHA_INTERPOLATE = 9; Engine._ALPHA_SCREENMODE = 10; Engine._DELAYLOADSTATE_NONE = 0; Engine._DELAYLOADSTATE_LOADED = 1; Engine._DELAYLOADSTATE_LOADING = 2; Engine._DELAYLOADSTATE_NOTLOADED = 4; Engine._TEXTUREFORMAT_ALPHA = 0; Engine._TEXTUREFORMAT_LUMINANCE = 1; Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2; Engine._TEXTUREFORMAT_RGB = 4; Engine._TEXTUREFORMAT_RGBA = 5; Engine._TEXTUREFORMAT_R = 6; Engine._TEXTUREFORMAT_RG = 7; Engine._TEXTURETYPE_UNSIGNED_INT = 0; Engine._TEXTURETYPE_FLOAT = 1; Engine._TEXTURETYPE_HALF_FLOAT = 2; // Depht or Stencil test Constants. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn. Engine._ALWAYS = 0x0207; // 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._LESS = 0x0201; // 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._EQUAL = 0x0202; // 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._LEQUAL = 0x0203; // 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._GREATER = 0x0204; // 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._GEQUAL = 0x0206; // 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._NOTEQUAL = 0x0205; // 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. // Stencil Actions Constants. Engine._KEEP = 0x1E00; Engine._REPLACE = 0x1E01; Engine._INCR = 0x1E02; Engine._DECR = 0x1E03; Engine._INVERT = 0x150A; Engine._INCR_WRAP = 0x8507; Engine._DECR_WRAP = 0x8508; // Texture rescaling mode Engine._SCALEMODE_FLOOR = 1; Engine._SCALEMODE_NEAREST = 2; Engine._SCALEMODE_CEILING = 3; // Updatable statics so stick with vars here /** * Gets or sets the epsilon value used by collision engine */ Engine.CollisionsEpsilon = 0.001; /** * Gets or sets the relative url used to load code if using the engine in non-minified mode */ Engine.CodeRepository = "src/"; /** * Gets or sets the relative url used to load shaders if using the engine in non-minified mode */ Engine.ShadersRepository = "src/Shaders/"; return Engine; }()); BABYLON.Engine = Engine; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.engine.js.map var BABYLON; (function (BABYLON) { /** * Node is the basic class for all scene objects (Mesh, Light Camera). */ var Node = /** @class */ (function () { /** * Creates a new Node * @param {string} name - the name and id to be given to this node * @param {BABYLON.Scene} the scene this node will be added to */ function Node(name, scene) { if (scene === void 0) { scene = null; } /** * Gets or sets a string used to store user defined state for the node */ this.state = ""; /** * Gets or sets an object used to store user defined information for the node */ this.metadata = null; /** * Gets or sets a boolean used to define if the node must be serialized */ this.doNotSerialize = false; /** @hidden */ this._isDisposed = false; /** * Gets a list of Animations associated with the node */ this.animations = new Array(); this._ranges = {}; this._isEnabled = true; this._isReady = true; /** @hidden */ this._currentRenderId = -1; this._parentRenderId = -1; this._childRenderId = -1; this._animationPropertiesOverride = null; /** * An event triggered when the mesh is disposed */ this.onDisposeObservable = new BABYLON.Observable(); // Behaviors this._behaviors = new Array(); this.name = name; this.id = name; this._scene = (scene || BABYLON.Engine.LastCreatedScene); this.uniqueId = this._scene.getUniqueId(); this._initCache(); } /** * Gets a boolean indicating if the node has been disposed * @returns true if the node was disposed */ Node.prototype.isDisposed = function () { return this._isDisposed; }; Object.defineProperty(Node.prototype, "parent", { get: function () { return this._parentNode; }, /** * Gets or sets the parent of the node */ set: function (parent) { if (this._parentNode === parent) { return; } // Remove self from list of children of parent if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) { var index = this._parentNode._children.indexOf(this); if (index !== -1) { this._parentNode._children.splice(index, 1); } } // Store new parent this._parentNode = parent; // Add as child to new parent if (this._parentNode) { if (this._parentNode._children === undefined || this._parentNode._children === null) { this._parentNode._children = new Array(); } this._parentNode._children.push(this); } }, enumerable: true, configurable: true }); Object.defineProperty(Node.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 }); /** * Gets a string idenfifying the name of the class * @returns "Node" string */ Node.prototype.getClassName = function () { return "Node"; }; Object.defineProperty(Node.prototype, "onDispose", { /** * Sets a callback that will be raised when the node will be disposed */ set: function (callback) { if (this._onDisposeObserver) { this.onDisposeObservable.remove(this._onDisposeObserver); } this._onDisposeObserver = this.onDisposeObservable.add(callback); }, enumerable: true, configurable: true }); /** * Gets the scene of the node * @returns a {BABYLON.Scene} */ Node.prototype.getScene = function () { return this._scene; }; /** * Gets the engine of the node * @returns a {BABYLON.Engine} */ Node.prototype.getEngine = function () { return this._scene.getEngine(); }; /** * Attach a behavior to the node * @see http://doc.babylonjs.com/features/behaviour * @param behavior defines the behavior to attach * @returns the current Node */ Node.prototype.addBehavior = function (behavior) { var _this = this; var index = this._behaviors.indexOf(behavior); if (index !== -1) { return this; } behavior.init(); if (this._scene.isLoading) { // We defer the attach when the scene will be loaded this._scene.onDataLoadedObservable.addOnce(function () { behavior.attach(_this); }); } else { behavior.attach(this); } this._behaviors.push(behavior); return this; }; /** * Remove an attached behavior * @see http://doc.babylonjs.com/features/behaviour * @param behavior defines the behavior to attach * @returns the current Node */ Node.prototype.removeBehavior = function (behavior) { var index = this._behaviors.indexOf(behavior); if (index === -1) { return this; } this._behaviors[index].detach(); this._behaviors.splice(index, 1); return this; }; Object.defineProperty(Node.prototype, "behaviors", { /** * Gets the list of attached behaviors * @see http://doc.babylonjs.com/features/behaviour */ get: function () { return this._behaviors; }, enumerable: true, configurable: true }); /** * Gets an attached behavior by name * @param name defines the name of the behavior to look for * @see http://doc.babylonjs.com/features/behaviour * @returns null if behavior was not found else the requested behavior */ Node.prototype.getBehaviorByName = function (name) { for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) { var behavior = _a[_i]; if (behavior.name === name) { return behavior; } } return null; }; /** * Returns the world matrix of the node * @returns a matrix containing the node's world matrix */ Node.prototype.getWorldMatrix = function () { return BABYLON.Matrix.Identity(); }; /** @hidden */ Node.prototype._getWorldMatrixDeterminant = function () { return 1; }; // override it in derived class if you add new variables to the cache // and call the parent class method /** @hidden */ Node.prototype._initCache = function () { this._cache = {}; this._cache.parent = undefined; }; /** @hidden */ Node.prototype.updateCache = function (force) { if (!force && this.isSynchronized()) return; this._cache.parent = this.parent; this._updateCache(); }; // override it in derived class if you add new variables to the cache // and call the parent class method if !ignoreParentClass /** @hidden */ Node.prototype._updateCache = function (ignoreParentClass) { }; // override it in derived class if you add new variables to the cache /** @hidden */ Node.prototype._isSynchronized = function () { return true; }; /** @hidden */ Node.prototype._markSyncedWithParent = function () { if (this.parent) { this._parentRenderId = this.parent._childRenderId; } }; /** @hidden */ Node.prototype.isSynchronizedWithParent = function () { if (!this.parent) { return true; } if (this._parentRenderId !== this.parent._childRenderId) { return false; } return this.parent.isSynchronized(); }; /** @hidden */ Node.prototype.isSynchronized = function (updateCache) { var check = this.hasNewParent(); check = check || !this.isSynchronizedWithParent(); check = check || !this._isSynchronized(); if (updateCache) this.updateCache(true); return !check; }; /** @hidden */ Node.prototype.hasNewParent = function (update) { if (this._cache.parent === this.parent) return false; if (update) this._cache.parent = this.parent; return true; }; /** * Is this node ready to be used/rendered * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default) * @return true if the node is ready */ Node.prototype.isReady = function (completeCheck) { if (completeCheck === void 0) { completeCheck = false; } return this._isReady; }; /** * Is this node enabled? * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors * @return whether this node (and its parent) is enabled */ Node.prototype.isEnabled = function (checkAncestors) { if (checkAncestors === void 0) { checkAncestors = true; } if (checkAncestors === false) { return this._isEnabled; } if (this._isEnabled === false) { return false; } if (this.parent !== undefined && this.parent !== null) { return this.parent.isEnabled(checkAncestors); } return true; }; /** * Set the enabled state of this node * @param value defines the new enabled state */ Node.prototype.setEnabled = function (value) { this._isEnabled = value; }; /** * Is this node a descendant of the given node? * The function will iterate up the hierarchy until the ancestor was found or no more parents defined * @param ancestor defines the parent node to inspect * @returns a boolean indicating if this node is a descendant of the given node */ Node.prototype.isDescendantOf = function (ancestor) { if (this.parent) { if (this.parent === ancestor) { return true; } return this.parent.isDescendantOf(ancestor); } return false; }; /** @hidden */ Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) { if (directDescendantsOnly === void 0) { directDescendantsOnly = false; } if (!this._children) { return; } for (var index = 0; index < this._children.length; index++) { var item = this._children[index]; if (!predicate || predicate(item)) { results.push(item); } if (!directDescendantsOnly) { item._getDescendants(results, false, predicate); } } }; /** * Will return all nodes that have this node as ascendant * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored * @return all children nodes of all types */ Node.prototype.getDescendants = function (directDescendantsOnly, predicate) { var results = new Array(); this._getDescendants(results, directDescendantsOnly, predicate); return results; }; /** * Get all child-meshes of this node * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored * @returns an array of {BABYLON.AbstractMesh} */ Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) { var results = []; this._getDescendants(results, directDescendantsOnly, function (node) { return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh)); }); return results; }; /** * Get all child-transformNodes of this node * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored * @returns an array of {BABYLON.TransformNode} */ Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) { var results = []; this._getDescendants(results, directDescendantsOnly, function (node) { return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode)); }); return results; }; /** * Get all direct children of this node * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored * @returns an array of {BABYLON.Node} */ Node.prototype.getChildren = function (predicate) { return this.getDescendants(true, predicate); }; /** @hidden */ Node.prototype._setReady = function (state) { if (state === this._isReady) { return; } if (!state) { this._isReady = false; return; } if (this.onReady) { this.onReady(this); } this._isReady = true; }; /** * Get an animation by name * @param name defines the name of the animation to look for * @returns null if not found else the requested animation */ Node.prototype.getAnimationByName = function (name) { for (var i = 0; i < this.animations.length; i++) { var animation = this.animations[i]; if (animation.name === name) { return animation; } } return null; }; /** * Creates an animation range for this node * @param name defines the name of the range * @param from defines the starting key * @param to defines the end key */ Node.prototype.createAnimationRange = function (name, from, to) { // check name not already in use if (!this._ranges[name]) { this._ranges[name] = new BABYLON.AnimationRange(name, from, to); for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) { if (this.animations[i]) { this.animations[i].createRange(name, from, to); } } } }; /** * Delete a specific animation range * @param name defines the name of the range to delete * @param deleteFrames defines if animation frames from the range must be deleted as well */ Node.prototype.deleteAnimationRange = function (name, deleteFrames) { if (deleteFrames === void 0) { deleteFrames = true; } for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) { if (this.animations[i]) { this.animations[i].deleteRange(name, deleteFrames); } } this._ranges[name] = null; // said much faster than 'delete this._range[name]' }; /** * Get an animation range by name * @param name defines the name of the animation range to look for * @returns null if not found else the requested animation range */ Node.prototype.getAnimationRange = function (name) { return this._ranges[name]; }; /** * Will start the animation sequence * @param name defines the range frames for animation sequence * @param loop defines if the animation should loop (false by default) * @param speedRatio defines the speed factor in which to run the animation (1 by default) * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default) * @returns the object created for this animation. If range does not exist, it will return null */ Node.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); }; /** * Serialize animation ranges into a JSON compatible object * @returns serialization object */ Node.prototype.serializeAnimationRanges = function () { var serializationRanges = []; for (var name in this._ranges) { var localRange = this._ranges[name]; if (!localRange) { continue; } var range = {}; range.name = name; range.from = localRange.from; range.to = localRange.to; serializationRanges.push(range); } return serializationRanges; }; /** * Computes the world matrix of the node * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch * @returns the world matrix */ Node.prototype.computeWorldMatrix = function (force) { return BABYLON.Matrix.Identity(); }; /** * 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) */ Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) { if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; } if (!doNotRecurse) { var nodes = this.getDescendants(true); for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { var node = nodes_1[_i]; node.dispose(doNotRecurse, disposeMaterialAndTextures); } } else { var transformNodes = this.getChildTransformNodes(true); for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) { var transformNode = transformNodes_1[_a]; transformNode.parent = null; transformNode.computeWorldMatrix(true); } } this.parent = null; // Callback this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); // Behaviors for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) { var behavior = _c[_b]; behavior.detach(); } this._behaviors = []; this._isDisposed = true; }; /** * Parse animation range data from a serialization object and store them into a given node * @param node defines where to store the animation ranges * @param parsedNode defines the serialization object to read data from * @param scene defines the hosting scene */ Node.ParseAnimationRanges = function (node, parsedNode, scene) { if (parsedNode.ranges) { for (var index = 0; index < parsedNode.ranges.length; index++) { var data = parsedNode.ranges[index]; node.createAnimationRange(data.name, data.from, data.to); } } }; __decorate([ BABYLON.serialize() ], Node.prototype, "name", void 0); __decorate([ BABYLON.serialize() ], Node.prototype, "id", void 0); __decorate([ BABYLON.serialize() ], Node.prototype, "uniqueId", void 0); __decorate([ BABYLON.serialize() ], Node.prototype, "state", void 0); __decorate([ BABYLON.serialize() ], Node.prototype, "metadata", void 0); return Node; }()); BABYLON.Node = Node; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.node.js.map var BABYLON; (function (BABYLON) { 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) */ function BoundingSphere(min, max) { this._tempRadiusVector = BABYLON.Vector3.Zero(); this.reConstruct(min, max); } /** * Recreates the entire bounding sphere from scratch * @param min defines the new minimum vector (in local space) * @param max defines the new maximum vector (in local space) */ BoundingSphere.prototype.reConstruct = function (min, max) { this.minimum = min.clone(); this.maximum = max.clone(); var distance = BABYLON.Vector3.Distance(min, max); this.center = BABYLON.Vector3.Lerp(min, max, 0.5); this.radius = distance * 0.5; this.centerWorld = BABYLON.Vector3.Zero(); this._update(BABYLON.Matrix.Identity()); }; // Methods BoundingSphere.prototype._update = function (world) { BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld); BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector); this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius; }; BoundingSphere.prototype.isInFrustum = function (frustumPlanes) { for (var i = 0; i < 6; i++) { if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld) return false; } return true; }; BoundingSphere.prototype.intersectsPoint = function (point) { var x = this.centerWorld.x - point.x; var y = this.centerWorld.y - point.y; var z = this.centerWorld.z - point.z; var distance = Math.sqrt((x * x) + (y * y) + (z * z)); if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon) return false; return true; }; // Statics BoundingSphere.Intersects = function (sphere0, sphere1) { var x = sphere0.centerWorld.x - sphere1.centerWorld.x; var y = sphere0.centerWorld.y - sphere1.centerWorld.y; var z = sphere0.centerWorld.z - sphere1.centerWorld.z; var distance = Math.sqrt((x * x) + (y * y) + (z * z)); if (sphere0.radiusWorld + sphere1.radiusWorld < distance) return false; return true; }; return BoundingSphere; }()); BABYLON.BoundingSphere = BoundingSphere; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.boundingSphere.js.map var BABYLON; (function (BABYLON) { 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) */ function BoundingBox(min, max) { this.vectorsWorld = new Array(); this.reConstruct(min, max); } // Methods /** * Recreates the entire bounding box from scratch * @param min defines the new minimum vector (in local space) * @param max defines the new maximum vector (in local space) */ BoundingBox.prototype.reConstruct = function (min, max) { this.minimum = min.clone(); this.maximum = max.clone(); // Bounding vectors this.vectors = new Array(); this.vectors.push(this.minimum.clone()); this.vectors.push(this.maximum.clone()); this.vectors.push(this.minimum.clone()); this.vectors[2].x = this.maximum.x; this.vectors.push(this.minimum.clone()); this.vectors[3].y = this.maximum.y; this.vectors.push(this.minimum.clone()); this.vectors[4].z = this.maximum.z; this.vectors.push(this.maximum.clone()); this.vectors[5].z = this.minimum.z; this.vectors.push(this.maximum.clone()); this.vectors[6].x = this.minimum.x; this.vectors.push(this.maximum.clone()); this.vectors[7].y = this.minimum.y; // OBB this.center = this.maximum.add(this.minimum).scale(0.5); this.extendSize = this.maximum.subtract(this.minimum).scale(0.5); this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()]; // World for (var index = 0; index < this.vectors.length; index++) { this.vectorsWorld[index] = BABYLON.Vector3.Zero(); } this.minimumWorld = BABYLON.Vector3.Zero(); this.maximumWorld = BABYLON.Vector3.Zero(); this.centerWorld = BABYLON.Vector3.Zero(); this.extendSizeWorld = BABYLON.Vector3.Zero(); this._update(this._worldMatrix || BABYLON.Matrix.Identity()); }; BoundingBox.prototype.getWorldMatrix = function () { return this._worldMatrix; }; BoundingBox.prototype.setWorldMatrix = function (matrix) { this._worldMatrix.copyFrom(matrix); return this; }; BoundingBox.prototype._update = function (world) { BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld); BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld); for (var index = 0; index < this.vectors.length; index++) { var v = this.vectorsWorld[index]; BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v); if (v.x < this.minimumWorld.x) this.minimumWorld.x = v.x; if (v.y < this.minimumWorld.y) this.minimumWorld.y = v.y; if (v.z < this.minimumWorld.z) this.minimumWorld.z = v.z; if (v.x > this.maximumWorld.x) this.maximumWorld.x = v.x; if (v.y > this.maximumWorld.y) this.maximumWorld.y = v.y; if (v.z > this.maximumWorld.z) this.maximumWorld.z = v.z; } // Extend this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld); this.extendSizeWorld.scaleInPlace(0.5); // OBB this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld); this.centerWorld.scaleInPlace(0.5); BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]); BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]); BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]); this._worldMatrix = world; }; BoundingBox.prototype.isInFrustum = function (frustumPlanes) { return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes); }; BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) { return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes); }; BoundingBox.prototype.intersectsPoint = function (point) { var delta = -BABYLON.Epsilon; if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x) return false; if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y) return false; if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z) return false; return true; }; BoundingBox.prototype.intersectsSphere = function (sphere) { return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld); }; BoundingBox.prototype.intersectsMinMax = function (min, max) { if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x) return false; if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y) return false; if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z) return false; return true; }; // Statics BoundingBox.Intersects = function (box0, box1) { if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x) return false; if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y) return false; if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z) return false; return true; }; BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) { var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint); var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector); return (num <= (sphereRadius * sphereRadius)); }; BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) { for (var p = 0; p < 6; p++) { for (var i = 0; i < 8; i++) { if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) { return false; } } } return true; }; BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) { for (var p = 0; p < 6; p++) { var inCount = 8; for (var i = 0; i < 8; i++) { if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) { --inCount; } else { break; } } if (inCount === 0) return false; } return true; }; return BoundingBox; }()); BABYLON.BoundingBox = BoundingBox; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.boundingBox.js.map var BABYLON; (function (BABYLON) { var computeBoxExtents = function (axis, box) { var p = BABYLON.Vector3.Dot(box.centerWorld, axis); var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x; var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y; var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z; var r = r0 + r1 + r2; return { min: p - r, max: p + r }; }; var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); }; var axisOverlap = function (axis, box0, box1) { var result0 = computeBoxExtents(axis, box0); var result1 = computeBoxExtents(axis, box1); return extentsOverlap(result0.min, result0.max, result1.min, result1.max); }; var BoundingInfo = /** @class */ (function () { function BoundingInfo(minimum, maximum) { this.minimum = minimum; this.maximum = maximum; this._isLocked = false; this.boundingBox = new BABYLON.BoundingBox(minimum, maximum); this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum); } Object.defineProperty(BoundingInfo.prototype, "isLocked", { get: function () { return this._isLocked; }, set: function (value) { this._isLocked = value; }, enumerable: true, configurable: true }); // Methods 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 */ BoundingInfo.prototype.centerOn = function (center, extend) { this.minimum = center.subtract(extend); this.maximum = center.add(extend); this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum); this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum); return this; }; BoundingInfo.prototype.isInFrustum = function (frustumPlanes) { if (!this.boundingSphere.isInFrustum(frustumPlanes)) return false; 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 size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld); return size.length(); }, enumerable: true, configurable: true }); BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) { return this.boundingBox.isCompletelyInFrustum(frustumPlanes); }; BoundingInfo.prototype._checkCollision = function (collider) { return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld); }; 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; }; BoundingInfo.prototype.intersects = function (boundingInfo, precise) { if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) { return false; } if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) { return false; } if (!BABYLON.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(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1)) return false; if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1)) return false; if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1)) return false; if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1)) return false; if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1)) return false; if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1)) return false; if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1)) return false; if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1)) return false; if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1)) return false; return true; }; return BoundingInfo; }()); BABYLON.BoundingInfo = BoundingInfo; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.boundingInfo.js.map var BABYLON; (function (BABYLON) { var TransformNode = /** @class */ (function (_super) { __extends(TransformNode, _super); function TransformNode(name, scene, isPure) { if (scene === void 0) { scene = null; } if (isPure === void 0) { isPure = true; } var _this = _super.call(this, name, scene) || this; _this._forward = new BABYLON.Vector3(0, 0, 1); _this._forwardInverted = new BABYLON.Vector3(0, 0, -1); _this._up = new BABYLON.Vector3(0, 1, 0); _this._right = new BABYLON.Vector3(1, 0, 0); _this._rightInverted = new BABYLON.Vector3(-1, 0, 0); // Properties _this._rotation = BABYLON.Vector3.Zero(); _this._scaling = BABYLON.Vector3.One(); _this._isDirty = false; /** * Set the billboard mode. Default is 0. * * | Value | Type | Description | * | --- | --- | --- | * | 0 | BILLBOARDMODE_NONE | | * | 1 | BILLBOARDMODE_X | | * | 2 | BILLBOARDMODE_Y | | * | 4 | BILLBOARDMODE_Z | | * | 7 | BILLBOARDMODE_ALL | | * */ _this.billboardMode = TransformNode.BILLBOARDMODE_NONE; _this.scalingDeterminant = 1; _this.infiniteDistance = false; /** * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored. * By default the system will update normals to compensate */ _this.ignoreNonUniformScaling = false; _this.position = BABYLON.Vector3.Zero(); _this._localWorld = BABYLON.Matrix.Zero(); _this._worldMatrix = BABYLON.Matrix.Zero(); _this._worldMatrixDeterminant = 0; _this._absolutePosition = BABYLON.Vector3.Zero(); _this._pivotMatrix = BABYLON.Matrix.Identity(); _this._postMultiplyPivotMatrix = false; _this._isWorldMatrixFrozen = false; /** * An event triggered after the world matrix is updated */ _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable(); _this._nonUniformScaling = false; if (isPure) { _this.getScene().addTransformNode(_this); } return _this; } /** * Gets a string idenfifying the name of the class * @returns "TransformNode" string */ TransformNode.prototype.getClassName = function () { return "TransformNode"; }; Object.defineProperty(TransformNode.prototype, "rotation", { /** * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector! * Default : (0.0, 0.0, 0.0) */ get: function () { return this._rotation; }, set: function (newRotation) { this._rotation = newRotation; }, enumerable: true, configurable: true }); Object.defineProperty(TransformNode.prototype, "scaling", { /** * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z. * Default : (1.0, 1.0, 1.0) */ get: function () { return this._scaling; }, /** * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z. * Default : (1.0, 1.0, 1.0) */ set: function (newScaling) { this._scaling = newScaling; }, enumerable: true, configurable: true }); Object.defineProperty(TransformNode.prototype, "rotationQuaternion", { /** * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion. * It's null by default. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0) */ get: function () { return this._rotationQuaternion; }, set: function (quaternion) { this._rotationQuaternion = quaternion; //reset the rotation vector. if (quaternion && this.rotation.length()) { this.rotation.copyFromFloats(0.0, 0.0, 0.0); } }, enumerable: true, configurable: true }); Object.defineProperty(TransformNode.prototype, "forward", { /** * The forward direction of that transform in world space. */ get: function () { return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix())); }, enumerable: true, configurable: true }); Object.defineProperty(TransformNode.prototype, "up", { /** * The up direction of that transform in world space. */ get: function () { return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix())); }, enumerable: true, configurable: true }); Object.defineProperty(TransformNode.prototype, "right", { /** * The right direction of that transform in world space. */ get: function () { return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix())); }, enumerable: true, configurable: true }); /** * Returns the latest update of the World matrix * Returns a Matrix. */ TransformNode.prototype.getWorldMatrix = function () { if (this._currentRenderId !== this.getScene().getRenderId()) { this.computeWorldMatrix(); } return this._worldMatrix; }; /** @hidden */ TransformNode.prototype._getWorldMatrixDeterminant = function () { return this._worldMatrixDeterminant; }; Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", { /** * Returns directly the latest state of the mesh World matrix. * A Matrix is returned. */ get: function () { return this._worldMatrix; }, enumerable: true, configurable: true }); /** * Copies the paramater passed Matrix into the mesh Pose matrix. * Returns the TransformNode. */ TransformNode.prototype.updatePoseMatrix = function (matrix) { this._poseMatrix.copyFrom(matrix); return this; }; /** * Returns the mesh Pose matrix. * Returned object : Matrix */ TransformNode.prototype.getPoseMatrix = function () { return this._poseMatrix; }; TransformNode.prototype._isSynchronized = function () { if (this._isDirty) { return false; } if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) return false; if (this._cache.pivotMatrixUpdated) { return false; } if (this.infiniteDistance) { return false; } if (!this._cache.position.equals(this.position)) return false; if (this.rotationQuaternion) { if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion)) return false; } if (!this._cache.rotation.equals(this.rotation)) return false; if (!this._cache.scaling.equals(this.scaling)) return false; return true; }; TransformNode.prototype._initCache = function () { _super.prototype._initCache.call(this); this._cache.localMatrixUpdated = false; this._cache.position = BABYLON.Vector3.Zero(); this._cache.scaling = BABYLON.Vector3.Zero(); this._cache.rotation = BABYLON.Vector3.Zero(); this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0); this._cache.billboardMode = -1; }; TransformNode.prototype.markAsDirty = function (property) { if (property === "rotation") { this.rotationQuaternion = null; } this._currentRenderId = Number.MAX_VALUE; this._isDirty = true; return this; }; Object.defineProperty(TransformNode.prototype, "absolutePosition", { /** * Returns the current mesh absolute position. * Retuns a Vector3. */ get: function () { return this._absolutePosition; }, enumerable: true, configurable: true }); /** * Sets a new matrix to apply before all other transformation * @param matrix defines the transform matrix * @returns the current TransformNode */ TransformNode.prototype.setPreTransformMatrix = function (matrix) { return this.setPivotMatrix(matrix, false); }; /** * Sets a new pivot matrix to the current node * @param matrix defines the new pivot matrix to use * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect * @returns the current TransformNode */ TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) { if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; } this._pivotMatrix = matrix.clone(); this._cache.pivotMatrixUpdated = true; this._postMultiplyPivotMatrix = postMultiplyPivotMatrix; if (this._postMultiplyPivotMatrix) { if (!this._pivotMatrixInverse) { this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix); } else { this._pivotMatrix.invertToRef(this._pivotMatrixInverse); } } return this; }; /** * Returns the mesh pivot matrix. * Default : Identity. * A Matrix is returned. */ TransformNode.prototype.getPivotMatrix = function () { return this._pivotMatrix; }; /** * Prevents the World matrix to be computed any longer. * Returns the TransformNode. */ TransformNode.prototype.freezeWorldMatrix = function () { this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily this.computeWorldMatrix(true); this._isWorldMatrixFrozen = true; return this; }; /** * Allows back the World matrix computation. * Returns the TransformNode. */ TransformNode.prototype.unfreezeWorldMatrix = function () { this._isWorldMatrixFrozen = false; this.computeWorldMatrix(true); return this; }; Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", { /** * True if the World matrix has been frozen. * Returns a boolean. */ get: function () { return this._isWorldMatrixFrozen; }, enumerable: true, configurable: true }); /** * Retuns the mesh absolute position in the World. * Returns a Vector3. */ TransformNode.prototype.getAbsolutePosition = function () { this.computeWorldMatrix(); return this._absolutePosition; }; /** * Sets the mesh absolute position in the World from a Vector3 or an Array(3). * Returns the TransformNode. */ TransformNode.prototype.setAbsolutePosition = function (absolutePosition) { if (!absolutePosition) { return this; } var absolutePositionX; var absolutePositionY; var absolutePositionZ; if (absolutePosition.x === undefined) { if (arguments.length < 3) { return this; } absolutePositionX = arguments[0]; absolutePositionY = arguments[1]; absolutePositionZ = arguments[2]; } else { absolutePositionX = absolutePosition.x; absolutePositionY = absolutePosition.y; absolutePositionZ = absolutePosition.z; } if (this.parent) { var invertParentWorldMatrix = this.parent.getWorldMatrix().clone(); invertParentWorldMatrix.invert(); var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ); this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix); } else { this.position.x = absolutePositionX; this.position.y = absolutePositionY; this.position.z = absolutePositionZ; } return this; }; /** * Sets the mesh position in its local space. * Returns the TransformNode. */ TransformNode.prototype.setPositionWithLocalVector = function (vector3) { this.computeWorldMatrix(); this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld); return this; }; /** * Returns the mesh position in the local space from the current World matrix values. * Returns a new Vector3. */ TransformNode.prototype.getPositionExpressedInLocalSpace = function () { this.computeWorldMatrix(); var invLocalWorldMatrix = this._localWorld.clone(); invLocalWorldMatrix.invert(); return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix); }; /** * Translates the mesh along the passed Vector3 in its local space. * Returns the TransformNode. */ TransformNode.prototype.locallyTranslate = function (vector3) { this.computeWorldMatrix(true); this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld); return this; }; /** * Orients a mesh towards a target point. Mesh must be drawn facing user. * @param targetPoint the position (must be in same space as current mesh) to look at * @param yawCor optional yaw (y-axis) correction in radians * @param pitchCor optional pitch (x-axis) correction in radians * @param rollCor optional roll (z-axis) correction in radians * @param space the choosen space of the target * @returns the TransformNode. */ TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) { if (yawCor === void 0) { yawCor = 0; } if (pitchCor === void 0) { pitchCor = 0; } if (rollCor === void 0) { rollCor = 0; } if (space === void 0) { space = BABYLON.Space.LOCAL; } var dv = TransformNode._lookAtVectorCache; var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition(); targetPoint.subtractToRef(pos, dv); var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2; var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z); var pitch = Math.atan2(dv.y, len); if (this.rotationQuaternion) { BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion); } else { this.rotation.x = pitch + pitchCor; this.rotation.y = yaw + yawCor; this.rotation.z = rollCor; } return this; }; /** * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh. * This Vector3 is expressed in the World space. */ TransformNode.prototype.getDirection = function (localAxis) { var result = BABYLON.Vector3.Zero(); this.getDirectionToRef(localAxis, result); return result; }; /** * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh. * localAxis is expressed in the mesh local space. * result is computed in the Wordl space from the mesh World matrix. * Returns the TransformNode. */ TransformNode.prototype.getDirectionToRef = function (localAxis, result) { BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result); return this; }; /** * Sets a new pivot point to the current node * @param point defines the new pivot point to use * @param space defines if the point is in world or local space (local by default) * @returns the current TransformNode */ TransformNode.prototype.setPivotPoint = function (point, space) { if (space === void 0) { space = BABYLON.Space.LOCAL; } if (this.getScene().getRenderId() == 0) { this.computeWorldMatrix(true); } var wm = this.getWorldMatrix(); if (space == BABYLON.Space.WORLD) { var tmat = BABYLON.Tmp.Matrix[0]; wm.invertToRef(tmat); point = BABYLON.Vector3.TransformCoordinates(point, tmat); } return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true); }; /** * Returns a new Vector3 set with the mesh pivot point coordinates in the local space. */ TransformNode.prototype.getPivotPoint = function () { var point = BABYLON.Vector3.Zero(); this.getPivotPointToRef(point); return point; }; /** * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space. * Returns the TransformNode. */ TransformNode.prototype.getPivotPointToRef = function (result) { result.x = -this._pivotMatrix.m[12]; result.y = -this._pivotMatrix.m[13]; result.z = -this._pivotMatrix.m[14]; return this; }; /** * Returns a new Vector3 set with the mesh pivot point World coordinates. */ TransformNode.prototype.getAbsolutePivotPoint = function () { var point = BABYLON.Vector3.Zero(); this.getAbsolutePivotPointToRef(point); return point; }; /** * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates. * Returns the TransformNode. */ TransformNode.prototype.getAbsolutePivotPointToRef = function (result) { result.x = this._pivotMatrix.m[12]; result.y = this._pivotMatrix.m[13]; result.z = this._pivotMatrix.m[14]; this.getPivotPointToRef(result); BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result); return this; }; /** * Defines the passed node as the parent of the current node. * The node will remain exactly where it is and its position / rotation will be updated accordingly * Returns the TransformNode. */ TransformNode.prototype.setParent = function (node) { if (node === null) { var rotation = BABYLON.Tmp.Quaternion[0]; var position = BABYLON.Tmp.Vector3[0]; var scale = BABYLON.Tmp.Vector3[1]; if (this.parent && this.parent.computeWorldMatrix) { this.parent.computeWorldMatrix(true); } this.computeWorldMatrix(true); this.getWorldMatrix().decompose(scale, rotation, position); if (this.rotationQuaternion) { this.rotationQuaternion.copyFrom(rotation); } else { rotation.toEulerAnglesToRef(this.rotation); } this.scaling.x = scale.x; this.scaling.y = scale.y; this.scaling.z = scale.z; this.position.x = position.x; this.position.y = position.y; this.position.z = position.z; } else { var rotation = BABYLON.Tmp.Quaternion[0]; var position = BABYLON.Tmp.Vector3[0]; var scale = BABYLON.Tmp.Vector3[1]; var diffMatrix = BABYLON.Tmp.Matrix[0]; var invParentMatrix = BABYLON.Tmp.Matrix[1]; this.computeWorldMatrix(true); node.computeWorldMatrix(true); node.getWorldMatrix().invertToRef(invParentMatrix); this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix); diffMatrix.decompose(scale, rotation, position); if (this.rotationQuaternion) { this.rotationQuaternion.copyFrom(rotation); } else { rotation.toEulerAnglesToRef(this.rotation); } this.position.x = position.x; this.position.y = position.y; this.position.z = position.z; this.scaling.x = scale.x; this.scaling.y = scale.y; this.scaling.z = scale.z; } this.parent = node; return this; }; Object.defineProperty(TransformNode.prototype, "nonUniformScaling", { get: function () { return this._nonUniformScaling; }, enumerable: true, configurable: true }); TransformNode.prototype._updateNonUniformScalingState = function (value) { if (this._nonUniformScaling === value) { return false; } this._nonUniformScaling = value; return true; }; /** * Attach the current TransformNode to another TransformNode associated with a bone * @param bone Bone affecting the TransformNode * @param affectedTransformNode TransformNode associated with the bone */ TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) { this._transformToBoneReferal = affectedTransformNode; this.parent = bone; if (bone.getWorldMatrix().determinant() < 0) { this.scalingDeterminant *= -1; } return this; }; TransformNode.prototype.detachFromBone = function () { if (!this.parent) { return this; } if (this.parent.getWorldMatrix().determinant() < 0) { this.scalingDeterminant *= -1; } this._transformToBoneReferal = null; this.parent = null; return this; }; /** * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used. * The passed axis is also normalized. * Returns the TransformNode. */ TransformNode.prototype.rotate = function (axis, amount, space) { axis.normalize(); if (!this.rotationQuaternion) { this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z); this.rotation = BABYLON.Vector3.Zero(); } var rotationQuaternion; if (!space || space === BABYLON.Space.LOCAL) { rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache); this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion); } else { if (this.parent) { var invertParentWorldMatrix = this.parent.getWorldMatrix().clone(); invertParentWorldMatrix.invert(); axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix); } rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache); rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion); } return this; }; /** * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used. * The passed axis is also normalized. * Returns the TransformNode. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm */ TransformNode.prototype.rotateAround = function (point, axis, amount) { axis.normalize(); if (!this.rotationQuaternion) { this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z); this.rotation.copyFromFloats(0, 0, 0); } point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]); BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]); BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]); BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]); BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]); BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]); BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]); this.position.addInPlace(BABYLON.Tmp.Vector3[1]); BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion); return this; }; /** * Translates the mesh along the axis vector for the passed distance in the given space. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD. * Returns the TransformNode. */ TransformNode.prototype.translate = function (axis, distance, space) { var displacementVector = axis.scale(distance); if (!space || space === BABYLON.Space.LOCAL) { var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector); this.setPositionWithLocalVector(tempV3); } else { this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector)); } return this; }; /** * Adds a rotation step to the mesh current rotation. * x, y, z are Euler angles expressed in radians. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set. * This means this rotation is made in the mesh local space only. * It's useful to set a custom rotation order different from the BJS standard one YXZ. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis. * ```javascript * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3); * ``` * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles. * Returns the TransformNode. */ TransformNode.prototype.addRotation = function (x, y, z) { var rotationQuaternion; if (this.rotationQuaternion) { rotationQuaternion = this.rotationQuaternion; } else { rotationQuaternion = BABYLON.Tmp.Quaternion[1]; BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion); } var accumulation = BABYLON.Tmp.Quaternion[0]; BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation); rotationQuaternion.multiplyInPlace(accumulation); if (!this.rotationQuaternion) { rotationQuaternion.toEulerAnglesToRef(this.rotation); } return this; }; /** * Computes the mesh World matrix and returns it. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned. * If the parameter `force`is set to `true`, the actual computation is done. * Returns the mesh World Matrix. */ TransformNode.prototype.computeWorldMatrix = function (force) { if (this._isWorldMatrixFrozen) { return this._worldMatrix; } if (!force && this.isSynchronized(true)) { this._currentRenderId = this.getScene().getRenderId(); return this._worldMatrix; } this._cache.position.copyFrom(this.position); this._cache.scaling.copyFrom(this.scaling); this._cache.pivotMatrixUpdated = false; this._cache.billboardMode = this.billboardMode; this._currentRenderId = this.getScene().getRenderId(); this._childRenderId = this.getScene().getRenderId(); this._isDirty = false; // Scaling BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]); // Rotation //rotate, if quaternion is set and rotation was used if (this.rotationQuaternion) { var len = this.rotation.length(); if (len) { this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z)); this.rotation.copyFromFloats(0, 0, 0); } } if (this.rotationQuaternion) { this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]); this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion); } else { BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]); this._cache.rotation.copyFrom(this.rotation); } // Translation var camera = this.getScene().activeCamera; if (this.infiniteDistance && !this.parent && camera) { var cameraWorldMatrix = camera.getWorldMatrix(); var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]); BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]); } else { BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]); } // Composing transformations this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]); BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]); // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13) if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) { if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) { // Need to decompose each rotation here var currentPosition = BABYLON.Tmp.Vector3[3]; if (this.parent && this.parent.getWorldMatrix) { if (this._transformToBoneReferal) { this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]); BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition); } else { BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition); } } else { currentPosition.copyFrom(this.position); } currentPosition.subtractInPlace(camera.globalPosition); var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0); if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) { finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z); } if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) { finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z); } if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) { finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x); } BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]); } else { BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix()); BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0); BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]); } BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]); BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]); } // Local world BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld); // Parent if (this.parent && this.parent.getWorldMatrix) { if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) { if (this._transformToBoneReferal) { this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]); BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]); } else { BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix()); } this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]); BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]); this._worldMatrix.copyFrom(this._localWorld); this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]); } else { if (this._transformToBoneReferal) { this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]); BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix); } else { this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix); } } this._markSyncedWithParent(); } else { this._worldMatrix.copyFrom(this._localWorld); } // Post multiply inverse of pivotMatrix if (this._postMultiplyPivotMatrix) { this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix); } // Normal matrix if (!this.ignoreNonUniformScaling) { if (this.scaling.isNonUniform) { this._updateNonUniformScalingState(true); } else if (this.parent && this.parent._nonUniformScaling) { this._updateNonUniformScalingState(this.parent._nonUniformScaling); } else { this._updateNonUniformScalingState(false); } } else { this._updateNonUniformScalingState(false); } this._afterComputeWorldMatrix(); // Absolute position this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]); // Callbacks this.onAfterWorldMatrixUpdateObservable.notifyObservers(this); if (!this._poseMatrix) { this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix); } // Cache the determinant this._worldMatrixDeterminant = this._worldMatrix.determinant(); return this._worldMatrix; }; TransformNode.prototype._afterComputeWorldMatrix = function () { }; /** * If you'd like to be called back after the mesh position, rotation or scaling has been updated. * @param func: callback function to add * * Returns the TransformNode. */ TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) { this.onAfterWorldMatrixUpdateObservable.add(func); return this; }; /** * Removes a registered callback function. * Returns the TransformNode. */ TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) { this.onAfterWorldMatrixUpdateObservable.removeCallback(func); return this; }; /** * Clone the current transform node * Returns the new transform node * @param name Name of the new clone * @param newParent New parent for the clone * @param doNotCloneChildren Do not clone children hierarchy */ TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) { var _this = this; var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this); result.name = name; result.id = name; if (newParent) { result.parent = newParent; } if (!doNotCloneChildren) { // Children var directDescendants = this.getDescendants(true); for (var index = 0; index < directDescendants.length; index++) { var child = directDescendants[index]; if (child.clone) { child.clone(name + "." + child.name, result); } } } return result; }; TransformNode.prototype.serialize = function (currentSerializationObject) { var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject); serializationObject.type = this.getClassName(); // Parent if (this.parent) { serializationObject.parentId = this.parent.id; } if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) { serializationObject.tags = BABYLON.Tags.GetTags(this); } serializationObject.localMatrix = this.getPivotMatrix().asArray(); serializationObject.isEnabled = this.isEnabled(); // Parent if (this.parent) { serializationObject.parentId = this.parent.id; } return serializationObject; }; // Statics /** * Returns a new TransformNode object parsed from the source provided. * The parameter `parsedMesh` is the source. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with */ TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) { var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl); if (BABYLON.Tags) { BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags); } if (parsedTransformNode.localMatrix) { transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix)); } else if (parsedTransformNode.pivotMatrix) { transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix)); } transformNode.setEnabled(parsedTransformNode.isEnabled); // Parent if (parsedTransformNode.parentId) { transformNode._waitingParentId = parsedTransformNode.parentId; } return transformNode; }; /** * Releases resources associated with this transform node. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) */ TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) { if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; } // Animations this.getScene().stopAnimation(this); // Remove from scene this.getScene().removeTransformNode(this); this.onAfterWorldMatrixUpdateObservable.clear(); _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures); }; // Statics TransformNode.BILLBOARDMODE_NONE = 0; TransformNode.BILLBOARDMODE_X = 1; TransformNode.BILLBOARDMODE_Y = 2; TransformNode.BILLBOARDMODE_Z = 4; TransformNode.BILLBOARDMODE_ALL = 7; TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0); TransformNode._rotationAxisCache = new BABYLON.Quaternion(); __decorate([ BABYLON.serializeAsVector3() ], TransformNode.prototype, "_rotation", void 0); __decorate([ BABYLON.serializeAsQuaternion() ], TransformNode.prototype, "_rotationQuaternion", void 0); __decorate([ BABYLON.serializeAsVector3() ], TransformNode.prototype, "_scaling", void 0); __decorate([ BABYLON.serialize() ], TransformNode.prototype, "billboardMode", void 0); __decorate([ BABYLON.serialize() ], TransformNode.prototype, "scalingDeterminant", void 0); __decorate([ BABYLON.serialize() ], TransformNode.prototype, "infiniteDistance", void 0); __decorate([ BABYLON.serialize() ], TransformNode.prototype, "ignoreNonUniformScaling", void 0); __decorate([ BABYLON.serializeAsVector3() ], TransformNode.prototype, "position", void 0); return TransformNode; }(BABYLON.Node)); BABYLON.TransformNode = TransformNode; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.transformNode.js.map var BABYLON; (function (BABYLON) { /** * Class used to store all common mesh properties */ var AbstractMesh = /** @class */ (function (_super) { __extends(AbstractMesh, _super); // Constructor /** * Creates a new AbstractMesh * @param name defines the name of the mesh * @param scene defines the hosting scene */ function AbstractMesh(name, scene) { if (scene === void 0) { scene = null; } var _this = _super.call(this, name, scene, false) || this; _this._facetNb = 0; // facet number _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ? _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data _this._subDiv = { max: 1, X: 1, Y: 1, Z: 1 }; _this._facetDepthSort = false; // is the facet depth sort to be computed _this._facetDepthSortEnabled = false; // is the facet depth sort initialized // Events /** * An event triggered when this mesh collides with another one */ _this.onCollideObservable = new BABYLON.Observable(); /** * An event triggered when the collision's position changes */ _this.onCollisionPositionChangeObservable = new BABYLON.Observable(); /** * An event triggered when material is changed */ _this.onMaterialChangedObservable = new BABYLON.Observable(); // Properties /** * Gets or sets the orientation for POV movement & rotation */ _this.definedFacingForward = true; /** * This property determines the type of occlusion query algorithm to run in WebGl, you can use: * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate. * @see http://doc.babylonjs.com/features/occlusionquery */ _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE; /** * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values: * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh. * * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show. * @see http://doc.babylonjs.com/features/occlusionquery */ _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE; /** * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object. * The default value is -1 which means don't break the query and wait till the result * @see http://doc.babylonjs.com/features/occlusionquery */ _this.occlusionRetryCount = -1; _this._occlusionInternalRetryCounter = 0; _this._isOccluded = false; _this._isOcclusionQueryInProgress = false; _this._visibility = 1.0; /** Gets or sets the alpha index used to sort transparent meshes * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index */ _this.alphaIndex = Number.MAX_VALUE; /** * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true */ _this.isVisible = true; /** * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true */ _this.isPickable = true; /** * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default) */ _this.showBoundingBox = false; /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */ _this.showSubMeshesBoundingBox = false; /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default) * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares */ _this.isBlocker = false; /** * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default) */ _this.enablePointerMoveEvents = false; /** * Specifies the rendering group id for this mesh (0 by default) * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups */ _this.renderingGroupId = 0; _this._receiveShadows = false; /** * Gets or sets a boolean indicating if the outline must be rendered as well * @see https://www.babylonjs-playground.com/#10WJ5S#3 */ _this.renderOutline = false; /** Defines color to use when rendering outline */ _this.outlineColor = BABYLON.Color3.Red(); /** Define width to use when rendering outline */ _this.outlineWidth = 0.02; /** * Gets or sets a boolean indicating if the overlay must be rendered as well * @see https://www.babylonjs-playground.com/#10WJ5S#2 */ _this.renderOverlay = false; /** Defines color to use when rendering overlay */ _this.overlayColor = BABYLON.Color3.Red(); /** Defines alpha to use when rendering overlay */ _this.overlayAlpha = 0.5; _this._hasVertexAlpha = false; _this._useVertexColors = true; _this._computeBonesUsingShaders = true; _this._numBoneInfluencers = 4; _this._applyFog = true; /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */ _this.useOctreeForRenderingSelection = true; /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */ _this.useOctreeForPicking = true; /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */ _this.useOctreeForCollisions = true; _this._layerMask = 0x0FFFFFFF; /** * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase) */ _this.alwaysSelectAsActiveMesh = false; /** * Gets or sets the current action manager * @see http://doc.babylonjs.com/how_to/how_to_use_actions */ _this.actionManager = null; /** * Gets or sets impostor used for physic simulation * @see http://doc.babylonjs.com/features/physics_engine */ _this.physicsImpostor = null; // Collisions _this._checkCollisions = false; _this._collisionMask = -1; _this._collisionGroup = -1; /** * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5)) * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity */ _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5); /** * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0)) * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity */ _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0); _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0); _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0); // Edges /** * Defines edge width used when edgesRenderer is enabled * @see https://www.babylonjs-playground.com/#10OJSG#13 */ _this.edgesWidth = 1; /** * Defines edge color used when edgesRenderer is enabled * @see https://www.babylonjs-playground.com/#10OJSG#13 */ _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1); // Cache _this._collisionsTransformMatrix = BABYLON.Matrix.Zero(); _this._collisionsScalingMatrix = BABYLON.Matrix.Zero(); /** @hidden */ _this._renderId = 0; /** @hidden */ _this._intersectionsInProgress = new Array(); /** @hidden */ _this._unIndexed = false; /** @hidden */ _this._lightSources = new Array(); _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) { if (collidedMesh === void 0) { collidedMesh = null; } //TODO move this to the collision coordinator! if (_this.getScene().workerCollisions) newPosition.multiplyInPlace(_this._collider._radius); newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions); if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) { _this.position.addInPlace(_this._diffPositionForCollisions); } if (collidedMesh) { _this.onCollideObservable.notifyObservers(collidedMesh); } _this.onCollisionPositionChangeObservable.notifyObservers(_this.position); }; _this.getScene().addMesh(_this); _this._resyncLightSources(); return _this; } Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", { /** * No billboard */ get: function () { return BABYLON.TransformNode.BILLBOARDMODE_NONE; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", { /** Billboard on X axis */ get: function () { return BABYLON.TransformNode.BILLBOARDMODE_X; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", { /** Billboard on Y axis */ get: function () { return BABYLON.TransformNode.BILLBOARDMODE_Y; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", { /** Billboard on Z axis */ get: function () { return BABYLON.TransformNode.BILLBOARDMODE_Z; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", { /** Billboard on all axes */ get: function () { return BABYLON.TransformNode.BILLBOARDMODE_ALL; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "facetNb", { /** * Gets the number of facets in the mesh * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet */ get: function () { return this._facetNb; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", { /** * Gets or set the number (integer) of subdivisions per axis in the partioning space * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning */ get: function () { return this._partitioningSubdivisions; }, set: function (nb) { this._partitioningSubdivisions = nb; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", { /** * The ratio (float) to apply to the bouding box size to set to the partioning space. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning */ get: function () { return this._partitioningBBoxRatio; }, set: function (ratio) { this._partitioningBBoxRatio = ratio; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", { /** * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`. * Works only for updatable meshes. * Doesn't work with multi-materials * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort */ get: function () { return this._facetDepthSort; }, set: function (sort) { this._facetDepthSort = sort; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", { /** * The location (Vector3) where the facet depth sort must be computed from. * By default, the active camera position. * Used only when facet depth sort is enabled * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort */ get: function () { return this._facetDepthSortFrom; }, set: function (location) { this._facetDepthSortFrom = location; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", { /** * gets a boolean indicating if facetData is enabled * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet */ get: function () { return this._facetDataEnabled; }, enumerable: true, configurable: true }); /** @hidden */ AbstractMesh.prototype._updateNonUniformScalingState = function (value) { if (!_super.prototype._updateNonUniformScalingState.call(this, value)) { return false; } this._markSubMeshesAsMiscDirty(); return true; }; Object.defineProperty(AbstractMesh.prototype, "onCollide", { /** Set a function to call when this mesh collides with another one */ set: function (callback) { if (this._onCollideObserver) { this.onCollideObservable.remove(this._onCollideObserver); } this._onCollideObserver = this.onCollideObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", { /** Set a function to call when the collision's position changes */ set: function (callback) { if (this._onCollisionPositionChangeObserver) { this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver); } this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "isOccluded", { /** * Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not * @see http://doc.babylonjs.com/features/occlusionquery */ get: function () { return this._isOccluded; }, set: function (value) { this._isOccluded = value; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", { /** * Flag to check the progress status of the query * @see http://doc.babylonjs.com/features/occlusionquery */ get: function () { return this._isOcclusionQueryInProgress; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "visibility", { /** * Gets or sets mesh visibility between 0 and 1 (default is 1) */ get: function () { return this._visibility; }, /** * Gets or sets mesh visibility between 0 and 1 (default is 1) */ set: function (value) { if (this._visibility === value) { return; } this._visibility = value; this._markSubMeshesAsMiscDirty(); }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "material", { /** Gets or sets current material */ get: function () { return this._material; }, set: function (value) { if (this._material === value) { return; } this._material = value; if (this.onMaterialChangedObservable.hasObservers) { this.onMaterialChangedObservable.notifyObservers(this); } if (!this.subMeshes) { return; } this._unBindEffect(); }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "receiveShadows", { /** * Gets or sets a boolean indicating that this mesh can receive realtime shadows * @see http://doc.babylonjs.com/babylon101/shadows */ get: function () { return this._receiveShadows; }, set: function (value) { if (this._receiveShadows === value) { return; } this._receiveShadows = value; this._markSubMeshesAsLightDirty(); }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", { /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */ get: function () { return this._hasVertexAlpha; }, set: function (value) { if (this._hasVertexAlpha === value) { return; } this._hasVertexAlpha = value; this._markSubMeshesAsAttributesDirty(); this._markSubMeshesAsMiscDirty(); }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "useVertexColors", { /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */ get: function () { return this._useVertexColors; }, set: function (value) { if (this._useVertexColors === value) { return; } this._useVertexColors = value; this._markSubMeshesAsAttributesDirty(); }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", { /** * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default) */ get: function () { return this._computeBonesUsingShaders; }, set: function (value) { if (this._computeBonesUsingShaders === value) { return; } this._computeBonesUsingShaders = value; this._markSubMeshesAsAttributesDirty(); }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", { /** Gets or sets the number of allowed bone influences per vertex (4 by default) */ get: function () { return this._numBoneInfluencers; }, set: function (value) { if (this._numBoneInfluencers === value) { return; } this._numBoneInfluencers = value; this._markSubMeshesAsAttributesDirty(); }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "applyFog", { /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */ get: function () { return this._applyFog; }, set: function (value) { if (this._applyFog === value) { return; } this._applyFog = value; this._markSubMeshesAsMiscDirty(); }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "layerMask", { /** * Gets or sets the current layer mask (default is 0x0FFFFFFF) * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures */ get: function () { return this._layerMask; }, set: function (value) { if (value === this._layerMask) { return; } this._layerMask = value; this._resyncLightSources(); }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "collisionMask", { /** * Gets or sets a collision mask used to mask collisions (default is -1). * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0 */ get: function () { return this._collisionMask; }, set: function (mask) { this._collisionMask = !isNaN(mask) ? mask : -1; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "collisionGroup", { /** * Gets or sets the current collision group mask (-1 by default). * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0 */ get: function () { return this._collisionGroup; }, set: function (mask) { this._collisionGroup = !isNaN(mask) ? mask : -1; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "_positions", { /** @hidden */ get: function () { return null; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "skeleton", { get: function () { return this._skeleton; }, /** * Gets or sets a skeleton to apply skining transformations * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons */ set: function (value) { if (this._skeleton && this._skeleton.needInitialSkinMatrix) { this._skeleton._unregisterMeshWithPoseMatrix(this); } if (value && value.needInitialSkinMatrix) { value._registerMeshWithPoseMatrix(this); } this._skeleton = value; if (!this._skeleton) { this._bonesTransformMatrices = null; } this._markSubMeshesAsAttributesDirty(); }, enumerable: true, configurable: true }); /** * Returns the string "AbstractMesh" * @returns "AbstractMesh" */ AbstractMesh.prototype.getClassName = function () { return "AbstractMesh"; }; /** * Gets a string representation of the current mesh * @param fullDetails defines a boolean indicating if full details must be included * @returns a string representation of the current mesh */ AbstractMesh.prototype.toString = function (fullDetails) { var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO"); ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0); if (this._skeleton) { ret += ", skeleton: " + this._skeleton.name; } if (fullDetails) { ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode]; ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO"); } return ret; }; /** @hidden */ AbstractMesh.prototype._rebuild = function () { if (this._occlusionQuery) { this._occlusionQuery = null; } if (this._edgesRenderer) { this._edgesRenderer._rebuild(); } if (!this.subMeshes) { return; } for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) { var subMesh = _a[_i]; subMesh._rebuild(); } }; /** @hidden */ AbstractMesh.prototype._resyncLightSources = function () { this._lightSources.length = 0; for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) { var light = _a[_i]; if (!light.isEnabled()) { continue; } if (light.canAffectMesh(this)) { this._lightSources.push(light); } } this._markSubMeshesAsLightDirty(); }; /** @hidden */ AbstractMesh.prototype._resyncLighSource = function (light) { var isIn = light.isEnabled() && light.canAffectMesh(this); var index = this._lightSources.indexOf(light); if (index === -1) { if (!isIn) { return; } this._lightSources.push(light); } else { if (isIn) { return; } this._lightSources.splice(index, 1); } this._markSubMeshesAsLightDirty(); }; /** @hidden */ AbstractMesh.prototype._unBindEffect = function () { for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) { var subMesh = _a[_i]; subMesh.setEffect(null); } }; /** @hidden */ AbstractMesh.prototype._removeLightSource = function (light) { var index = this._lightSources.indexOf(light); if (index === -1) { return; } this._lightSources.splice(index, 1); this._markSubMeshesAsLightDirty(); }; AbstractMesh.prototype._markSubMeshesAsDirty = function (func) { if (!this.subMeshes) { return; } for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) { var subMesh = _a[_i]; if (subMesh._materialDefines) { func(subMesh._materialDefines); } } }; /** @hidden */ AbstractMesh.prototype._markSubMeshesAsLightDirty = function () { this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); }); }; /** @hidden */ AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () { this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); }); }; /** @hidden */ AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () { if (!this.subMeshes) { return; } for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) { var subMesh = _a[_i]; var material = subMesh.getMaterial(); if (material) { material.markAsDirty(BABYLON.Material.MiscDirtyFlag); } } }; Object.defineProperty(AbstractMesh.prototype, "scaling", { /** * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0) */ get: function () { return this._scaling; }, set: function (newScaling) { this._scaling = newScaling; if (this.physicsImpostor) { this.physicsImpostor.forceUpdate(); } }, enumerable: true, configurable: true }); // Methods /** * Disables the mesh edge rendering mode * @returns the currentAbstractMesh */ AbstractMesh.prototype.disableEdgesRendering = function () { if (this._edgesRenderer) { this._edgesRenderer.dispose(); this._edgesRenderer = null; } return this; }; /** * Enables the edge rendering mode on the mesh. * This mode makes the mesh edges visible * @param epsilon defines the maximal distance between two angles to detect a face * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces * @returns the currentAbstractMesh * @see https://www.babylonjs-playground.com/#19O9TU#0 */ AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) { if (epsilon === void 0) { epsilon = 0.95; } if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; } this.disableEdgesRendering(); this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices); return this; }; Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", { /** * Gets the edgesRenderer associated with the mesh */ get: function () { return this._edgesRenderer; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "isBlocked", { /** * Returns true if the mesh is blocked. Implemented by child classes */ get: function () { return false; }, enumerable: true, configurable: true }); /** * Returns the mesh itself by default. Implemented by child classes * @param camera defines the camera to use to pick the right LOD level * @returns the currentAbstractMesh */ AbstractMesh.prototype.getLOD = function (camera) { return this; }; /** * Returns 0 by default. Implemented by child classes * @returns an integer */ AbstractMesh.prototype.getTotalVertices = function () { return 0; }; /** * Returns null by default. Implemented by child classes * @returns null */ AbstractMesh.prototype.getIndices = function () { return null; }; /** * Returns the array of the requested vertex data kind. Implemented by child classes * @param kind defines the vertex data kind to use * @returns null */ AbstractMesh.prototype.getVerticesData = function (kind) { return null; }; /** * Sets the vertex data of the mesh geometry for the requested `kind`. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data. * Note that a new underlying VertexBuffer object is created each call. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed. * @param kind defines vertex data kind: * * BABYLON.VertexBuffer.PositionKind * * BABYLON.VertexBuffer.UVKind * * BABYLON.VertexBuffer.UV2Kind * * BABYLON.VertexBuffer.UV3Kind * * BABYLON.VertexBuffer.UV4Kind * * BABYLON.VertexBuffer.UV5Kind * * BABYLON.VertexBuffer.UV6Kind * * BABYLON.VertexBuffer.ColorKind * * BABYLON.VertexBuffer.MatricesIndicesKind * * BABYLON.VertexBuffer.MatricesIndicesExtraKind * * BABYLON.VertexBuffer.MatricesWeightsKind * * BABYLON.VertexBuffer.MatricesWeightsExtraKind * @param data defines the data source * @param updatable defines if the data must be flagged as updatable (or static) * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind * @returns the current mesh */ AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) { return this; }; /** * Updates the existing vertex data of the mesh geometry for the requested `kind`. * If the mesh has no geometry, it is simply returned as it is. * @param kind defines vertex data kind: * * BABYLON.VertexBuffer.PositionKind * * BABYLON.VertexBuffer.UVKind * * BABYLON.VertexBuffer.UV2Kind * * BABYLON.VertexBuffer.UV3Kind * * BABYLON.VertexBuffer.UV4Kind * * BABYLON.VertexBuffer.UV5Kind * * BABYLON.VertexBuffer.UV6Kind * * BABYLON.VertexBuffer.ColorKind * * BABYLON.VertexBuffer.MatricesIndicesKind * * BABYLON.VertexBuffer.MatricesIndicesExtraKind * * BABYLON.VertexBuffer.MatricesWeightsKind * * BABYLON.VertexBuffer.MatricesWeightsExtraKind * @param data defines the data source * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh * @returns the current mesh */ AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) { return this; }; /** * Sets the mesh indices, * If the mesh has no geometry, a new Geometry object is created and set to the mesh. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array) * @param totalVertices Defines the total number of vertices * @returns the current mesh */ AbstractMesh.prototype.setIndices = function (indices, totalVertices) { return this; }; /** * Gets a boolean indicating if specific vertex data is present * @param kind defines the vertex data kind to use * @returns true is data kind is present */ AbstractMesh.prototype.isVerticesDataPresent = function (kind) { return false; }; /** * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined * @returns a BoundingInfo */ AbstractMesh.prototype.getBoundingInfo = function () { if (this._masterMesh) { return this._masterMesh.getBoundingInfo(); } if (!this._boundingInfo) { // this._boundingInfo is being created here this._updateBoundingInfo(); } // cannot be null. return this._boundingInfo; }; /** * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units) * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box * @returns the current mesh */ AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) { if (includeDescendants === void 0) { includeDescendants = true; } var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants); var sizeVec = boundingVectors.max.subtract(boundingVectors.min); var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z); if (maxDimension === 0) { return this; } var scale = 1 / maxDimension; this.scaling.scaleInPlace(scale); return this; }; /** * Overwrite the current bounding info * @param boundingInfo defines the new bounding info * @returns the current mesh */ AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) { this._boundingInfo = boundingInfo; return this; }; Object.defineProperty(AbstractMesh.prototype, "useBones", { /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */ get: function () { return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)); }, enumerable: true, configurable: true }); /** @hidden */ AbstractMesh.prototype._preActivate = function () { }; /** @hidden */ AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) { }; /** @hidden */ AbstractMesh.prototype._activate = function (renderId) { this._renderId = renderId; }; /** * Gets the current world matrix * @returns a Matrix */ AbstractMesh.prototype.getWorldMatrix = function () { if (this._masterMesh) { return this._masterMesh.getWorldMatrix(); } return _super.prototype.getWorldMatrix.call(this); }; /** @hidden */ AbstractMesh.prototype._getWorldMatrixDeterminant = function () { if (this._masterMesh) { return this._masterMesh._getWorldMatrixDeterminant(); } return _super.prototype._getWorldMatrixDeterminant.call(this); }; // ================================== Point of View Movement ================================= /** * Perform relative position change from the point of view of behind the front of the mesh. * This is performed taking into account the meshes current rotation, so you do not have to care. * Supports definition of mesh facing forward or backward * @param amountRight defines the distance on the right axis * @param amountUp defines the distance on the up axis * @param amountForward defines the distance on the forward axis * @returns the current mesh */ AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) { this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward)); return this; }; /** * Calculate relative position change from the point of view of behind the front of the mesh. * This is performed taking into account the meshes current rotation, so you do not have to care. * Supports definition of mesh facing forward or backward * @param amountRight defines the distance on the right axis * @param amountUp defines the distance on the up axis * @param amountForward defines the distance on the forward axis * @returns the new displacement vector */ AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) { var rotMatrix = new BABYLON.Matrix(); var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z); rotQuaternion.toRotationMatrix(rotMatrix); var translationDelta = BABYLON.Vector3.Zero(); var defForwardMult = this.definedFacingForward ? -1 : 1; BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta); return translationDelta; }; // ================================== Point of View Rotation ================================= /** * Perform relative rotation change from the point of view of behind the front of the mesh. * Supports definition of mesh facing forward or backward * @param flipBack defines the flip * @param twirlClockwise defines the twirl * @param tiltRight defines the tilt * @returns the current mesh */ AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) { this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight)); return this; }; /** * Calculate relative rotation change from the point of view of behind the front of the mesh. * Supports definition of mesh facing forward or backward. * @param flipBack defines the flip * @param twirlClockwise defines the twirl * @param tiltRight defines the tilt * @returns the new rotation vector */ AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) { var defForwardMult = this.definedFacingForward ? 1 : -1; return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult); }; /** * Return the minimum and maximum world vectors of the entire hierarchy under current mesh * @param includeDescendants Include bounding info from descendants as well (true by default) * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors * @returns the new bounding vectors */ AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) { if (includeDescendants === void 0) { includeDescendants = true; } if (predicate === void 0) { predicate = null; } // Ensures that all world matrix will be recomputed. this.getScene().incrementRenderId(); this.computeWorldMatrix(true); var min; var max; var boundingInfo = this.getBoundingInfo(); if (!this.subMeshes) { min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); } else { min = boundingInfo.boundingBox.minimumWorld; max = boundingInfo.boundingBox.maximumWorld; } if (includeDescendants) { var descendants = this.getDescendants(false); for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) { var descendant = descendants_1[_i]; var childMesh = descendant; childMesh.computeWorldMatrix(true); // Filters meshes based on custom predicate function. if (predicate && !predicate(childMesh)) { continue; } //make sure we have the needed params to get mix and max if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) { continue; } var childBoundingInfo = childMesh.getBoundingInfo(); var boundingBox = childBoundingInfo.boundingBox; var minBox = boundingBox.minimumWorld; var maxBox = boundingBox.maximumWorld; BABYLON.Tools.CheckExtends(minBox, min, max); BABYLON.Tools.CheckExtends(maxBox, min, max); } } return { min: min, max: max }; }; /** @hidden */ AbstractMesh.prototype._updateBoundingInfo = function () { this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition); this._boundingInfo.update(this.worldMatrixFromCache); this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache); return this; }; /** @hidden */ AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) { if (!this.subMeshes) { return this; } for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) { var subMesh = this.subMeshes[subIndex]; if (!subMesh.IsGlobal) { subMesh.updateBoundingInfo(matrix); } } return this; }; /** @hidden */ AbstractMesh.prototype._afterComputeWorldMatrix = function () { // Bounding info this._updateBoundingInfo(); }; /** * Returns `true` if the mesh is within the frustum defined by the passed array of planes. * A mesh is in the frustum if its bounding box intersects the frustum * @param frustumPlanes defines the frustum to test * @returns true if the mesh is in the frustum planes */ AbstractMesh.prototype.isInFrustum = function (frustumPlanes) { return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes); }; /** * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes. * A mesh is completely in the frustum if its bounding box it completely inside the frustum. * @param frustumPlanes defines the frustum to test * @returns true if the mesh is completely in the frustum planes */ AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) { return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes); }; /** * True if the mesh intersects another mesh or a SolidParticle object * @param mesh defines a target mesh or SolidParticle to test * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes) * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes * @returns true if there is an intersection */ AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) { if (precise === void 0) { precise = false; } if (!this._boundingInfo || !mesh._boundingInfo) { return false; } if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) { return true; } if (includeDescendants) { for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) { var child = _a[_i]; if (child.intersectsMesh(mesh, precise, true)) { return true; } } } return false; }; /** * Returns true if the passed point (Vector3) is inside the mesh bounding box * @param point defines the point to test * @returns true if there is an intersection */ AbstractMesh.prototype.intersectsPoint = function (point) { if (!this._boundingInfo) { return false; } return this._boundingInfo.intersectsPoint(point); }; /** * Gets the current physics impostor * @see http://doc.babylonjs.com/features/physics_engine * @returns a physics impostor or null */ AbstractMesh.prototype.getPhysicsImpostor = function () { return this.physicsImpostor; }; /** * Gets the position of the current mesh in camera space * @param camera defines the camera to use * @returns a position */ AbstractMesh.prototype.getPositionInCameraSpace = function (camera) { if (camera === void 0) { camera = null; } if (!camera) { camera = this.getScene().activeCamera; } return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix()); }; /** * Returns the distance from the mesh to the active camera * @param camera defines the camera to use * @returns the distance */ AbstractMesh.prototype.getDistanceToCamera = function (camera) { if (camera === void 0) { camera = null; } if (!camera) { camera = this.getScene().activeCamera; } return this.absolutePosition.subtract(camera.position).length(); }; /** * Apply a physic impulse to the mesh * @param force defines the force to apply * @param contactPoint defines where to apply the force * @returns the current mesh * @see http://doc.babylonjs.com/how_to/using_the_physics_engine */ AbstractMesh.prototype.applyImpulse = function (force, contactPoint) { if (!this.physicsImpostor) { return this; } this.physicsImpostor.applyImpulse(force, contactPoint); return this; }; /** * Creates a physic joint between two meshes * @param otherMesh defines the other mesh to use * @param pivot1 defines the pivot to use on this mesh * @param pivot2 defines the pivot to use on the other mesh * @param options defines additional options (can be plugin dependent) * @returns the current mesh * @see https://www.babylonjs-playground.com/#0BS5U0#0 */ AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) { if (!this.physicsImpostor || !otherMesh.physicsImpostor) { return this; } this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, { mainPivot: pivot1, connectedPivot: pivot2, nativeParams: options }); return this; }; Object.defineProperty(AbstractMesh.prototype, "checkCollisions", { // Collisions /** * Gets or sets a boolean indicating that this mesh can be used in the collision engine * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity */ get: function () { return this._checkCollisions; }, set: function (collisionEnabled) { this._checkCollisions = collisionEnabled; if (this.getScene().workerCollisions) { this.getScene().collisionCoordinator.onMeshUpdated(this); } }, enumerable: true, configurable: true }); Object.defineProperty(AbstractMesh.prototype, "collider", { /** * Gets Collider object used to compute collisions (not physics) * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity */ get: function () { return this._collider; }, enumerable: true, configurable: true }); /** * Move the mesh using collision engine * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity * @param displacement defines the requested displacement vector * @returns the current mesh */ AbstractMesh.prototype.moveWithCollisions = function (displacement) { var globalPosition = this.getAbsolutePosition(); globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions); if (!this._collider) { this._collider = new BABYLON.Collider(); } this._collider._radius = this.ellipsoid; this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId); return this; }; // Submeshes octree /** * 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 */ AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) { if (maxCapacity === void 0) { maxCapacity = 64; } if (maxDepth === void 0) { maxDepth = 2; } if (!this._submeshesOctree) { this._submeshesOctree = new BABYLON.Octree(BABYLON.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; }; // Collisions /** @hidden */ AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) { this._generatePointsArray(); if (!this._positions) { return this; } // Transformation if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) { subMesh._lastColliderTransformMatrix = transformMatrix.clone(); subMesh._lastColliderWorldVertices = []; subMesh._trianglePlanes = []; var start = subMesh.verticesStart; var end = (subMesh.verticesStart + subMesh.verticesCount); for (var i = start; i < end; i++) { subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix)); } } // Collide collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial()); if (collider.collisionFound) { collider.collidedMesh = this; } return this; }; /** @hidden */ AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) { var subMeshes; var len; // Octrees if (this._submeshesOctree && this.useOctreeForCollisions) { var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z); var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius); len = intersections.length; subMeshes = intersections.data; } else { subMeshes = this.subMeshes; len = subMeshes.length; } for (var index = 0; index < len; index++) { var subMesh = subMeshes[index]; // Bounding test if (len > 1 && !subMesh._checkCollision(collider)) continue; this._collideForSubMesh(subMesh, transformMatrix, collider); } return this; }; /** @hidden */ AbstractMesh.prototype._checkCollision = function (collider) { // Bounding box test if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider)) return this; // Transformation matrix BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix); this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix); this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix); return this; }; // Picking /** @hidden */ AbstractMesh.prototype._generatePointsArray = function () { return false; }; /** * Checks if the passed Ray intersects with the mesh * @param ray defines the ray to use * @param fastCheck defines if fast mode (but less precise) must be used (false by default) * @returns the picking info * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh */ AbstractMesh.prototype.intersects = function (ray, fastCheck) { var pickingInfo = new BABYLON.PickingInfo(); if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) { return pickingInfo; } if (!this._generatePointsArray()) { return pickingInfo; } var intersectInfo = null; // Octrees var subMeshes; var len; if (this._submeshesOctree && this.useOctreeForPicking) { var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix()); var intersections = this._submeshesOctree.intersectsRay(worldRay); len = intersections.length; subMeshes = intersections.data; } else { subMeshes = this.subMeshes; len = subMeshes.length; } for (var index = 0; index < len; index++) { var subMesh = subMeshes[index]; // Bounding test if (len > 1 && !subMesh.canIntersects(ray)) continue; var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck); if (currentIntersectInfo) { if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) { intersectInfo = currentIntersectInfo; intersectInfo.subMeshId = index; if (fastCheck) { break; } } } } if (intersectInfo) { // Get picked point var world = this.getWorldMatrix(); var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world); var direction = ray.direction.clone(); direction = direction.scale(intersectInfo.distance); var worldDirection = BABYLON.Vector3.TransformNormal(direction, world); var pickedPoint = worldOrigin.add(worldDirection); // Return result pickingInfo.hit = true; pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint); pickingInfo.pickedPoint = pickedPoint; pickingInfo.pickedMesh = this; pickingInfo.bu = intersectInfo.bu || 0; pickingInfo.bv = intersectInfo.bv || 0; pickingInfo.faceId = intersectInfo.faceId; pickingInfo.subMeshId = intersectInfo.subMeshId; return pickingInfo; } return pickingInfo; }; /** * Clones the current mesh * @param name defines the mesh name * @param newParent defines the new mesh parent * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default) * @returns the new mesh */ AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) { return null; }; /** * Disposes all the submeshes of the current meshnp * @returns the current mesh */ AbstractMesh.prototype.releaseSubMeshes = function () { if (this.subMeshes) { while (this.subMeshes.length) { this.subMeshes[0].dispose(); } } else { this.subMeshes = new Array(); } return this; }; /** * Releases resources associated with this abstract mesh. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) */ AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) { var _this = this; if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; } var index; // Smart Array Retainers. this.getScene().freeActiveMeshes(); this.getScene().freeRenderingGroups(); // Action manager if (this.actionManager !== undefined && this.actionManager !== null) { this.actionManager.dispose(); this.actionManager = null; } // Skeleton this._skeleton = null; // Physics if (this.physicsImpostor) { this.physicsImpostor.dispose( /*!doNotRecurse*/); } // Intersections in progress for (index = 0; index < this._intersectionsInProgress.length; index++) { var other = this._intersectionsInProgress[index]; var pos = other._intersectionsInProgress.indexOf(this); other._intersectionsInProgress.splice(pos, 1); } this._intersectionsInProgress = []; // Lights var lights = this.getScene().lights; lights.forEach(function (light) { var meshIndex = light.includedOnlyMeshes.indexOf(_this); if (meshIndex !== -1) { light.includedOnlyMeshes.splice(meshIndex, 1); } meshIndex = light.excludedMeshes.indexOf(_this); if (meshIndex !== -1) { light.excludedMeshes.splice(meshIndex, 1); } // Shadow generators var generator = light.getShadowGenerator(); if (generator) { var shadowMap = generator.getShadowMap(); if (shadowMap && shadowMap.renderList) { meshIndex = shadowMap.renderList.indexOf(_this); if (meshIndex !== -1) { shadowMap.renderList.splice(meshIndex, 1); } } } }); // Edges if (this._edgesRenderer) { this._edgesRenderer.dispose(); this._edgesRenderer = null; } // SubMeshes if (this.getClassName() !== "InstancedMesh") { this.releaseSubMeshes(); } // Octree var sceneOctree = this.getScene().selectionOctree; if (sceneOctree !== undefined && sceneOctree !== null) { var index = sceneOctree.dynamicContent.indexOf(this); if (index !== -1) { sceneOctree.dynamicContent.splice(index, 1); } } // Query var engine = this.getScene().getEngine(); if (this._occlusionQuery) { this._isOcclusionQueryInProgress = false; engine.deleteQuery(this._occlusionQuery); this._occlusionQuery = null; } // Engine engine.wipeCaches(); // Remove from scene this.getScene().removeMesh(this); if (disposeMaterialAndTextures) { if (this.material) { this.material.dispose(false, true); } } if (!doNotRecurse) { // Particles for (index = 0; index < this.getScene().particleSystems.length; index++) { if (this.getScene().particleSystems[index].emitter === this) { this.getScene().particleSystems[index].dispose(); index--; } } } // facet data if (this._facetDataEnabled) { this.disableFacetData(); } this.onAfterWorldMatrixUpdateObservable.clear(); this.onCollideObservable.clear(); this.onCollisionPositionChangeObservable.clear(); _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures); }; /** * Adds the passed mesh as a child to the current mesh * @param mesh defines the child mesh * @returns the current mesh */ AbstractMesh.prototype.addChild = function (mesh) { mesh.setParent(this); return this; }; /** * Removes the passed mesh from the current mesh children list * @param mesh defines the child mesh * @returns the current mesh */ AbstractMesh.prototype.removeChild = function (mesh) { mesh.setParent(null); return this; }; // Facet data /** @hidden */ AbstractMesh.prototype._initFacetData = function () { if (!this._facetNormals) { this._facetNormals = new Array(); } if (!this._facetPositions) { this._facetPositions = new Array(); } if (!this._facetPartitioning) { this._facetPartitioning = new Array(); } this._facetNb = (this.getIndices().length / 3) | 0; this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10 this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box for (var f = 0; f < this._facetNb; f++) { this._facetNormals[f] = BABYLON.Vector3.Zero(); this._facetPositions[f] = BABYLON.Vector3.Zero(); } this._facetDataEnabled = true; return this; }; /** * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated. * This method can be called within the render loop. * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation * @returns the current mesh * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ AbstractMesh.prototype.updateFacetData = function () { if (!this._facetDataEnabled) { this._initFacetData(); } var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind); var indices = this.getIndices(); var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind); var bInfo = this.getBoundingInfo(); if (this._facetDepthSort && !this._facetDepthSortEnabled) { // init arrays, matrix and sort function on first call this._facetDepthSortEnabled = true; if (indices instanceof Uint16Array) { this._depthSortedIndices = new Uint16Array(indices); } else if (indices instanceof Uint32Array) { this._depthSortedIndices = new Uint32Array(indices); } else { var needs32bits = false; for (var i = 0; i < indices.length; i++) { if (indices[i] > 65535) { needs32bits = true; break; } } if (needs32bits) { this._depthSortedIndices = new Uint32Array(indices); } else { this._depthSortedIndices = new Uint16Array(indices); } } this._facetDepthSortFunction = function (f1, f2) { return (f2.sqDistance - f1.sqDistance); }; if (!this._facetDepthSortFrom) { var camera = this.getScene().activeCamera; this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero(); } this._depthSortedFacets = []; for (var f = 0; f < this._facetNb; f++) { var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 }; this._depthSortedFacets.push(depthSortedFacet); } this._invertedMatrix = BABYLON.Matrix.Identity(); this._facetDepthSortOrigin = BABYLON.Vector3.Zero(); } this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon; this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon; this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon; var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y; bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z; this._subDiv.max = this._partitioningSubdivisions; this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax); this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y; this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z; // set the parameters for ComputeNormals() this._facetParameters.facetNormals = this.getFacetLocalNormals(); this._facetParameters.facetPositions = this.getFacetLocalPositions(); this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning(); this._facetParameters.bInfo = bInfo; this._facetParameters.bbSize = this._bbSize; this._facetParameters.subDiv = this._subDiv; this._facetParameters.ratio = this.partitioningBBoxRatio; this._facetParameters.depthSort = this._facetDepthSort; if (this._facetDepthSort && this._facetDepthSortEnabled) { this.computeWorldMatrix(true); this._worldMatrix.invertToRef(this._invertedMatrix); BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin); this._facetParameters.distanceTo = this._facetDepthSortOrigin; } this._facetParameters.depthSortedFacets = this._depthSortedFacets; BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters); if (this._facetDepthSort && this._facetDepthSortEnabled) { this._depthSortedFacets.sort(this._facetDepthSortFunction); var l = (this._depthSortedIndices.length / 3) | 0; for (var f = 0; f < l; f++) { var sind = this._depthSortedFacets[f].ind; this._depthSortedIndices[f * 3] = indices[sind]; this._depthSortedIndices[f * 3 + 1] = indices[sind + 1]; this._depthSortedIndices[f * 3 + 2] = indices[sind + 2]; } this.updateIndices(this._depthSortedIndices); } return this; }; /** * Returns the facetLocalNormals array. * The normals are expressed in the mesh local spac * @returns an array of Vector3 * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ AbstractMesh.prototype.getFacetLocalNormals = function () { if (!this._facetNormals) { this.updateFacetData(); } return this._facetNormals; }; /** * Returns the facetLocalPositions array. * The facet positions are expressed in the mesh local space * @returns an array of Vector3 * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ AbstractMesh.prototype.getFacetLocalPositions = function () { if (!this._facetPositions) { this.updateFacetData(); } return this._facetPositions; }; /** * Returns the facetLocalPartioning array * @returns an array of array of numbers * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ AbstractMesh.prototype.getFacetLocalPartitioning = function () { if (!this._facetPartitioning) { this.updateFacetData(); } return this._facetPartitioning; }; /** * Returns the i-th facet position in the world system. * This method allocates a new Vector3 per call * @param i defines the facet index * @returns a new Vector3 * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ AbstractMesh.prototype.getFacetPosition = function (i) { var pos = BABYLON.Vector3.Zero(); this.getFacetPositionToRef(i, pos); return pos; }; /** * Sets the reference Vector3 with the i-th facet position in the world system * @param i defines the facet index * @param ref defines the target vector * @returns the current mesh * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) { var localPos = (this.getFacetLocalPositions())[i]; var world = this.getWorldMatrix(); BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref); return this; }; /** * Returns the i-th facet normal in the world system. * This method allocates a new Vector3 per call * @param i defines the facet index * @returns a new Vector3 * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ AbstractMesh.prototype.getFacetNormal = function (i) { var norm = BABYLON.Vector3.Zero(); this.getFacetNormalToRef(i, norm); return norm; }; /** * Sets the reference Vector3 with the i-th facet normal in the world system * @param i defines the facet index * @param ref defines the target vector * @returns the current mesh * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) { var localNorm = (this.getFacetLocalNormals())[i]; BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref); return this; }; /** * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system) * @param x defines x coordinate * @param y defines y coordinate * @param z defines z coordinate * @returns the array of facet indexes * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) { var bInfo = this.getBoundingInfo(); var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x); var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y); var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z); if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) { return null; } return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz]; }; /** * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found * @param projected sets as the (x,y,z) world projection on the facet * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position * @param x defines x coordinate * @param y defines y coordinate * @param z defines z coordinate * @returns the face index if found (or null instead) * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) { if (checkFace === void 0) { checkFace = false; } if (facing === void 0) { facing = true; } var world = this.getWorldMatrix(); var invMat = BABYLON.Tmp.Matrix[5]; world.invertToRef(invMat); var invVect = BABYLON.Tmp.Vector3[8]; BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing); if (projected) { // tranform the local computed projected vector to world coordinates BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected); } return closest; }; /** * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found * @param projected sets as the (x,y,z) local projection on the facet * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position * @param x defines x coordinate * @param y defines y coordinate * @param z defines z coordinate * @returns the face index if found (or null instead) * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) { if (checkFace === void 0) { checkFace = false; } if (facing === void 0) { facing = true; } var closest = null; var tmpx = 0.0; var tmpy = 0.0; var tmpz = 0.0; var d = 0.0; // tmp dot facet normal * facet position var t0 = 0.0; var projx = 0.0; var projy = 0.0; var projz = 0.0; // Get all the facets in the same partitioning block than (x, y, z) var facetPositions = this.getFacetLocalPositions(); var facetNormals = this.getFacetLocalNormals(); var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z); if (!facetsInBlock) { return null; } // Get the closest facet to (x, y, z) var shortest = Number.MAX_VALUE; // init distance vars var tmpDistance = shortest; var fib; // current facet in the block var norm; // current facet normal var p0; // current facet barycenter position // loop on all the facets in the current partitioning block for (var idx = 0; idx < facetsInBlock.length; idx++) { fib = facetsInBlock[idx]; norm = facetNormals[fib]; p0 = facetPositions[fib]; d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z; if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) { // compute (x,y,z) projection on the facet = (projx, projy, projz) d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z; t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z); projx = x + norm.x * t0; projy = y + norm.y * t0; projz = z + norm.z * t0; tmpx = projx - x; tmpy = projy - y; tmpz = projz - z; tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z) shortest = tmpDistance; closest = fib; if (projected) { projected.x = projx; projected.y = projy; projected.z = projz; } } } } return closest; }; /** * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals() * @returns the parameters * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ AbstractMesh.prototype.getFacetDataParameters = function () { return this._facetParameters; }; /** * Disables the feature FacetData and frees the related memory * @returns the current mesh * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata */ AbstractMesh.prototype.disableFacetData = function () { if (this._facetDataEnabled) { this._facetDataEnabled = false; this._facetPositions = new Array(); this._facetNormals = new Array(); this._facetPartitioning = new Array(); this._facetParameters = null; this._depthSortedIndices = new Uint32Array(0); } return this; }; /** * Updates the AbstractMesh indices array * @param indices defines the data source * @returns the current mesh */ AbstractMesh.prototype.updateIndices = function (indices) { return this; }; /** * Creates new normals data for the mesh * @param updatable defines if the normal vertex buffer must be flagged as updatable * @returns the current mesh */ AbstractMesh.prototype.createNormals = function (updatable) { var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind); var indices = this.getIndices(); var normals; if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) { normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind); } else { normals = []; } BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem }); this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable); return this; }; /** * Align the mesh with a normal * @param normal defines the normal to use * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default) * @returns the current mesh */ AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) { if (!upDirection) { upDirection = BABYLON.Axis.Y; } var axisX = BABYLON.Tmp.Vector3[0]; var axisZ = BABYLON.Tmp.Vector3[1]; BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ); BABYLON.Vector3.CrossToRef(normal, axisZ, axisX); if (this.rotationQuaternion) { BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion); } else { BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation); } return this; }; /** @hidden */ AbstractMesh.prototype._checkOcclusionQuery = function () { var engine = this.getEngine(); if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) { this._isOccluded = false; return; } if (this.isOcclusionQueryInProgress && this._occlusionQuery) { var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery); if (isOcclusionQueryAvailable) { var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery); this._isOcclusionQueryInProgress = false; this._occlusionInternalRetryCounter = 0; this._isOccluded = occlusionQueryResult === 1 ? false : true; } else { this._occlusionInternalRetryCounter++; if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) { this._isOcclusionQueryInProgress = false; this._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. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded; } else { return; } } } var scene = this.getScene(); var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer(); if (!this._occlusionQuery) { this._occlusionQuery = engine.createQuery(); } engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery); occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this); engine.endOcclusionQuery(this.occlusionQueryAlgorithmType); this._isOcclusionQueryInProgress = true; }; /** No occlusion */ AbstractMesh.OCCLUSION_TYPE_NONE = 0; /** Occlusion set to optimisitic */ AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1; /** Occlusion set to strict */ AbstractMesh.OCCLUSION_TYPE_STRICT = 2; /** Use an accurante occlusion algorithm */ AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0; /** Use a conservative occlusion algorithm */ AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1; return AbstractMesh; }(BABYLON.TransformNode)); BABYLON.AbstractMesh = AbstractMesh; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.abstractMesh.js.map var BABYLON; (function (BABYLON) { /** * 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) { __extends(Light, _super); /** * Creates a Light object in the scene. * Documentation : http://doc.babylonjs.com/tutorials/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 BABYLON.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 BABYLON.Color3(1.0, 1.0, 1.0); /** * 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; /** * 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. */ _this.range = Number.MAX_VALUE; /** * 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(); _this.getScene().addLight(_this); _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine()); _this._buildUniformLayout(); _this.includedOnlyMeshes = new Array(); _this.excludedMeshes = new Array(); _this._resyncMeshes(); return _this; } Object.defineProperty(Light, "LIGHTMAP_DEFAULT", { /** * If every light affecting the material is in this lightmapMode, * material.lightmapTexture adds or multiplies * (depends on material.useLightmapAsShadowmap) * after every other light calculations. */ get: function () { return Light._LIGHTMAP_DEFAULT; }, enumerable: true, configurable: true }); Object.defineProperty(Light, "LIGHTMAP_SPECULAR", { /** * material.lightmapTexture as only diffuse lighting from this light * adds only specular lighting from this light * adds dynamic shadows */ get: function () { return Light._LIGHTMAP_SPECULAR; }, enumerable: true, configurable: true }); Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", { /** * material.lightmapTexture as only lighting * no light calculation from this light * only adds dynamic shadows from this light */ get: function () { return Light._LIGHTMAP_SHADOWSONLY; }, enumerable: true, configurable: true }); Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", { /** * Each light type uses the default quantity according to its type: * point/spot lights use luminous intensity * directional lights use illuminance */ get: function () { return Light._INTENSITYMODE_AUTOMATIC; }, enumerable: true, configurable: true }); Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", { /** * lumen (lm) */ get: function () { return Light._INTENSITYMODE_LUMINOUSPOWER; }, enumerable: true, configurable: true }); Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", { /** * candela (lm/sr) */ get: function () { return Light._INTENSITYMODE_LUMINOUSINTENSITY; }, enumerable: true, configurable: true }); Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", { /** * lux (lm/m^2) */ get: function () { return Light._INTENSITYMODE_ILLUMINANCE; }, enumerable: true, configurable: true }); Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", { /** * nit (cd/m^2) */ get: function () { return Light._INTENSITYMODE_LUMINANCE; }, enumerable: true, configurable: true }); Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", { /** * Light type const id of the point light. */ get: function () { return Light._LIGHTTYPEID_POINTLIGHT; }, enumerable: true, configurable: true }); Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", { /** * Light type const id of the directional light. */ get: function () { return Light._LIGHTTYPEID_DIRECTIONALLIGHT; }, enumerable: true, configurable: true }); Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", { /** * Light type const id of the spot light. */ get: function () { return Light._LIGHTTYPEID_SPOTLIGHT; }, enumerable: true, configurable: true }); Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", { /** * Light type const id of the hemispheric light. */ get: function () { return Light._LIGHTTYPEID_HEMISPHERICLIGHT; }, 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; }; /** * 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 BABYLON.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; }; /** * Computes and Returns the light World matrix. * @returns the world matrix */ Light.prototype.getWorldMatrix = function () { this._currentRenderId = this.getScene().getRenderId(); this._childRenderId = this._currentRenderId; var worldMatrix = this._getWorldMatrix(); if (this.parent && this.parent.getWorldMatrix) { if (!this._parentedWorldMatrix) { this._parentedWorldMatrix = BABYLON.Matrix.Identity(); } worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix); this._markSyncedWithParent(); return this._parentedWorldMatrix; } return worldMatrix; }; /** * 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 BABYLON.SerializationHelper.Clone(constructor, this); }; /** * Serializes the current light into a Serialization object. * @returns the serialized object. */ Light.prototype.serialize = function () { var serializationObject = BABYLON.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 BABYLON.Animation.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) { switch (type) { case 0: return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); }; case 1: return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); }; case 2: return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); }; case 3: return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); }; } 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 = BABYLON.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]; light.animations.push(BABYLON.Animation.Parse(parsedAnimation)); } BABYLON.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(); }; //lightmapMode Consts Light._LIGHTMAP_DEFAULT = 0; Light._LIGHTMAP_SPECULAR = 1; Light._LIGHTMAP_SHADOWSONLY = 2; // Intensity Mode Consts Light._INTENSITYMODE_AUTOMATIC = 0; Light._INTENSITYMODE_LUMINOUSPOWER = 1; Light._INTENSITYMODE_LUMINOUSINTENSITY = 2; Light._INTENSITYMODE_ILLUMINANCE = 3; Light._INTENSITYMODE_LUMINANCE = 4; // Light types ids const. Light._LIGHTTYPEID_POINTLIGHT = 0; Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1; Light._LIGHTTYPEID_SPOTLIGHT = 2; Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3; __decorate([ BABYLON.serializeAsColor3() ], Light.prototype, "diffuse", void 0); __decorate([ BABYLON.serializeAsColor3() ], Light.prototype, "specular", void 0); __decorate([ BABYLON.serialize() ], Light.prototype, "intensity", void 0); __decorate([ BABYLON.serialize() ], Light.prototype, "range", void 0); __decorate([ BABYLON.serialize() ], Light.prototype, "intensityMode", null); __decorate([ BABYLON.serialize() ], Light.prototype, "radius", null); __decorate([ BABYLON.serialize() ], Light.prototype, "_renderPriority", void 0); __decorate([ BABYLON.expandToProperty("_reorderLightsInScene") ], Light.prototype, "renderPriority", void 0); __decorate([ BABYLON.serialize("shadowEnabled") ], Light.prototype, "_shadowEnabled", void 0); __decorate([ BABYLON.serialize("excludeWithLayerMask") ], Light.prototype, "_excludeWithLayerMask", void 0); __decorate([ BABYLON.serialize("includeOnlyWithLayerMask") ], Light.prototype, "_includeOnlyWithLayerMask", void 0); __decorate([ BABYLON.serialize("lightmapMode") ], Light.prototype, "_lightmapMode", void 0); return Light; }(BABYLON.Node)); BABYLON.Light = Light; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.light.js.map var BABYLON; (function (BABYLON) { var Camera = /** @class */ (function (_super) { __extends(Camera, _super); function Camera(name, position, scene, setActiveOnSceneIfNoneActive) { if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; } var _this = _super.call(this, name, scene) || this; /** * The vector the camera should consider as up. * (default is Vector3(0, 1, 0) aka Vector3.Up()) */ _this.upVector = BABYLON.Vector3.Up(); _this.orthoLeft = null; _this.orthoRight = null; _this.orthoBottom = null; _this.orthoTop = null; /** * FOV is set in Radians. (default is 0.8) */ _this.fov = 0.8; _this.minZ = 1; _this.maxZ = 10000.0; _this.inertia = 0.9; _this.mode = Camera.PERSPECTIVE_CAMERA; _this.isIntermediate = false; _this.viewport = new BABYLON.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; // Camera rig members _this.cameraRigMode = Camera.RIG_MODE_NONE; _this._rigCameras = new Array(); _this._webvrViewMatrix = BABYLON.Matrix.Identity(); _this._skipRendering = false; _this.customRenderTargets = new Array(); // Observables _this.onViewMatrixChangedObservable = new BABYLON.Observable(); _this.onProjectionMatrixChangedObservable = new BABYLON.Observable(); _this.onAfterCheckInputsObservable = new BABYLON.Observable(); _this.onRestoreStateObservable = new BABYLON.Observable(); // Cache _this._computedViewMatrix = BABYLON.Matrix.Identity(); _this._projectionMatrix = new BABYLON.Matrix(); _this._doNotComputeProjectionMatrix = false; _this._worldMatrix = BABYLON.Matrix.Identity(); _this._postProcesses = new Array(); _this._transformMatrix = BABYLON.Matrix.Zero(); _this._activeMeshes = new BABYLON.SmartArray(256); _this._globalPosition = BABYLON.Vector3.Zero(); _this._refreshFrustumPlanes = true; _this.getScene().addCamera(_this); if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) { _this.getScene().activeCamera = _this; } _this.position = position; return _this; } Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", { get: function () { return Camera._PERSPECTIVE_CAMERA; }, enumerable: true, configurable: true }); Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", { get: function () { return Camera._ORTHOGRAPHIC_CAMERA; }, enumerable: true, configurable: true }); Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", { /** * 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. * */ get: function () { return Camera._FOVMODE_VERTICAL_FIXED; }, enumerable: true, configurable: true }); Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", { /** * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum. * */ get: function () { return Camera._FOVMODE_HORIZONTAL_FIXED; }, enumerable: true, configurable: true }); Object.defineProperty(Camera, "RIG_MODE_NONE", { get: function () { return Camera._RIG_MODE_NONE; }, enumerable: true, configurable: true }); Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", { get: function () { return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH; }, enumerable: true, configurable: true }); Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", { get: function () { return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL; }, enumerable: true, configurable: true }); Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", { get: function () { return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED; }, enumerable: true, configurable: true }); Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", { get: function () { return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER; }, enumerable: true, configurable: true }); Object.defineProperty(Camera, "RIG_MODE_VR", { get: function () { return Camera._RIG_MODE_VR; }, enumerable: true, configurable: true }); Object.defineProperty(Camera, "RIG_MODE_WEBVR", { get: function () { return Camera._RIG_MODE_WEBVR; }, enumerable: true, configurable: true }); /** * Store current camera state (fov, position, etc..) */ 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 */ Camera.prototype.restoreState = function () { if (this._restoreStateValues()) { this.onRestoreStateObservable.notifyObservers(this); return true; } return false; }; Camera.prototype.getClassName = function () { return "Camera"; }; /** * @param {boolean} fullDetails - support for multiple levels of logging within scene loading */ 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", { get: function () { return this._globalPosition; }, enumerable: true, configurable: true }); Camera.prototype.getActiveMeshes = function () { return this._activeMeshes; }; 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); }; //Cache Camera.prototype._initCache = function () { _super.prototype._initCache.call(this); this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); this._cache.upVector = new BABYLON.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; }; Camera.prototype._updateCache = function (ignoreParentClass) { if (!ignoreParentClass) { _super.prototype._updateCache.call(this); } this._cache.position.copyFrom(this.position); this._cache.upVector.copyFrom(this.upVector); }; // Synchronized Camera.prototype._isSynchronized = function () { return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix(); }; 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(); }; 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; }; // Controls Camera.prototype.attachControl = function (element, noPreventDefault) { }; Camera.prototype.detachControl = function (element) { }; Camera.prototype.update = function () { this._checkInputs(); if (this.cameraRigMode !== Camera.RIG_MODE_NONE) { this._updateRigCameras(); } }; Camera.prototype._checkInputs = function () { this.onAfterCheckInputsObservable.notifyObservers(this); }; Object.defineProperty(Camera.prototype, "rigCameras", { get: function () { return this._rigCameras; }, enumerable: true, configurable: true }); Object.defineProperty(Camera.prototype, "rigPostProcess", { 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 instanceof BABYLON.PassPostProcess; 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); } } }; Camera.prototype.attachPostProcess = function (postProcess, insertAt) { if (insertAt === void 0) { insertAt = null; } if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) { BABYLON.Tools.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); }; Camera.prototype.detachPostProcess = function (postProcess) { var idx = this._postProcesses.indexOf(postProcess); if (idx !== -1) { this._postProcesses[idx] = null; } this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated }; 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; }; Camera.prototype._getViewMatrix = function () { return BABYLON.Matrix.Identity(); }; Camera.prototype.getViewMatrix = function (force) { if (!force && this._isSynchronizedViewMatrix()) { return this._computedViewMatrix; } this.updateCache(); this._computedViewMatrix = this._getViewMatrix(); this._currentRenderId = this.getScene().getRenderId(); this._childRenderId = this._currentRenderId; 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; }; Camera.prototype.freezeProjectionMatrix = function (projection) { this._doNotComputeProjectionMatrix = true; if (projection !== undefined) { this._projectionMatrix = projection; } }; ; Camera.prototype.unfreezeProjectionMatrix = function () { this._doNotComputeProjectionMatrix = false; }; ; 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) { BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED); } else { BABYLON.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) { BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix); } else { BABYLON.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; }; Camera.prototype.getTranformationMatrix = function () { this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix); return this._transformMatrix; }; Camera.prototype.updateFrustumPlanes = function () { if (!this._refreshFrustumPlanes) { return; } this.getTranformationMatrix(); if (!this._frustumPlanes) { this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix); } else { BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes); } this._refreshFrustumPlanes = false; }; Camera.prototype.isInFrustum = function (target) { this.updateFrustumPlanes(); return target.isInFrustum(this._frustumPlanes); }; Camera.prototype.isCompletelyInFrustum = function (target) { this.updateFrustumPlanes(); return target.isCompletelyInFrustum(this._frustumPlanes); }; 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 = new BABYLON.Vector3(0, 0, 1); var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform); var direction = BABYLON.Vector3.Normalize(forwardWorld); return new BABYLON.Ray(origin, direction, length); }; /** * 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, "leftCamera", { // ---- Camera rigs section ---- get: function () { if (this._rigCameras.length < 1) { return null; } return this._rigCameras[0]; }, enumerable: true, configurable: true }); Object.defineProperty(Camera.prototype, "rightCamera", { get: function () { if (this._rigCameras.length < 2) { return null; } return this._rigCameras[1]; }, enumerable: true, configurable: true }); Camera.prototype.getLeftTarget = function () { if (this._rigCameras.length < 1) { return null; } return this._rigCameras[0].getTarget(); }; Camera.prototype.getRightTarget = function () { if (this._rigCameras.length < 2) { return null; } return this._rigCameras[1].getTarget(); }; 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 = BABYLON.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); var rightCamera = this.createRigCamera(this.name + "_R", 1); if (leftCamera && rightCamera) { this._rigCameras.push(leftCamera); this._rigCameras.push(rightCamera); } } switch (this.cameraRigMode) { case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH: this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]); this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras); break; case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL: case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED: case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER: var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED; this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]); this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz); break; case Camera.RIG_MODE_VR: var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault(); this._rigCameras[0]._cameraRigParams.vrMetrics = metrics; this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0); this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix(); this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix; this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix; this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix; this._rigCameras[1]._cameraRigParams.vrMetrics = metrics; this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0); this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix(); this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix; this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix; this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix; if (metrics.compensateDistortion) { this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics); this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics); } break; case Camera.RIG_MODE_WEBVR: if (rigParams.vrDisplay) { var leftEye = rigParams.vrDisplay.getEyeParameters('left'); var rightEye = rigParams.vrDisplay.getEyeParameters('right'); //Left eye this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0); this._rigCameras[0].setCameraRigParameter("left", true); //leaving this for future reference this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs); this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye); this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData); this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera); this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix(); this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix; this._rigCameras[0].parent = this; this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix; //Right eye this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0); this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye); this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs); this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData); this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera); this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix(); this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix; this._rigCameras[1].parent = this; this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix; if (Camera.UseAlternateWebVRRendering) { this._rigCameras[1]._skipRendering = true; this._rigCameras[0]._alternateCamera = this._rigCameras[1]; } } break; } this._cascadePostProcessesToRigCams(); this.update(); }; Camera.prototype._getVRProjectionMatrix = function () { BABYLON.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. */ Camera.prototype._getWebVRProjectionMatrix = function () { return BABYLON.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. */ Camera.prototype._getWebVRViewMatrix = function () { return BABYLON.Matrix.Identity(); }; Camera.prototype.setCameraRigParameter = function (name, value) { if (!this._cameraRigParams) { this._cameraRigParams = {}; } this._cameraRigParams[name] = value; //provisionnally: if (name === "interaxialDistance") { this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637); } }; /** * needs to be overridden by children so sub has required properties to be copied */ Camera.prototype.createRigCamera = function (name, cameraIndex) { return null; }; /** * May need to be overridden by children */ 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; } // only update viewport when ANAGLYPH if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) { this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport; } }; Camera.prototype._setupInputs = function () { }; Camera.prototype.serialize = function () { var serializationObject = BABYLON.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 BABYLON.Animation.AppendSerializedAnimations(this, serializationObject); serializationObject.ranges = this.serializeAnimationRanges(); return serializationObject; }; Camera.prototype.clone = function (name) { return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this); }; Camera.prototype.getDirection = function (localAxis) { var result = BABYLON.Vector3.Zero(); this.getDirectionToRef(localAxis, result); return result; }; Camera.prototype.getDirectionToRef = function (localAxis, result) { BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result); }; Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) { if (interaxial_distance === void 0) { interaxial_distance = 0; } if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; } switch (type) { case "ArcRotateCamera": return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); }; case "DeviceOrientationCamera": return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); }; case "FollowCamera": return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); }; case "ArcFollowCamera": return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); }; case "GamepadCamera": return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); }; case "TouchCamera": return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); }; case "VirtualJoysticksCamera": return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); }; case "WebVRFreeCamera": return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); }; case "WebVRGamepadCamera": return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); }; case "VRDeviceOrientationFreeCamera": return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); }; case "VRDeviceOrientationGamepadCamera": return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); }; case "AnaglyphArcRotateCamera": return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); }; case "AnaglyphFreeCamera": return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); }; case "AnaglyphGamepadCamera": return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); }; case "AnaglyphUniversalCamera": return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); }; case "StereoscopicArcRotateCamera": return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); }; case "StereoscopicFreeCamera": return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); }; case "StereoscopicGamepadCamera": return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); }; case "StereoscopicUniversalCamera": return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); }; case "FreeCamera": // Forcing Universal here return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); }; default: // Universal Camera is the default value return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); }; } }; Camera.prototype.computeWorldMatrix = function () { return this.getWorldMatrix(); }; Camera.Parse = function (parsedCamera, scene) { var type = parsedCamera.type; var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide); var camera = BABYLON.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(BABYLON.Vector3.FromArray(parsedCamera.position)); } // Target if (parsedCamera.target) { if (camera.setTarget) { camera.setTarget(BABYLON.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]; camera.animations.push(BABYLON.Animation.Parse(parsedAnimation)); } BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene); } if (parsedCamera.autoAnimate) { scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0); } return camera; }; // Statics Camera._PERSPECTIVE_CAMERA = 0; Camera._ORTHOGRAPHIC_CAMERA = 1; Camera._FOVMODE_VERTICAL_FIXED = 0; Camera._FOVMODE_HORIZONTAL_FIXED = 1; Camera._RIG_MODE_NONE = 0; Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10; Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11; Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12; Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13; Camera._RIG_MODE_VR = 20; Camera._RIG_MODE_WEBVR = 21; Camera.ForceAttachControlToAlwaysPreventDefault = false; Camera.UseAlternateWebVRRendering = false; __decorate([ BABYLON.serializeAsVector3() ], Camera.prototype, "position", void 0); __decorate([ BABYLON.serializeAsVector3() ], Camera.prototype, "upVector", void 0); __decorate([ BABYLON.serialize() ], Camera.prototype, "orthoLeft", void 0); __decorate([ BABYLON.serialize() ], Camera.prototype, "orthoRight", void 0); __decorate([ BABYLON.serialize() ], Camera.prototype, "orthoBottom", void 0); __decorate([ BABYLON.serialize() ], Camera.prototype, "orthoTop", void 0); __decorate([ BABYLON.serialize() ], Camera.prototype, "fov", void 0); __decorate([ BABYLON.serialize() ], Camera.prototype, "minZ", void 0); __decorate([ BABYLON.serialize() ], Camera.prototype, "maxZ", void 0); __decorate([ BABYLON.serialize() ], Camera.prototype, "inertia", void 0); __decorate([ BABYLON.serialize() ], Camera.prototype, "mode", void 0); __decorate([ BABYLON.serialize() ], Camera.prototype, "layerMask", void 0); __decorate([ BABYLON.serialize() ], Camera.prototype, "fovMode", void 0); __decorate([ BABYLON.serialize() ], Camera.prototype, "cameraRigMode", void 0); __decorate([ BABYLON.serialize() ], Camera.prototype, "interaxialDistance", void 0); __decorate([ BABYLON.serialize() ], Camera.prototype, "isStereoscopicSideBySide", void 0); return Camera; }(BABYLON.Node)); BABYLON.Camera = Camera; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.camera.js.map var BABYLON; (function (BABYLON) { var RenderingManager = /** @class */ (function () { function RenderingManager(scene) { this._renderingGroups = new Array(); this._autoClearDepthStencil = {}; this._customOpaqueSortCompareFn = {}; this._customAlphaTestSortCompareFn = {}; this._customTransparentSortCompareFn = {}; this._renderinGroupInfo = null; this._scene = scene; for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) { this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true }; } } RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) { if (depth === void 0) { depth = true; } if (stencil === void 0) { stencil = true; } if (this._depthStencilBufferAlreadyCleaned) { return; } this._scene.getEngine().clear(null, false, depth, stencil); this._depthStencilBufferAlreadyCleaned = true; }; RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) { // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null; var info = null; if (observable) { if (!this._renderinGroupInfo) { this._renderinGroupInfo = new BABYLON.RenderingGroupInfo(); } info = this._renderinGroupInfo; info.scene = this._scene; info.camera = this._scene.activeCamera; } // Dispatch sprites if (renderSprites) { for (var index = 0; index < this._scene.spriteManagers.length; index++) { var manager = this._scene.spriteManagers[index]; this.dispatchSprites(manager); } } // Render for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) { this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS; var renderingGroup = this._renderingGroups[index]; if (!renderingGroup && !observable) continue; var renderingGroupMask = 0; // Fire PRECLEAR stage if (observable && info) { renderingGroupMask = Math.pow(2, index); info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR; info.renderingGroupId = index; observable.notifyObservers(info, renderingGroupMask); } // Clear depth/stencil if needed if (RenderingManager.AUTOCLEAR) { var autoClear = this._autoClearDepthStencil[index]; if (autoClear && autoClear.autoClear) { this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil); } } if (observable && info) { // Fire PREOPAQUE stage info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE; observable.notifyObservers(info, renderingGroupMask); // Fire PRETRANSPARENT stage info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT; observable.notifyObservers(info, renderingGroupMask); } if (renderingGroup) renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes); // Fire POSTTRANSPARENT stage if (observable && info) { info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT; observable.notifyObservers(info, renderingGroupMask); } } }; RenderingManager.prototype.reset = function () { for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) { var renderingGroup = this._renderingGroups[index]; if (renderingGroup) { renderingGroup.prepare(); } } }; RenderingManager.prototype.dispose = function () { this.freeRenderingGroups(); this._renderingGroups.length = 0; }; /** * Clear the info related to rendering groups preventing retention points during dispose. */ RenderingManager.prototype.freeRenderingGroups = function () { for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) { var renderingGroup = this._renderingGroups[index]; if (renderingGroup) { renderingGroup.dispose(); } } }; RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) { if (this._renderingGroups[renderingGroupId] === undefined) { this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]); } }; RenderingManager.prototype.dispatchSprites = function (spriteManager) { var renderingGroupId = spriteManager.renderingGroupId || 0; this._prepareRenderingGroup(renderingGroupId); this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager); }; RenderingManager.prototype.dispatchParticles = function (particleSystem) { var renderingGroupId = particleSystem.renderingGroupId || 0; this._prepareRenderingGroup(renderingGroupId); this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem); }; /** * @param subMesh The submesh to dispatch * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance. */ RenderingManager.prototype.dispatch = function (subMesh, mesh, material) { if (mesh === undefined) { mesh = subMesh.getMesh(); } var renderingGroupId = mesh.renderingGroupId || 0; this._prepareRenderingGroup(renderingGroupId); this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material); }; /** * 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. */ RenderingManager.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._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn; this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn; this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn; if (this._renderingGroups[renderingGroupId]) { var group = this._renderingGroups[renderingGroupId]; group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId]; group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId]; group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId]; } }; /** * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups. * * @param renderingGroupId The rendering group id corresponding to its index * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true. * @param depth Automatically clears depth between groups if true and autoClear is true. * @param stencil Automatically clears stencil between groups if true and autoClear is true. */ RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) { if (depth === void 0) { depth = true; } if (stencil === void 0) { stencil = true; } this._autoClearDepthStencil[renderingGroupId] = { autoClear: autoClearDepthStencil, depth: depth, stencil: stencil }; }; /** * The max id used for rendering groups (not included) */ RenderingManager.MAX_RENDERINGGROUPS = 4; /** * The min id used for rendering groups (included) */ RenderingManager.MIN_RENDERINGGROUPS = 0; /** * Used to globally prevent autoclearing scenes. */ RenderingManager.AUTOCLEAR = true; return RenderingManager; }()); BABYLON.RenderingManager = RenderingManager; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.renderingManager.js.map var BABYLON; (function (BABYLON) { var RenderingGroup = /** @class */ (function () { /** * Creates a new rendering group. * @param index The rendering group index * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied */ function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) { if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; } if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; } if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; } this.index = index; this._opaqueSubMeshes = new BABYLON.SmartArray(256); this._transparentSubMeshes = new BABYLON.SmartArray(256); this._alphaTestSubMeshes = new BABYLON.SmartArray(256); this._depthOnlySubMeshes = new BABYLON.SmartArray(256); this._particleSystems = new BABYLON.SmartArray(256); this._spriteManagers = new BABYLON.SmartArray(256); this._edgesRenderers = new BABYLON.SmartArray(16); this._scene = scene; this.opaqueSortCompareFn = opaqueSortCompareFn; this.alphaTestSortCompareFn = alphaTestSortCompareFn; this.transparentSortCompareFn = transparentSortCompareFn; } Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", { /** * Set the opaque sort comparison function. * If null the sub meshes will be render in the order they were created */ set: function (value) { this._opaqueSortCompareFn = value; if (value) { this._renderOpaque = this.renderOpaqueSorted; } else { this._renderOpaque = RenderingGroup.renderUnsorted; } }, enumerable: true, configurable: true }); Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", { /** * Set the alpha test sort comparison function. * If null the sub meshes will be render in the order they were created */ set: function (value) { this._alphaTestSortCompareFn = value; if (value) { this._renderAlphaTest = this.renderAlphaTestSorted; } else { this._renderAlphaTest = RenderingGroup.renderUnsorted; } }, enumerable: true, configurable: true }); Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", { /** * Set the transparent sort comparison function. * If null the sub meshes will be render in the order they were created */ set: function (value) { if (value) { this._transparentSortCompareFn = value; } else { this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare; } this._renderTransparent = this.renderTransparentSorted; }, enumerable: true, configurable: true }); /** * Render all the sub meshes contained in the group. * @param customRenderFunction Used to override the default render behaviour of the group. * @returns true if rendered some submeshes. */ RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) { if (customRenderFunction) { customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes); return; } var engine = this._scene.getEngine(); // Depth only if (this._depthOnlySubMeshes.length !== 0) { engine.setColorWrite(false); this._renderAlphaTest(this._depthOnlySubMeshes); engine.setColorWrite(true); } // Opaque if (this._opaqueSubMeshes.length !== 0) { this._renderOpaque(this._opaqueSubMeshes); } // Alpha test if (this._alphaTestSubMeshes.length !== 0) { this._renderAlphaTest(this._alphaTestSubMeshes); } var stencilState = engine.getStencilBuffer(); engine.setStencilBuffer(false); // Sprites if (renderSprites) { this._renderSprites(); } // Particles if (renderParticles) { this._renderParticles(activeMeshes); } if (this.onBeforeTransparentRendering) { this.onBeforeTransparentRendering(); } // Transparent if (this._transparentSubMeshes.length !== 0) { this._renderTransparent(this._transparentSubMeshes); engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE); } // Set back stencil to false in case it changes before the edge renderer. engine.setStencilBuffer(false); // Edges for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) { this._edgesRenderers.data[edgesRendererIndex].render(); } // Restore Stencil state. engine.setStencilBuffer(stencilState); }; /** * Renders the opaque submeshes in the order from the opaqueSortCompareFn. * @param subMeshes The submeshes to render */ RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) { return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false); }; /** * Renders the opaque submeshes in the order from the alphatestSortCompareFn. * @param subMeshes The submeshes to render */ RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) { return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false); }; /** * Renders the opaque submeshes in the order from the transparentSortCompareFn. * @param subMeshes The submeshes to render */ RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) { return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true); }; /** * Renders the submeshes in a specified order. * @param subMeshes The submeshes to sort before render * @param sortCompareFn The comparison function use to sort * @param cameraPosition The camera position use to preprocess the submeshes to help sorting * @param transparent Specifies to activate blending if true */ RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) { var subIndex = 0; var subMesh; var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero(); for (; subIndex < subMeshes.length; subIndex++) { subMesh = subMeshes.data[subIndex]; subMesh._alphaIndex = subMesh.getMesh().alphaIndex; subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length(); } var sortedArray = subMeshes.data.slice(0, subMeshes.length); if (sortCompareFn) { sortedArray.sort(sortCompareFn); } for (subIndex = 0; subIndex < sortedArray.length; subIndex++) { subMesh = sortedArray[subIndex]; if (transparent) { var material = subMesh.getMaterial(); if (material && material.needDepthPrePass) { var engine = material.getScene().getEngine(); engine.setColorWrite(false); engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE); subMesh.render(false); engine.setColorWrite(true); } } subMesh.render(transparent); } }; /** * Renders the submeshes in the order they were dispatched (no sort applied). * @param subMeshes The submeshes to render */ RenderingGroup.renderUnsorted = function (subMeshes) { for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) { var submesh = subMeshes.data[subIndex]; submesh.render(false); } }; /** * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) * are rendered back to front if in the same alpha index. * * @param a The first submesh * @param b The second submesh * @returns The result of the comparison */ RenderingGroup.defaultTransparentSortCompare = function (a, b) { // Alpha index first if (a._alphaIndex > b._alphaIndex) { return 1; } if (a._alphaIndex < b._alphaIndex) { return -1; } // Then distance to camera return RenderingGroup.backToFrontSortCompare(a, b); }; /** * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) * are rendered back to front. * * @param a The first submesh * @param b The second submesh * @returns The result of the comparison */ RenderingGroup.backToFrontSortCompare = function (a, b) { // Then distance to camera if (a._distanceToCamera < b._distanceToCamera) { return 1; } if (a._distanceToCamera > b._distanceToCamera) { return -1; } return 0; }; /** * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) * are rendered front to back (prevent overdraw). * * @param a The first submesh * @param b The second submesh * @returns The result of the comparison */ RenderingGroup.frontToBackSortCompare = function (a, b) { // Then distance to camera if (a._distanceToCamera < b._distanceToCamera) { return -1; } if (a._distanceToCamera > b._distanceToCamera) { return 1; } return 0; }; /** * Resets the different lists of submeshes to prepare a new frame. */ RenderingGroup.prototype.prepare = function () { this._opaqueSubMeshes.reset(); this._transparentSubMeshes.reset(); this._alphaTestSubMeshes.reset(); this._depthOnlySubMeshes.reset(); this._particleSystems.reset(); this._spriteManagers.reset(); this._edgesRenderers.reset(); }; RenderingGroup.prototype.dispose = function () { this._opaqueSubMeshes.dispose(); this._transparentSubMeshes.dispose(); this._alphaTestSubMeshes.dispose(); this._depthOnlySubMeshes.dispose(); this._particleSystems.dispose(); this._spriteManagers.dispose(); this._edgesRenderers.dispose(); }; /** * Inserts the submesh in its correct queue depending on its material. * @param subMesh The submesh to dispatch * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance. */ RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) { // Get mesh and materials if not provided if (mesh === undefined) { mesh = subMesh.getMesh(); } if (material === undefined) { material = subMesh.getMaterial(); } if (material === null || material === undefined) { return; } if (material.needAlphaBlendingForMesh(mesh)) { // Transparent this._transparentSubMeshes.push(subMesh); } else if (material.needAlphaTesting()) { // Alpha test if (material.needDepthPrePass) { this._depthOnlySubMeshes.push(subMesh); } this._alphaTestSubMeshes.push(subMesh); } else { if (material.needDepthPrePass) { this._depthOnlySubMeshes.push(subMesh); } this._opaqueSubMeshes.push(subMesh); // Opaque } if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) { this._edgesRenderers.push(mesh._edgesRenderer); } }; RenderingGroup.prototype.dispatchSprites = function (spriteManager) { this._spriteManagers.push(spriteManager); }; RenderingGroup.prototype.dispatchParticles = function (particleSystem) { this._particleSystems.push(particleSystem); }; RenderingGroup.prototype._renderParticles = function (activeMeshes) { if (this._particleSystems.length === 0) { return; } // Particles var activeCamera = this._scene.activeCamera; this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene); for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) { var particleSystem = this._particleSystems.data[particleIndex]; if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) { continue; } var emitter = particleSystem.emitter; if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) { this._scene._activeParticles.addCount(particleSystem.render(), false); } } this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene); }; RenderingGroup.prototype._renderSprites = function () { if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) { return; } // Sprites var activeCamera = this._scene.activeCamera; this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene); for (var id = 0; id < this._spriteManagers.length; id++) { var spriteManager = this._spriteManagers.data[id]; if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) { spriteManager.render(); } } this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene); }; return RenderingGroup; }()); BABYLON.RenderingGroup = RenderingGroup; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.renderingGroup.js.map var BABYLON; (function (BABYLON) { /** @hidden */ var ClickInfo = /** @class */ (function () { function ClickInfo() { this._singleClick = false; this._doubleClick = false; this._hasSwiped = false; this._ignore = false; } Object.defineProperty(ClickInfo.prototype, "singleClick", { get: function () { return this._singleClick; }, set: function (b) { this._singleClick = b; }, enumerable: true, configurable: true }); Object.defineProperty(ClickInfo.prototype, "doubleClick", { get: function () { return this._doubleClick; }, set: function (b) { this._doubleClick = b; }, enumerable: true, configurable: true }); Object.defineProperty(ClickInfo.prototype, "hasSwiped", { get: function () { return this._hasSwiped; }, set: function (b) { this._hasSwiped = b; }, enumerable: true, configurable: true }); Object.defineProperty(ClickInfo.prototype, "ignore", { get: function () { return this._ignore; }, set: function (b) { this._ignore = b; }, enumerable: true, configurable: true }); return ClickInfo; }()); /** * This class is used by the onRenderingGroupObservable */ var RenderingGroupInfo = /** @class */ (function () { function RenderingGroupInfo() { } /** * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared * This stage will be fired no matter what */ RenderingGroupInfo.STAGE_PRECLEAR = 1; /** * Called before opaque object are rendered. * This stage will be fired only if there's 3D Opaque content to render */ RenderingGroupInfo.STAGE_PREOPAQUE = 2; /** * Called after the opaque objects are rendered and before the transparent ones * This stage will be fired only if there's 3D transparent content to render */ RenderingGroupInfo.STAGE_PRETRANSPARENT = 3; /** * Called after the transparent object are rendered, last hook of the renderingGroup phase * This stage will be fired no matter what */ RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4; return RenderingGroupInfo; }()); BABYLON.RenderingGroupInfo = RenderingGroupInfo; /** * Represents a scene to be rendered by the engine. * @see http://doc.babylonjs.com/features/scene */ var Scene = /** @class */ (function () { /** * Creates a new Scene * @param engine defines the engine to use to render this scene */ function Scene(engine) { // Members /** * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame */ this.autoClear = true; /** * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame */ this.autoClearDepthAndStencil = true; /** * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0)) */ this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0); /** * Defines the color used to simulate the ambient color (Default is (0, 0, 0)) */ this.ambientColor = new BABYLON.Color3(0, 0, 0); this._forceWireframe = false; this._forcePointsCloud = false; /** * Gets or sets a boolean indicating if all bounding boxes must be rendered */ this.forceShowBoundingBoxes = false; /** * Gets or sets a boolean indicating if animations are enabled */ this.animationsEnabled = true; this._animationPropertiesOverride = null; /** * Gets or sets a boolean indicating if a constant deltatime has to be used * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate */ this.useConstantAnimationDeltaTime = false; /** * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated * Please note that it requires to run a ray cast through the scene on every frame */ this.constantlyUpdateMeshUnderPointer = false; /** * Defines the HTML cursor to use when hovering over interactive elements */ this.hoverCursor = "pointer"; /** * Defines the HTML default cursor to use (empty by default) */ this.defaultCursor = ""; /** * This is used to call preventDefault() on pointer down * in order to block unwanted artifacts like system double clicks */ this.preventDefaultOnPointerDown = true; // Metadata /** * Gets or sets user defined metadata */ this.metadata = null; /** * Use this array to add regular expressions used to disable offline support for specific urls */ this.disableOfflineSupportExceptionRules = new Array(); /** * An event triggered when the scene is disposed. */ this.onDisposeObservable = new BABYLON.Observable(); this._onDisposeObserver = null; /** * An event triggered before rendering the scene (right after animations and physics) */ this.onBeforeRenderObservable = new BABYLON.Observable(); this._onBeforeRenderObserver = null; /** * An event triggered after rendering the scene */ this.onAfterRenderObservable = new BABYLON.Observable(); this._onAfterRenderObserver = null; /** * An event triggered before animating the scene */ this.onBeforeAnimationsObservable = new BABYLON.Observable(); /** * An event triggered after animations processing */ this.onAfterAnimationsObservable = new BABYLON.Observable(); /** * An event triggered before draw calls are ready to be sent */ this.onBeforeDrawPhaseObservable = new BABYLON.Observable(); /** * An event triggered after draw calls have been sent */ this.onAfterDrawPhaseObservable = new BABYLON.Observable(); /** * An event triggered when physic simulation is about to be run */ this.onBeforePhysicsObservable = new BABYLON.Observable(); /** * An event triggered when physic simulation has been done */ this.onAfterPhysicsObservable = new BABYLON.Observable(); /** * An event triggered when the scene is ready */ this.onReadyObservable = new BABYLON.Observable(); /** * An event triggered before rendering a camera */ this.onBeforeCameraRenderObservable = new BABYLON.Observable(); this._onBeforeCameraRenderObserver = null; /** * An event triggered after rendering a camera */ this.onAfterCameraRenderObservable = new BABYLON.Observable(); this._onAfterCameraRenderObserver = null; /** * An event triggered when active meshes evaluation is about to start */ this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable(); /** * An event triggered when active meshes evaluation is done */ this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable(); /** * An event triggered when particles rendering is about to start * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well) */ this.onBeforeParticlesRenderingObservable = new BABYLON.Observable(); /** * An event triggered when particles rendering is done * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well) */ this.onAfterParticlesRenderingObservable = new BABYLON.Observable(); /** * An event triggered when sprites rendering is about to start * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well) */ this.onBeforeSpritesRenderingObservable = new BABYLON.Observable(); /** * An event triggered when sprites rendering is done * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well) */ this.onAfterSpritesRenderingObservable = new BABYLON.Observable(); /** * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed */ this.onDataLoadedObservable = new BABYLON.Observable(); /** * An event triggered when a camera is created */ this.onNewCameraAddedObservable = new BABYLON.Observable(); /** * An event triggered when a camera is removed */ this.onCameraRemovedObservable = new BABYLON.Observable(); /** * An event triggered when a light is created */ this.onNewLightAddedObservable = new BABYLON.Observable(); /** * An event triggered when a light is removed */ this.onLightRemovedObservable = new BABYLON.Observable(); /** * An event triggered when a geometry is created */ this.onNewGeometryAddedObservable = new BABYLON.Observable(); /** * An event triggered when a geometry is removed */ this.onGeometryRemovedObservable = new BABYLON.Observable(); /** * An event triggered when a transform node is created */ this.onNewTransformNodeAddedObservable = new BABYLON.Observable(); /** * An event triggered when a transform node is removed */ this.onTransformNodeRemovedObservable = new BABYLON.Observable(); /** * An event triggered when a mesh is created */ this.onNewMeshAddedObservable = new BABYLON.Observable(); /** * An event triggered when a mesh is removed */ this.onMeshRemovedObservable = new BABYLON.Observable(); /** * An event triggered when render targets are about to be rendered * Can happen multiple times per frame. */ this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable(); /** * An event triggered when render targets were rendered. * Can happen multiple times per frame. */ this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable(); /** * An event triggered before calculating deterministic simulation step */ this.onBeforeStepObservable = new BABYLON.Observable(); /** * An event triggered after calculating deterministic simulation step */ this.onAfterStepObservable = new BABYLON.Observable(); /** * This Observable will be triggered for each stage of each renderingGroup of each rendered camera. * The RenderinGroupInfo class contains all the information about the context in which the observable is called * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3) */ this.onRenderingGroupObservable = new BABYLON.Observable(); // Animations /** * Gets a list of Animations associated with the scene */ this.animations = []; this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256); /** * This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance). * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true */ this.onPrePointerObservable = new BABYLON.Observable(); /** * Observable event triggered each time an input event is received from the rendering canvas */ this.onPointerObservable = new BABYLON.Observable(); this._meshPickProceed = false; this._currentPickResult = null; this._previousPickResult = null; this._totalPointersPressed = 0; this._doubleClickOccured = false; /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */ this.cameraToUseForPointers = null; this._startingPointerPosition = new BABYLON.Vector2(0, 0); this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0); this._startingPointerTime = 0; this._previousStartingPointerTime = 0; this._pointerCaptures = {}; // Deterministic lockstep this._timeAccumulator = 0; this._currentStepId = 0; this._currentInternalStep = 0; // Keyboard /** * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl() * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true */ this.onPreKeyboardObservable = new BABYLON.Observable(); /** * Observable event triggered each time an keyboard event is received from the hosting window */ this.onKeyboardObservable = new BABYLON.Observable(); // Coordinates system this._useRightHandedSystem = false; // Fog this._fogEnabled = true; this._fogMode = Scene.FOGMODE_NONE; /** * Gets or sets the fog color to use * @see http://doc.babylonjs.com/babylon101/environment#fog */ this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3); /** * Gets or sets the fog density to use * @see http://doc.babylonjs.com/babylon101/environment#fog */ this.fogDensity = 0.1; /** * Gets or sets the fog start distance to use * @see http://doc.babylonjs.com/babylon101/environment#fog */ this.fogStart = 0; /** * Gets or sets the fog end distance to use * @see http://doc.babylonjs.com/babylon101/environment#fog */ this.fogEnd = 1000.0; // Lights this._shadowsEnabled = true; this._lightsEnabled = true; /** * All of the lights added to this scene * @see http://doc.babylonjs.com/babylon101/lights */ this.lights = new Array(); // Cameras /** All of the cameras added to this scene. * @see http://doc.babylonjs.com/babylon101/cameras */ this.cameras = new Array(); /** All of the active cameras added to this scene. */ this.activeCameras = new Array(); // Meshes /** * All of the tranform nodes added to this scene * @see http://doc.babylonjs.com/how_to/transformnode */ this.transformNodes = new Array(); /** * All of the (abstract) meshes added to this scene */ this.meshes = new Array(); /** * All of the animation groups added to this scene * @see http://doc.babylonjs.com/how_to/group */ this.animationGroups = new Array(); // Geometries this._geometries = new Array(); /** * All of the materials added to this scene * @see http://doc.babylonjs.com/babylon101/materials */ this.materials = new Array(); /** * All of the multi-materials added to this scene * @see http://doc.babylonjs.com/how_to/multi_materials */ this.multiMaterials = new Array(); // Textures this._texturesEnabled = true; /** * All of the textures added to this scene */ this.textures = new Array(); // Particles /** * Gets or sets a boolean indicating if particles are enabled on this scene */ this.particlesEnabled = true; /** * All of the particle systems added to this scene * @see http://doc.babylonjs.com/babylon101/particles */ this.particleSystems = new Array(); // Sprites /** * Gets or sets a boolean indicating if sprites are enabled on this scene */ this.spritesEnabled = true; /** * All of the sprite managers added to this scene * @see http://doc.babylonjs.com/babylon101/sprites */ this.spriteManagers = new Array(); /** * The list of layers (background and foreground) of the scene */ this.layers = new Array(); /** * The list of effect layers (highlights/glow) added to the scene * @see http://doc.babylonjs.com/how_to/highlight_layer * @see http://doc.babylonjs.com/how_to/glow_layer */ this.effectLayers = new Array(); // Skeletons this._skeletonsEnabled = true; /** * The list of skeletons added to the scene * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons */ this.skeletons = new Array(); // Morph targets /** * The list of morph target managers added to the scene * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh */ this.morphTargetManagers = new Array(); // Lens flares /** * Gets or sets a boolean indicating if lens flares are enabled on this scene */ this.lensFlaresEnabled = true; /** * The list of lens flare system added to the scene * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares */ this.lensFlareSystems = new Array(); // Collisions /** * Gets or sets a boolean indicating if collisions are enabled on this scene * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity */ this.collisionsEnabled = true; /** * Defines the gravity applied to this scene (used only for collisions) * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity */ this.gravity = new BABYLON.Vector3(0, -9.807, 0); // Postprocesses /** * Gets or sets a boolean indicating if postprocesses are enabled on this scene */ this.postProcessesEnabled = true; /** * The list of postprocesses added to the scene */ this.postProcesses = new Array(); // Customs render targets /** * Gets or sets a boolean indicating if render targets are enabled on this scene */ this.renderTargetsEnabled = true; /** * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com */ this.dumpNextRenderTargets = false; /** * The list of user defined render targets added to the scene */ this.customRenderTargets = new Array(); /** * Gets the list of meshes imported to the scene through SceneLoader */ this.importedMeshesFiles = new Array(); // Probes /** * Gets or sets a boolean indicating if probes are enabled on this scene */ this.probesEnabled = true; /** * The list of reflection probes added to the scene * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes */ this.reflectionProbes = new Array(); /** @hidden */ this._actionManagers = new Array(); this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256); // Procedural textures /** * Gets or sets a boolean indicating if procedural textures are enabled on this scene */ this.proceduralTexturesEnabled = true; /** * The list of procedural textures added to the scene * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures */ this.proceduralTextures = new Array(); /** * The list of sound tracks added to the scene * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music */ this.soundTracks = new Array(); this._audioEnabled = true; this._headphone = false; // Performance counters this._totalVertices = new BABYLON.PerfCounter(); /** @hidden */ this._activeIndices = new BABYLON.PerfCounter(); /** @hidden */ this._activeParticles = new BABYLON.PerfCounter(); /** @hidden */ this._activeBones = new BABYLON.PerfCounter(); this._animationTime = 0; /** * Gets or sets a general scale for animation speed * @see https://www.babylonjs-playground.com/#IBU2W7#3 */ this.animationTimeScale = 1; this._renderId = 0; this._executeWhenReadyTimeoutId = -1; this._intermediateRendering = false; this._viewUpdateFlag = -1; this._projectionUpdateFlag = -1; this._alternateViewUpdateFlag = -1; this._alternateProjectionUpdateFlag = -1; /** @hidden */ this._toBeDisposed = new BABYLON.SmartArray(256); this._activeRequests = new Array(); this._pendingData = new Array(); this._isDisposed = false; /** * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound) */ this.dispatchAllSubMeshesOfActiveMeshes = false; this._activeMeshes = new BABYLON.SmartArray(256); this._processedMaterials = new BABYLON.SmartArray(256); this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256); /** @hidden */ this._activeParticleSystems = new BABYLON.SmartArray(256); this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32); this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32); /** @hidden */ this._activeAnimatables = new Array(); this._transformMatrix = BABYLON.Matrix.Zero(); this._useAlternateCameraConfiguration = false; this._alternateRendering = false; /** * Gets or sets a boolean indicating if lights must be sorted by priority (off by default) * This is useful if there are more lights that the maximum simulteanous authorized */ this.requireLightSorting = false; this._depthRenderer = {}; this._activeMeshesFrozen = false; this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null; this._engine = engine || BABYLON.Engine.LastCreatedEngine; this._engine.scenes.push(this); this._uid = null; this._renderingManager = new BABYLON.RenderingManager(this); this.postProcessManager = new BABYLON.PostProcessManager(this); if (BABYLON.OutlineRenderer) { this._outlineRenderer = new BABYLON.OutlineRenderer(this); } if (BABYLON.Tools.IsWindowObjectExist()) { this.attachControl(); } //simplification queue if (BABYLON.SimplificationQueue) { this.simplificationQueue = new BABYLON.SimplificationQueue(); } //collision coordinator initialization. For now legacy per default. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded)); // Uniform Buffer this._createUbo(); // Default Image processing definition. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration(); } Object.defineProperty(Scene, "FOGMODE_NONE", { /** The fog is deactivated */ get: function () { return Scene._FOGMODE_NONE; }, enumerable: true, configurable: true }); Object.defineProperty(Scene, "FOGMODE_EXP", { /** The fog density is following an exponential function */ get: function () { return Scene._FOGMODE_EXP; }, enumerable: true, configurable: true }); Object.defineProperty(Scene, "FOGMODE_EXP2", { /** The fog density is following an exponential function faster than FOGMODE_EXP */ get: function () { return Scene._FOGMODE_EXP2; }, enumerable: true, configurable: true }); Object.defineProperty(Scene, "FOGMODE_LINEAR", { /** The fog density is following a linear function. */ get: function () { return Scene._FOGMODE_LINEAR; }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "environmentTexture", { /** * Texture used in all pbr material as the reflection texture. * As in the majority of the scene they are the same (exception for multi room and so on), * this is easier to reference from here than from all the materials. */ get: function () { return this._environmentTexture; }, /** * Texture used in all pbr material as the reflection texture. * As in the majority of the scene they are the same (exception for multi room and so on), * this is easier to set here than in all the materials. */ set: function (value) { if (this._environmentTexture === value) { return; } this._environmentTexture = value; this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", { /** * Default image processing configuration used either in the rendering * Forward main pass or through the imageProcessingPostProcess if present. * As in the majority of the scene they are the same (exception for multi camera), * this is easier to reference from here than from all the materials and post process. * * No setter as we it is a shared configuration, you can set the values instead. */ get: function () { return this._imageProcessingConfiguration; }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "forceWireframe", { get: function () { return this._forceWireframe; }, /** * Gets or sets a boolean indicating if all rendering must be done in wireframe */ set: function (value) { if (this._forceWireframe === value) { return; } this._forceWireframe = value; this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "forcePointsCloud", { get: function () { return this._forcePointsCloud; }, /** * Gets or sets a boolean indicating if all rendering must be done in point cloud */ set: function (value) { if (this._forcePointsCloud === value) { return; } this._forcePointsCloud = value; this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "animationPropertiesOverride", { /** * Gets or sets the animation properties override */ get: function () { return this._animationPropertiesOverride; }, set: function (value) { this._animationPropertiesOverride = value; }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "onDispose", { /** Sets a function to be executed when this scene is disposed. */ set: function (callback) { if (this._onDisposeObserver) { this.onDisposeObservable.remove(this._onDisposeObserver); } this._onDisposeObserver = this.onDisposeObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "beforeRender", { /** Sets a function to be executed before rendering this scene */ set: function (callback) { if (this._onBeforeRenderObserver) { this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver); } if (callback) { this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback); } }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "afterRender", { /** Sets a function to be executed after rendering this scene */ set: function (callback) { if (this._onAfterRenderObserver) { this.onAfterRenderObservable.remove(this._onAfterRenderObserver); } if (callback) { this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback); } }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "beforeCameraRender", { /** Sets a function to be executed before rendering a camera*/ set: function (callback) { if (this._onBeforeCameraRenderObserver) { this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver); } this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "afterCameraRender", { /** Sets a function to be executed after rendering a camera*/ set: function (callback) { if (this._onAfterCameraRenderObserver) { this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver); } this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "gamepadManager", { /** * Gets the gamepad manager associated with the scene * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads */ get: function () { if (!this._gamepadManager) { this._gamepadManager = new BABYLON.GamepadManager(this); } return this._gamepadManager; }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "unTranslatedPointer", { /** * Gets the pointer coordinates without any translation (ie. straight out of the pointer event) */ get: function () { return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY); }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "useRightHandedSystem", { get: function () { return this._useRightHandedSystem; }, /** * Gets or sets a boolean indicating if the scene must use right-handed coordinates system */ set: function (value) { if (this._useRightHandedSystem === value) { return; } this._useRightHandedSystem = value; this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag); }, enumerable: true, configurable: true }); /** * Sets the step Id used by deterministic lock step * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep * @param newStepId defines the step Id */ Scene.prototype.setStepId = function (newStepId) { this._currentStepId = newStepId; }; ; /** * Gets the step Id used by deterministic lock step * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep * @returns the step Id */ Scene.prototype.getStepId = function () { return this._currentStepId; }; ; /** * Gets the internal step used by deterministic lock step * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep * @returns the internal step */ Scene.prototype.getInternalStep = function () { return this._currentInternalStep; }; ; Object.defineProperty(Scene.prototype, "fogEnabled", { get: function () { return this._fogEnabled; }, /** * Gets or sets a boolean indicating if fog is enabled on this scene * @see http://doc.babylonjs.com/babylon101/environment#fog */ set: function (value) { if (this._fogEnabled === value) { return; } this._fogEnabled = value; this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "fogMode", { get: function () { return this._fogMode; }, /** * Gets or sets the fog mode to use * @see http://doc.babylonjs.com/babylon101/environment#fog */ set: function (value) { if (this._fogMode === value) { return; } this._fogMode = value; this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "shadowsEnabled", { get: function () { return this._shadowsEnabled; }, /** * Gets or sets a boolean indicating if shadows are enabled on this scene */ set: function (value) { if (this._shadowsEnabled === value) { return; } this._shadowsEnabled = value; this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "lightsEnabled", { get: function () { return this._lightsEnabled; }, /** * Gets or sets a boolean indicating if lights are enabled on this scene */ set: function (value) { if (this._lightsEnabled === value) { return; } this._lightsEnabled = value; this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "defaultMaterial", { /** The default material used on meshes when no material is affected */ get: function () { if (!this._defaultMaterial) { this._defaultMaterial = new BABYLON.StandardMaterial("default material", this); } return this._defaultMaterial; }, /** The default material used on meshes when no material is affected */ set: function (value) { this._defaultMaterial = value; }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "texturesEnabled", { get: function () { return this._texturesEnabled; }, /** * Gets or sets a boolean indicating if textures are enabled on this scene */ set: function (value) { if (this._texturesEnabled === value) { return; } this._texturesEnabled = value; this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "skeletonsEnabled", { get: function () { return this._skeletonsEnabled; }, /** * Gets or sets a boolean indicating if skeletons are enabled on this scene */ set: function (value) { if (this._skeletonsEnabled === value) { return; } this._skeletonsEnabled = value; this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", { /** * Gets the postprocess render pipeline manager * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline */ get: function () { if (!this._postProcessRenderPipelineManager) { this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager(); } return this._postProcessRenderPipelineManager; }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "mainSoundTrack", { /** * Gets the main soundtrack associated with the scene */ get: function () { if (!this._mainSoundTrack) { this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true }); } return this._mainSoundTrack; }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", { /** @hidden */ get: function () { return this._alternateRendering; }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "frustumPlanes", { /** * Gets the list of frustum planes (built from the active camera) */ get: function () { return this._frustumPlanes; }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "geometryBufferRenderer", { /** * Gets the current geometry buffer associated to the scene. */ get: function () { return this._geometryBufferRenderer; }, /** * Sets the current geometry buffer for the scene. */ set: function (geometryBufferRenderer) { if (geometryBufferRenderer && geometryBufferRenderer.isSupported) { this._geometryBufferRenderer = geometryBufferRenderer; } }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "debugLayer", { /** * Gets the debug layer (aka Inspector) associated with the scene * @see http://doc.babylonjs.com/features/playground_debuglayer */ get: function () { if (!this._debugLayer) { this._debugLayer = new BABYLON.DebugLayer(this); } return this._debugLayer; }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "workerCollisions", { /** * Gets a boolean indicating if collisions are processed on a web worker * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21 */ get: function () { return this._workerCollisions; }, set: function (enabled) { if (!BABYLON.CollisionCoordinatorLegacy) { return; } enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker); this._workerCollisions = enabled; if (this.collisionCoordinator) { this.collisionCoordinator.destroy(); } this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy(); this.collisionCoordinator.init(this); }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "selectionOctree", { /** * Gets the octree used to boost mesh selection (picking) * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees */ get: function () { return this._selectionOctree; }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "meshUnderPointer", { /** * Gets the mesh that is currently under the pointer */ get: function () { return this._pointerOverMesh; }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "pointerX", { /** * Gets the current on-screen X position of the pointer */ get: function () { return this._pointerX; }, enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "pointerY", { /** * Gets the current on-screen Y position of the pointer */ get: function () { return this._pointerY; }, enumerable: true, configurable: true }); /** * Gets the cached material (ie. the latest rendered one) * @returns the cached material */ Scene.prototype.getCachedMaterial = function () { return this._cachedMaterial; }; /** * Gets the cached effect (ie. the latest rendered one) * @returns the cached effect */ Scene.prototype.getCachedEffect = function () { return this._cachedEffect; }; /** * Gets the cached visibility state (ie. the latest rendered one) * @returns the cached visibility state */ Scene.prototype.getCachedVisibility = function () { return this._cachedVisibility; }; /** * Gets a boolean indicating if the current material / effect / visibility must be bind again * @param material defines the current material * @param effect defines the current effect * @param visibility defines the current visibility state * @returns true if one parameter is not cached */ Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) { if (visibility === void 0) { visibility = 1; } return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility; }; /** * Gets the bounding box renderer associated with the scene * @returns a BoundingBoxRenderer */ Scene.prototype.getBoundingBoxRenderer = function () { if (!this._boundingBoxRenderer) { this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this); } return this._boundingBoxRenderer; }; /** * Gets the outline renderer associated with the scene * @returns a OutlineRenderer */ Scene.prototype.getOutlineRenderer = function () { return this._outlineRenderer; }; /** * Gets the engine associated with the scene * @returns an Engine */ Scene.prototype.getEngine = function () { return this._engine; }; /** * Gets the total number of vertices rendered per frame * @returns the total number of vertices rendered per frame */ Scene.prototype.getTotalVertices = function () { return this._totalVertices.current; }; Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", { /** * Gets the performance counter for total vertices * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation */ get: function () { return this._totalVertices; }, enumerable: true, configurable: true }); /** * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3) * @returns the total number of active indices rendered per frame */ Scene.prototype.getActiveIndices = function () { return this._activeIndices.current; }; Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", { /** * Gets the performance counter for active indices * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation */ get: function () { return this._activeIndices; }, enumerable: true, configurable: true }); /** * Gets the total number of active particles rendered per frame * @returns the total number of active particles rendered per frame */ Scene.prototype.getActiveParticles = function () { return this._activeParticles.current; }; Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", { /** * Gets the performance counter for active particles * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation */ get: function () { return this._activeParticles; }, enumerable: true, configurable: true }); /** * Gets the total number of active bones rendered per frame * @returns the total number of active bones rendered per frame */ Scene.prototype.getActiveBones = function () { return this._activeBones.current; }; Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", { /** * Gets the performance counter for active bones * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation */ get: function () { return this._activeBones; }, enumerable: true, configurable: true }); /** @hidden */ Scene.prototype.getInterFramePerfCounter = function () { BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class"); return 0; }; Object.defineProperty(Scene.prototype, "interFramePerfCounter", { /** @hidden */ get: function () { BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class"); return null; }, enumerable: true, configurable: true }); /** @hidden */ Scene.prototype.getLastFrameDuration = function () { BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class"); return 0; }; Object.defineProperty(Scene.prototype, "lastFramePerfCounter", { /** @hidden */ get: function () { BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class"); return null; }, enumerable: true, configurable: true }); /** @hidden */ Scene.prototype.getEvaluateActiveMeshesDuration = function () { BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class"); return 0; }; Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", { /** @hidden */ get: function () { BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class"); return null; }, enumerable: true, configurable: true }); /** * Gets the array of active meshes * @returns an array of AbstractMesh */ Scene.prototype.getActiveMeshes = function () { return this._activeMeshes; }; /** @hidden */ Scene.prototype.getRenderTargetsDuration = function () { BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class"); return 0; }; /** @hidden */ Scene.prototype.getRenderDuration = function () { BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class"); return 0; }; Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", { /** @hidden */ get: function () { BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class"); return null; }, enumerable: true, configurable: true }); /** @hidden */ Scene.prototype.getParticlesDuration = function () { BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class"); return 0; }; Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", { /** @hidden */ get: function () { BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class"); return null; }, enumerable: true, configurable: true }); /** @hidden */ Scene.prototype.getSpritesDuration = function () { BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class"); return 0; }; Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", { /** @hidden */ get: function () { BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class"); return null; }, enumerable: true, configurable: true }); /** * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.) * @returns a number */ Scene.prototype.getAnimationRatio = function () { return this._animationRatio; }; /** * Gets an unique Id for the current frame * @returns a number */ Scene.prototype.getRenderId = function () { return this._renderId; }; /** Call this function if you want to manually increment the render Id*/ Scene.prototype.incrementRenderId = function () { this._renderId++; }; Scene.prototype._updatePointerPosition = function (evt) { var canvasRect = this._engine.getRenderingCanvasClientRect(); if (!canvasRect) { return; } this._pointerX = evt.clientX - canvasRect.left; this._pointerY = evt.clientY - canvasRect.top; this._unTranslatedPointerX = this._pointerX; this._unTranslatedPointerY = this._pointerY; }; Scene.prototype._createUbo = function () { this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true); this._sceneUbo.addUniform("viewProjection", 16); this._sceneUbo.addUniform("view", 16); }; Scene.prototype._createAlternateUbo = function () { this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true); this._alternateSceneUbo.addUniform("viewProjection", 16); this._alternateSceneUbo.addUniform("view", 16); }; // Pointers handling Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) { var result = this.pickSprite(x, y, predicate, fastCheck, camera); if (result) { result.ray = originalPointerInfo ? originalPointerInfo.ray : null; } return result; }; Scene.prototype._setRayOnPointerInfo = function (pointerInfo) { if (pointerInfo.pickInfo) { if (!pointerInfo.pickInfo.ray) { pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera); } } }; /** * Use this method to simulate a pointer move on a mesh * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay * @param pickResult pickingInfo of the object wished to simulate pointer event on * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch) * @returns the current scene */ Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) { var evt = new PointerEvent("pointermove", pointerEventInit); if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) { return this; } return this._processPointerMove(pickResult, evt); }; Scene.prototype._processPointerMove = function (pickResult, evt) { var canvas = this._engine.getRenderingCanvas(); if (!canvas) { return this; } if (pickResult && pickResult.hit && pickResult.pickedMesh) { this.setPointerOverSprite(null); this.setPointerOverMesh(pickResult.pickedMesh); if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) { if (this._pointerOverMesh.actionManager.hoverCursor) { canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor; } else { canvas.style.cursor = this.hoverCursor; } } else { canvas.style.cursor = this.defaultCursor; } } else { this.setPointerOverMesh(null); // Sprites pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined); if (pickResult && pickResult.hit && pickResult.pickedSprite) { this.setPointerOverSprite(pickResult.pickedSprite); if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) { canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor; } else { canvas.style.cursor = this.hoverCursor; } } else { this.setPointerOverSprite(null); // Restore pointer canvas.style.cursor = this.defaultCursor; } } if (pickResult) { var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE; if (this.onPointerMove) { this.onPointerMove(evt, pickResult, type); } if (this.onPointerObservable.hasObservers()) { var pi = new BABYLON.PointerInfo(type, evt, pickResult); this._setRayOnPointerInfo(pi); this.onPointerObservable.notifyObservers(pi, type); } } return this; }; Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) { var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY); if (pickResult) { pi.ray = pickResult.ray; } this.onPrePointerObservable.notifyObservers(pi, type); if (pi.skipOnPointerObservable) { return true; } else { return false; } }; /** * Use this method to simulate a pointer down on a mesh * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay * @param pickResult pickingInfo of the object wished to simulate pointer event on * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch) * @returns the current scene */ Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) { var evt = new PointerEvent("pointerdown", pointerEventInit); if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) { return this; } return this._processPointerDown(pickResult, evt); }; Scene.prototype._processPointerDown = function (pickResult, evt) { var _this = this; if (pickResult && pickResult.hit && pickResult.pickedMesh) { this._pickedDownMesh = pickResult.pickedMesh; var actionManager = pickResult.pickedMesh.actionManager; if (actionManager) { if (actionManager.hasPickTriggers) { actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt)); switch (evt.button) { case 0: actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt)); break; case 1: actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt)); break; case 2: actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt)); break; } } if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) { window.setTimeout(function () { var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, function (mesh) { return (mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger) && mesh == _this._pickedDownMesh); }, false, _this.cameraToUseForPointers); if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) { if (_this._totalPointersPressed !== 0 && ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) && (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) { _this._startingPointerTime = 0; actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt)); } } }, Scene.LongPressDelay); } } } if (pickResult) { var type = BABYLON.PointerEventTypes.POINTERDOWN; if (this.onPointerDown) { this.onPointerDown(evt, pickResult, type); } if (this.onPointerObservable.hasObservers()) { var pi = new BABYLON.PointerInfo(type, evt, pickResult); this._setRayOnPointerInfo(pi); this.onPointerObservable.notifyObservers(pi, type); } } return this; }; /** * Use this method to simulate a pointer up on a mesh * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay * @param pickResult pickingInfo of the object wished to simulate pointer event on * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch) * @returns the current scene */ Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) { var evt = new PointerEvent("pointerup", pointerEventInit); var clickInfo = new ClickInfo(); clickInfo.singleClick = true; clickInfo.ignore = true; if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) { return this; } return this._processPointerUp(pickResult, evt, clickInfo); }; Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) { if (pickResult && pickResult && pickResult.pickedMesh) { this._pickedUpMesh = pickResult.pickedMesh; if (this._pickedDownMesh === this._pickedUpMesh) { if (this.onPointerPick) { this.onPointerPick(evt, pickResult); } if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) { var type_1 = BABYLON.PointerEventTypes.POINTERPICK; var pi = new BABYLON.PointerInfo(type_1, evt, pickResult); this._setRayOnPointerInfo(pi); this.onPointerObservable.notifyObservers(pi, type_1); } } if (pickResult.pickedMesh.actionManager) { if (clickInfo.ignore) { pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt)); } if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) { pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt)); } if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) { pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt)); } } } if (this._pickedDownMesh && this._pickedDownMesh.actionManager && this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) && this._pickedDownMesh !== this._pickedUpMesh) { this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt)); } var type = BABYLON.PointerEventTypes.POINTERUP; if (this.onPointerObservable.hasObservers()) { if (!clickInfo.ignore) { if (!clickInfo.hasSwiped) { if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) { var type_2 = BABYLON.PointerEventTypes.POINTERTAP; var pi = new BABYLON.PointerInfo(type_2, evt, pickResult); this._setRayOnPointerInfo(pi); this.onPointerObservable.notifyObservers(pi, type_2); } if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) { var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP; var pi = new BABYLON.PointerInfo(type_3, evt, pickResult); this._setRayOnPointerInfo(pi); this.onPointerObservable.notifyObservers(pi, type_3); } } } else { var pi = new BABYLON.PointerInfo(type, evt, pickResult); this._setRayOnPointerInfo(pi); this.onPointerObservable.notifyObservers(pi, type); } } if (this.onPointerUp) { this.onPointerUp(evt, pickResult, type); } return this; }; /** * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down) * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default) * @returns true if the pointer was captured */ Scene.prototype.isPointerCaptured = function (pointerId) { if (pointerId === void 0) { pointerId = 0; } return this._pointerCaptures[pointerId]; }; /** * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp * @param attachUp defines if you want to attach events to pointerup * @param attachDown defines if you want to attach events to pointerdown * @param attachMove defines if you want to attach events to pointermove */ Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) { var _this = this; if (attachUp === void 0) { attachUp = true; } if (attachDown === void 0) { attachDown = true; } if (attachMove === void 0) { attachMove = true; } this._initActionManager = function (act, clickInfo) { if (!_this._meshPickProceed) { var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers); _this._currentPickResult = pickResult; if (pickResult) { act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null; } _this._meshPickProceed = true; } return act; }; this._delayedSimpleClick = function (btn, clickInfo, cb) { // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) || btn !== _this._previousButtonPressed) { _this._doubleClickOccured = false; clickInfo.singleClick = true; clickInfo.ignore = false; cb(clickInfo, _this._currentPickResult); } }; this._initClickEvent = function (obs1, obs2, evt, cb) { var clickInfo = new ClickInfo(); _this._currentPickResult = null; var act = null; var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP); if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) { act = _this._initActionManager(act, clickInfo); if (act) checkPicking = act.hasPickTriggers; } if (checkPicking) { var btn = evt.button; clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold || Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold; if (!clickInfo.hasSwiped) { var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode; if (!checkSingleClickImmediately) { checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) && !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP); if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) { act = _this._initActionManager(act, clickInfo); if (act) checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger); } } if (checkSingleClickImmediately) { // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay || btn !== _this._previousButtonPressed) { clickInfo.singleClick = true; cb(clickInfo, _this._currentPickResult); } } // at least one double click is required to be check and exclusive double click is enabled else { // wait that no double click has been raised during the double click delay _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout; _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay); } var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP); if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) { act = _this._initActionManager(act, clickInfo); if (act) checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger); } if (checkDoubleClick) { // two successive keys pressed are equal, double click delay is not over and double click has not just occurred if (btn === _this._previousButtonPressed && Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay && !_this._doubleClickOccured) { // pointer has not moved for 2 clicks, it's a double click if (!clickInfo.hasSwiped && Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold && Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) { _this._previousStartingPointerTime = 0; _this._doubleClickOccured = true; clickInfo.doubleClick = true; clickInfo.ignore = false; if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) { clearTimeout(_this._previousDelayedSimpleClickTimeout); } _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout; cb(clickInfo, _this._currentPickResult); } // if the two successive clicks are too far, it's just two simple clicks else { _this._doubleClickOccured = false; _this._previousStartingPointerTime = _this._startingPointerTime; _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x; _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y; _this._previousButtonPressed = btn; if (Scene.ExclusiveDoubleClickMode) { if (_this._previousDelayedSimpleClickTimeout) { clearTimeout(_this._previousDelayedSimpleClickTimeout); } _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout; cb(clickInfo, _this._previousPickResult); } else { cb(clickInfo, _this._currentPickResult); } } } // just the first click of the double has been raised else { _this._doubleClickOccured = false; _this._previousStartingPointerTime = _this._startingPointerTime; _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x; _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y; _this._previousButtonPressed = btn; } } } } clickInfo.ignore = true; cb(clickInfo, _this._currentPickResult); }; this._spritePredicate = function (sprite) { return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers; }; this._onPointerMove = function (evt) { _this._updatePointerPosition(evt); // PreObservable support if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) { return; } if (!_this.cameraToUseForPointers && !_this.activeCamera) { return; } if (!_this.pointerMovePredicate) { _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); }; } // Meshes var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers); _this._processPointerMove(pickResult, evt); }; this._onPointerDown = function (evt) { _this._totalPointersPressed++; _this._pickedDownMesh = null; _this._meshPickProceed = false; _this._updatePointerPosition(evt); if (_this.preventDefaultOnPointerDown && canvas) { evt.preventDefault(); canvas.focus(); } // PreObservable support if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) { return; } if (!_this.cameraToUseForPointers && !_this.activeCamera) { return; } _this._pointerCaptures[evt.pointerId] = true; _this._startingPointerPosition.x = _this._pointerX; _this._startingPointerPosition.y = _this._pointerY; _this._startingPointerTime = Date.now(); if (!_this.pointerDownPredicate) { _this.pointerDownPredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled(); }; } // Meshes _this._pickedDownMesh = null; var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers); _this._processPointerDown(pickResult, evt); // Sprites _this._pickedDownSprite = null; if (_this.spriteManagers.length > 0) { pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined); if (pickResult && pickResult.hit && pickResult.pickedSprite) { if (pickResult.pickedSprite.actionManager) { _this._pickedDownSprite = pickResult.pickedSprite; switch (evt.button) { case 0: pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt)); break; case 1: pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt)); break; case 2: pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt)); break; } if (pickResult.pickedSprite.actionManager) { pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt)); } } } } }; this._onPointerUp = function (evt) { if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF return; // So we need to test it the pointer down was pressed before. } _this._totalPointersPressed--; _this._pickedUpMesh = null; _this._meshPickProceed = false; _this._updatePointerPosition(evt); _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) { // PreObservable support if (_this.onPrePointerObservable.hasObservers()) { if (!clickInfo.ignore) { if (!clickInfo.hasSwiped) { if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) { if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) { return; } } if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) { if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) { return; } } } } else { if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) { return; } } } if (!_this.cameraToUseForPointers && !_this.activeCamera) { return; } _this._pointerCaptures[evt.pointerId] = false; if (!_this.pointerUpPredicate) { _this.pointerUpPredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled(); }; } // Meshes if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) { _this._initActionManager(null, clickInfo); } if (!pickResult) { pickResult = _this._currentPickResult; } _this._processPointerUp(pickResult, evt, clickInfo); // Sprites if (!clickInfo.ignore) { if (_this.spriteManagers.length > 0) { var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined); if (spritePickResult) { if (spritePickResult.hit && spritePickResult.pickedSprite) { if (spritePickResult.pickedSprite.actionManager) { spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt)); if (spritePickResult.pickedSprite.actionManager) { if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) { spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt)); } } } } if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) { _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt)); } } } } _this._previousPickResult = _this._currentPickResult; }); }; this._onKeyDown = function (evt) { var type = BABYLON.KeyboardEventTypes.KEYDOWN; if (_this.onPreKeyboardObservable.hasObservers()) { var pi = new BABYLON.KeyboardInfoPre(type, evt); _this.onPreKeyboardObservable.notifyObservers(pi, type); if (pi.skipOnPointerObservable) { return; } } if (_this.onKeyboardObservable.hasObservers()) { var pi = new BABYLON.KeyboardInfo(type, evt); _this.onKeyboardObservable.notifyObservers(pi, type); } if (_this.actionManager) { _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt)); } }; this._onKeyUp = function (evt) { var type = BABYLON.KeyboardEventTypes.KEYUP; if (_this.onPreKeyboardObservable.hasObservers()) { var pi = new BABYLON.KeyboardInfoPre(type, evt); _this.onPreKeyboardObservable.notifyObservers(pi, type); if (pi.skipOnPointerObservable) { return; } } if (_this.onKeyboardObservable.hasObservers()) { var pi = new BABYLON.KeyboardInfo(type, evt); _this.onKeyboardObservable.notifyObservers(pi, type); } if (_this.actionManager) { _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt)); } }; var engine = this.getEngine(); this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () { if (!canvas) { return; } canvas.addEventListener("keydown", _this._onKeyDown, false); canvas.addEventListener("keyup", _this._onKeyUp, false); }); this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () { if (!canvas) { return; } canvas.removeEventListener("keydown", _this._onKeyDown); canvas.removeEventListener("keyup", _this._onKeyUp); }); var eventPrefix = BABYLON.Tools.GetPointerPrefix(); var canvas = this._engine.getRenderingCanvas(); if (!canvas) { return; } if (attachMove) { canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false); // Wheel canvas.addEventListener('mousewheel', this._onPointerMove, false); canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false); } if (attachDown) { canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false); } if (attachUp) { window.addEventListener(eventPrefix + "up", this._onPointerUp, false); } canvas.tabIndex = 1; }; /** Detaches all event handlers*/ Scene.prototype.detachControl = function () { var engine = this.getEngine(); var eventPrefix = BABYLON.Tools.GetPointerPrefix(); var canvas = engine.getRenderingCanvas(); if (!canvas) { return; } canvas.removeEventListener(eventPrefix + "move", this._onPointerMove); canvas.removeEventListener(eventPrefix + "down", this._onPointerDown); window.removeEventListener(eventPrefix + "up", this._onPointerUp); if (this._onCanvasBlurObserver) { engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver); } if (this._onCanvasFocusObserver) { engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver); } // Wheel canvas.removeEventListener('mousewheel', this._onPointerMove); canvas.removeEventListener('DOMMouseScroll', this._onPointerMove); // Keyboard canvas.removeEventListener("keydown", this._onKeyDown); canvas.removeEventListener("keyup", this._onKeyUp); // Observables this.onKeyboardObservable.clear(); this.onPreKeyboardObservable.clear(); this.onPointerObservable.clear(); this.onPrePointerObservable.clear(); }; /** * This function will check if the scene can be rendered (textures are loaded, shaders are compiled) * Delay loaded resources are not taking in account * @return true if all required resources are ready */ Scene.prototype.isReady = function () { if (this._isDisposed) { return false; } if (this._pendingData.length > 0) { return false; } var index; var engine = this.getEngine(); // Geometries for (index = 0; index < this._geometries.length; index++) { var geometry = this._geometries[index]; if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) { return false; } } // Meshes for (index = 0; index < this.meshes.length; index++) { var mesh = this.meshes[index]; if (!mesh.isEnabled()) { continue; } if (!mesh.subMeshes || mesh.subMeshes.length === 0) { continue; } if (!mesh.isReady(true)) { return false; } // Effect layers var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0; for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) { var layer = _a[_i]; if (!layer.hasMesh(mesh)) { continue; } for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) { var subMesh = _c[_b]; if (!layer.isReady(subMesh, hardwareInstancedRendering)) { return false; } } } } // Post-processes if (this.activeCameras && this.activeCameras.length > 0) { for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) { var camera = _e[_d]; if (!camera.isReady(true)) { return false; } } } else if (this.activeCamera) { if (!this.activeCamera.isReady(true)) { return false; } } // Particles for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) { var particleSystem = _g[_f]; if (!particleSystem.isReady()) { return false; } } return true; }; /** Resets all cached information relative to material (including effect and visibility) */ Scene.prototype.resetCachedMaterial = function () { this._cachedMaterial = null; this._cachedEffect = null; this._cachedVisibility = null; }; /** * Registers a function to be called before every frame render * @param func defines the function to register */ Scene.prototype.registerBeforeRender = function (func) { this.onBeforeRenderObservable.add(func); }; /** * Unregisters a function called before every frame render * @param func defines the function to unregister */ Scene.prototype.unregisterBeforeRender = function (func) { this.onBeforeRenderObservable.removeCallback(func); }; /** * Registers a function to be called after every frame render * @param func defines the function to register */ Scene.prototype.registerAfterRender = function (func) { this.onAfterRenderObservable.add(func); }; /** * Unregisters a function called after every frame render * @param func defines the function to unregister */ Scene.prototype.unregisterAfterRender = function (func) { this.onAfterRenderObservable.removeCallback(func); }; Scene.prototype._executeOnceBeforeRender = function (func) { var _this = this; var execFunc = function () { func(); setTimeout(function () { _this.unregisterBeforeRender(execFunc); }); }; this.registerBeforeRender(execFunc); }; /** * The provided function will run before render once and will be disposed afterwards. * A timeout delay can be provided so that the function will be executed in N ms. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed. * @param func The function to be executed. * @param timeout optional delay in ms */ Scene.prototype.executeOnceBeforeRender = function (func, timeout) { var _this = this; if (timeout !== undefined) { setTimeout(function () { _this._executeOnceBeforeRender(func); }, timeout); } else { this._executeOnceBeforeRender(func); } }; /** @hidden */ Scene.prototype._addPendingData = function (data) { this._pendingData.push(data); }; /** @hidden */ Scene.prototype._removePendingData = function (data) { var wasLoading = this.isLoading; var index = this._pendingData.indexOf(data); if (index !== -1) { this._pendingData.splice(index, 1); } if (wasLoading && !this.isLoading) { this.onDataLoadedObservable.notifyObservers(this); } }; /** * Returns the number of items waiting to be loaded * @returns the number of items waiting to be loaded */ Scene.prototype.getWaitingItemsCount = function () { return this._pendingData.length; }; Object.defineProperty(Scene.prototype, "isLoading", { /** * Returns a boolean indicating if the scene is still loading data */ get: function () { return this._pendingData.length > 0; }, enumerable: true, configurable: true }); /** * Registers a function to be executed when the scene is ready * @param {Function} func - the function to be executed */ Scene.prototype.executeWhenReady = function (func) { var _this = this; this.onReadyObservable.add(func); if (this._executeWhenReadyTimeoutId !== -1) { return; } this._executeWhenReadyTimeoutId = setTimeout(function () { _this._checkIsReady(); }, 150); }; /** * Returns a promise that resolves when the scene is ready * @returns A promise that resolves when the scene is ready */ Scene.prototype.whenReadyAsync = function () { var _this = this; return new Promise(function (resolve) { _this.executeWhenReady(function () { resolve(); }); }); }; /** @hidden */ Scene.prototype._checkIsReady = function () { var _this = this; if (this.isReady()) { this.onReadyObservable.notifyObservers(this); this.onReadyObservable.clear(); this._executeWhenReadyTimeoutId = -1; return; } this._executeWhenReadyTimeoutId = setTimeout(function () { _this._checkIsReady(); }, 150); }; // Animations /** * Will start the animation sequence of a given target * @param target defines the target * @param from defines from which frame should animation start * @param to defines until which frame should animation run. * @param weight defines the weight to apply to the animation (1.0 by default) * @param loop defines if the animation loops * @param speedRatio defines the speed in which to run the animation (1.0 by default) * @param onAnimationEnd defines the function to be executed when the animation ends * @param animatable defines an animatable object. If not provided a new one will be created from the given params * @returns the animatable object created for this animation */ Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) { 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); returnedAnimatable.weight = weight; return returnedAnimatable; }; /** * Will start the animation sequence of a given target * @param target defines the target * @param from defines from which frame should animation start * @param to defines until which frame should animation run. * @param loop defines if the animation loops * @param speedRatio defines the speed in which to run the animation (1.0 by default) * @param onAnimationEnd defines the function to be executed when the animation ends * @param animatable defines an animatable object. If not provided a new one will be created from the given params * @param stopCurrent defines if the current animations must be stopped first (true by default) * @returns the animatable object created for this animation */ Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) { 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); } if (!animatable) { animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd); } // Local animations if (target.animations) { 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); } } animatable.reset(); return animatable; }; /** * Begin a new animation on a given node * @param target defines the target where the animation will take place * @param animations defines the list of animations to start * @param from defines the initial value * @param to defines the final value * @param loop defines if you want animation to loop (off by default) * @param speedRatio defines the speed ratio to apply to all animations * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node) * @returns the list of created animatables */ Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) { if (speedRatio === undefined) { speedRatio = 1.0; } var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations); return animatable; }; /** * Begin a new animation on a given node and its hierarchy * @param target 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 animations defines the list of animations to start * @param from defines the initial value * @param to defines the final value * @param loop defines if you want animation to loop (off by default) * @param speedRatio defines the speed ratio to apply to all animations * @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 */ Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) { var children = target.getDescendants(directDescendantsOnly); var result = []; result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd)); for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { var child = children_1[_i]; result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd)); } return result; }; /** * Gets the animatable associated with a specific target * @param target defines the target of the animatable * @returns the required animatable if found */ 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; }; /** * Gets all animatables associated with a given target * @param target defines the target to look animatables for * @returns an array of Animatables */ 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; }; Object.defineProperty(Scene.prototype, "animatables", { /** * Gets all animatable attached to the scene */ get: function () { return this._activeAnimatables; }, enumerable: true, configurable: true }); /** * 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 empty) */ Scene.prototype.stopAnimation = function (target, animationName) { 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); } }; /** * Stops and removes all animations that have been applied to the scene */ 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.prototype._animate = function () { if (!this.animationsEnabled || this._activeAnimatables.length === 0) { return; } // Getting time var now = BABYLON.Tools.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(); }; /** @hidden */ 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.prototype._processLateAnimationBindingsForMatrices = function (holder) { var normalizer = 1.0; var finalPosition = BABYLON.Tmp.Vector3[0]; var finalScaling = BABYLON.Tmp.Vector3[1]; var finalQuaternion = BABYLON.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 = BABYLON.Tmp.Vector3[2]; var currentScaling = BABYLON.Tmp.Vector3[3]; var currentQuaternion = BABYLON.Tmp.Quaternion[1]; runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition); currentScaling.scaleAndAddToRef(scale, finalScaling); currentQuaternion.scaleAndAddToRef(scale, finalQuaternion); currentPosition.scaleAndAddToRef(scale, finalPosition); } BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue); return originalAnimation._workValue; }; Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) { var originalAnimation = holder.animations[0]; var originalValue = holder.originalValue; if (holder.animations.length === 1) { return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight)); } 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 return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight); } 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) { cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1])); cumulativeAmount = weights[index] + weights[index + 1]; index += 2; continue; } cumulativeAmount += weights[index]; BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion); index++; } return cumulativeQuaternion; }; 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 = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix var finalValue = void 0; if (matrixDecomposeMode) { finalValue = this._processLateAnimationBindingsForMatrices(holder); } else { var quaternionMode = originalValue.w !== undefined; if (quaternionMode) { finalValue = this._processLateAnimationBindingsForQuaternions(holder); } 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(); }; // Matrix /** @hidden */ Scene.prototype._switchToAlternateCameraConfiguration = function (active) { this._useAlternateCameraConfiguration = active; }; /** * Gets the current view matrix * @returns a Matrix */ Scene.prototype.getViewMatrix = function () { return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix; }; /** * Gets the current projection matrix * @returns a Matrix */ Scene.prototype.getProjectionMatrix = function () { return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix; }; /** * Gets the current transform matrix * @returns a Matrix made of View * Projection */ Scene.prototype.getTransformMatrix = function () { return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix; }; /** * Sets the current transform matrix * @param view defines the View matrix to use * @param projection defines the Projection matrix to use */ Scene.prototype.setTransformMatrix = function (view, projection) { if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) { return; } this._viewUpdateFlag = view.updateFlag; this._projectionUpdateFlag = projection.updateFlag; this._viewMatrix = view; this._projectionMatrix = projection; this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix); // Update frustum if (!this._frustumPlanes) { this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix); } else { BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes); } if (this.activeCamera && this.activeCamera._alternateCamera) { var otherCamera = this.activeCamera._alternateCamera; otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]); BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane } if (this._sceneUbo.useUbo) { this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix); this._sceneUbo.updateMatrix("view", this._viewMatrix); this._sceneUbo.update(); } }; /** @hidden */ Scene.prototype._setAlternateTransformMatrix = function (view, projection) { if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) { return; } this._alternateViewUpdateFlag = view.updateFlag; this._alternateProjectionUpdateFlag = projection.updateFlag; this._alternateViewMatrix = view; this._alternateProjectionMatrix = projection; if (!this._alternateTransformMatrix) { this._alternateTransformMatrix = BABYLON.Matrix.Zero(); } this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix); if (!this._alternateSceneUbo) { this._createAlternateUbo(); } if (this._alternateSceneUbo.useUbo) { this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix); this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix); this._alternateSceneUbo.update(); } }; /** * Gets the uniform buffer used to store scene data * @returns a UniformBuffer */ Scene.prototype.getSceneUniformBuffer = function () { return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo; }; /** * Gets an unique (relatively to the current scene) Id * @returns an unique number for the scene */ Scene.prototype.getUniqueId = function () { var result = Scene._uniqueIdCounter; Scene._uniqueIdCounter++; return result; }; /** * Add a mesh to the list of scene's meshes * @param newMesh defines the mesh to add * @param recursive if all child meshes should also be added to the scene */ Scene.prototype.addMesh = function (newMesh, recursive) { var _this = this; if (recursive === void 0) { recursive = false; } this.meshes.push(newMesh); //notify the collision coordinator if (this.collisionCoordinator) { this.collisionCoordinator.onMeshAdded(newMesh); } newMesh._resyncLightSources(); this.onNewMeshAddedObservable.notifyObservers(newMesh); if (recursive) { newMesh.getChildMeshes().forEach(function (m) { _this.addMesh(m); }); } }; /** * Remove a mesh for the list of scene's meshes * @param toRemove defines the mesh to remove * @param recursive if all child meshes should also be removed from the scene * @returns the index where the mesh was in the mesh list */ Scene.prototype.removeMesh = function (toRemove, recursive) { var _this = this; if (recursive === void 0) { recursive = false; } var index = this.meshes.indexOf(toRemove); if (index !== -1) { // Remove from the scene if mesh found this.meshes.splice(index, 1); } this.onMeshRemovedObservable.notifyObservers(toRemove); if (recursive) { toRemove.getChildMeshes().forEach(function (m) { _this.removeMesh(m); }); } return index; }; /** * Add a transform node to the list of scene's transform nodes * @param newTransformNode defines the transform node to add */ Scene.prototype.addTransformNode = function (newTransformNode) { this.transformNodes.push(newTransformNode); this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode); }; /** * Remove a transform node for the list of scene's transform nodes * @param toRemove defines the transform node to remove * @returns the index where the transform node was in the transform node list */ Scene.prototype.removeTransformNode = function (toRemove) { var index = this.transformNodes.indexOf(toRemove); if (index !== -1) { // Remove from the scene if found this.transformNodes.splice(index, 1); } this.onTransformNodeRemovedObservable.notifyObservers(toRemove); return index; }; /** * Remove a skeleton for the list of scene's skeletons * @param toRemove defines the skeleton to remove * @returns the index where the skeleton was in the skeleton list */ Scene.prototype.removeSkeleton = function (toRemove) { var index = this.skeletons.indexOf(toRemove); if (index !== -1) { // Remove from the scene if found this.skeletons.splice(index, 1); } return index; }; /** * Remove a morph target for the list of scene's morph targets * @param toRemove defines the morph target to remove * @returns the index where the morph target was in the morph target list */ Scene.prototype.removeMorphTargetManager = function (toRemove) { var index = this.morphTargetManagers.indexOf(toRemove); if (index !== -1) { // Remove from the scene if found this.morphTargetManagers.splice(index, 1); } return index; }; /** * Remove a light for the list of scene's lights * @param toRemove defines the light to remove * @returns the index where the light was in the light list */ Scene.prototype.removeLight = function (toRemove) { var index = this.lights.indexOf(toRemove); if (index !== -1) { // Remove from meshes for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) { var mesh = _a[_i]; mesh._removeLightSource(toRemove); } // Remove from the scene if mesh found this.lights.splice(index, 1); this.sortLightsByPriority(); } this.onLightRemovedObservable.notifyObservers(toRemove); return index; }; /** * Remove a camera for the list of scene's cameras * @param toRemove defines the camera to remove * @returns the index where the camera was in the camera list */ Scene.prototype.removeCamera = function (toRemove) { var index = this.cameras.indexOf(toRemove); if (index !== -1) { // Remove from the scene if mesh found this.cameras.splice(index, 1); } // Remove from activeCameras var index2 = this.activeCameras.indexOf(toRemove); if (index2 !== -1) { // Remove from the scene if mesh found this.activeCameras.splice(index2, 1); } // Reset the activeCamera if (this.activeCamera === toRemove) { if (this.cameras.length > 0) { this.activeCamera = this.cameras[0]; } else { this.activeCamera = null; } } this.onCameraRemovedObservable.notifyObservers(toRemove); return index; }; /** * Remove a particle system for the list of scene's particle systems * @param toRemove defines the particle system to remove * @returns the index where the particle system was in the particle system list */ Scene.prototype.removeParticleSystem = function (toRemove) { var index = this.particleSystems.indexOf(toRemove); if (index !== -1) { this.particleSystems.splice(index, 1); } return index; }; /** * Remove a animation for the list of scene's animations * @param toRemove defines the animation to remove * @returns the index where the animation was in the animation list */ Scene.prototype.removeAnimation = function (toRemove) { var index = this.animations.indexOf(toRemove); if (index !== -1) { this.animations.splice(index, 1); } return index; }; /** * Removes the given animation group from this scene. * @param toRemove The animation group to remove * @returns The index of the removed animation group */ Scene.prototype.removeAnimationGroup = function (toRemove) { var index = this.animationGroups.indexOf(toRemove); if (index !== -1) { this.animationGroups.splice(index, 1); } return index; }; /** * Removes the given multi-material from this scene. * @param toRemove The multi-material to remove * @returns The index of the removed multi-material */ Scene.prototype.removeMultiMaterial = function (toRemove) { var index = this.multiMaterials.indexOf(toRemove); if (index !== -1) { this.multiMaterials.splice(index, 1); } return index; }; /** * Removes the given material from this scene. * @param toRemove The material to remove * @returns The index of the removed material */ Scene.prototype.removeMaterial = function (toRemove) { var index = this.materials.indexOf(toRemove); if (index !== -1) { this.materials.splice(index, 1); } return index; }; /** * Removes the given lens flare system from this scene. * @param toRemove The lens flare system to remove * @returns The index of the removed lens flare system */ Scene.prototype.removeLensFlareSystem = function (toRemove) { var index = this.lensFlareSystems.indexOf(toRemove); if (index !== -1) { this.lensFlareSystems.splice(index, 1); } return index; }; /** * Removes the given action manager from this scene. * @param toRemove The action manager to remove * @returns The index of the removed action manager */ Scene.prototype.removeActionManager = function (toRemove) { var index = this._actionManagers.indexOf(toRemove); if (index !== -1) { this._actionManagers.splice(index, 1); } return index; }; /** * Removes the given effect layer from this scene. * @param toRemove defines the effect layer to remove * @returns the index of the removed effect layer */ Scene.prototype.removeEffectLayer = function (toRemove) { var index = this.effectLayers.indexOf(toRemove); if (index !== -1) { this.effectLayers.splice(index, 1); } return index; }; /** * Removes the given texture from this scene. * @param toRemove The texture to remove * @returns The index of the removed texture */ Scene.prototype.removeTexture = function (toRemove) { var index = this.textures.indexOf(toRemove); if (index !== -1) { this.textures.splice(index, 1); } return index; }; /** * Adds the given light to this scene * @param newLight The light to add */ Scene.prototype.addLight = function (newLight) { this.lights.push(newLight); this.sortLightsByPriority(); // Add light to all meshes (To support if the light is removed and then readded) for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) { var mesh = _a[_i]; if (mesh._lightSources.indexOf(newLight) === -1) { mesh._lightSources.push(newLight); mesh._resyncLightSources(); } } this.onNewLightAddedObservable.notifyObservers(newLight); }; /** * Sorts the list list based on light priorities */ Scene.prototype.sortLightsByPriority = function () { if (this.requireLightSorting) { this.lights.sort(BABYLON.Light.CompareLightsPriority); } }; /** * Adds the given camera to this scene * @param newCamera The camera to add */ Scene.prototype.addCamera = function (newCamera) { this.cameras.push(newCamera); this.onNewCameraAddedObservable.notifyObservers(newCamera); }; /** * Adds the given skeleton to this scene * @param newSkeleton The skeleton to add */ Scene.prototype.addSkeleton = function (newSkeleton) { this.skeletons.push(newSkeleton); }; /** * Adds the given particle system to this scene * @param newParticleSystem The particle system to add */ Scene.prototype.addParticleSystem = function (newParticleSystem) { this.particleSystems.push(newParticleSystem); }; /** * Adds the given animation to this scene * @param newAnimation The animation to add */ Scene.prototype.addAnimation = function (newAnimation) { this.animations.push(newAnimation); }; /** * Adds the given animation group to this scene. * @param newAnimationGroup The animation group to add */ Scene.prototype.addAnimationGroup = function (newAnimationGroup) { this.animationGroups.push(newAnimationGroup); }; /** * Adds the given multi-material to this scene * @param newMultiMaterial The multi-material to add */ Scene.prototype.addMultiMaterial = function (newMultiMaterial) { this.multiMaterials.push(newMultiMaterial); }; /** * Adds the given material to this scene * @param newMaterial The material to add */ Scene.prototype.addMaterial = function (newMaterial) { this.materials.push(newMaterial); }; /** * Adds the given morph target to this scene * @param newMorphTargetManager The morph target to add */ Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) { this.morphTargetManagers.push(newMorphTargetManager); }; /** * Adds the given geometry to this scene * @param newGeometry The geometry to add */ Scene.prototype.addGeometry = function (newGeometry) { this._geometries.push(newGeometry); }; /** * Adds the given lens flare system to this scene * @param newLensFlareSystem The lens flare system to add */ Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) { this.lensFlareSystems.push(newLensFlareSystem); }; /** * Adds the given effect layer to this scene * @param newEffectLayer defines the effect layer to add */ Scene.prototype.addEffectLayer = function (newEffectLayer) { this.effectLayers.push(newEffectLayer); }; /** * Adds the given action manager to this scene * @param newActionManager The action manager to add */ Scene.prototype.addActionManager = function (newActionManager) { this._actionManagers.push(newActionManager); }; /** * Adds the given texture to this scene. * @param newTexture The texture to add */ Scene.prototype.addTexture = function (newTexture) { this.textures.push(newTexture); }; /** * Switch active camera * @param newCamera defines the new active camera * @param attachControl defines if attachControl must be called for the new active camera (default: true) */ Scene.prototype.switchActiveCamera = function (newCamera, attachControl) { if (attachControl === void 0) { attachControl = true; } var canvas = this._engine.getRenderingCanvas(); if (!canvas) { return; } if (this.activeCamera) { this.activeCamera.detachControl(canvas); } this.activeCamera = newCamera; if (attachControl) { newCamera.attachControl(canvas); } }; /** * sets the active camera of the scene using its ID * @param id defines the camera's ID * @return the new active camera or null if none found. */ Scene.prototype.setActiveCameraByID = function (id) { var camera = this.getCameraByID(id); if (camera) { this.activeCamera = camera; return camera; } return null; }; /** * sets the active camera of the scene using its name * @param name defines the camera's name * @returns the new active camera or null if none found. */ Scene.prototype.setActiveCameraByName = function (name) { var camera = this.getCameraByName(name); if (camera) { this.activeCamera = camera; return camera; } return null; }; /** * get an animation group using its name * @param name defines the material's name * @return the animation group or null if none found. */ Scene.prototype.getAnimationGroupByName = function (name) { for (var index = 0; index < this.animationGroups.length; index++) { if (this.animationGroups[index].name === name) { return this.animationGroups[index]; } } return null; }; /** * get a material using its id * @param id defines the material's ID * @return the material or null if none found. */ Scene.prototype.getMaterialByID = function (id) { for (var index = 0; index < this.materials.length; index++) { if (this.materials[index].id === id) { return this.materials[index]; } } return null; }; /** * Gets a material using its name * @param name defines the material's name * @return the material or null if none found. */ Scene.prototype.getMaterialByName = function (name) { for (var index = 0; index < this.materials.length; index++) { if (this.materials[index].name === name) { return this.materials[index]; } } return null; }; /** * Gets a lens flare system using its name * @param name defines the name to look for * @returns the lens flare system or null if not found */ Scene.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; }; /** * Gets a lens flare system using its id * @param id defines the id to look for * @returns the lens flare system or null if not found */ Scene.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; }; /** * Gets a camera using its id * @param id defines the id to look for * @returns the camera or null if not found */ Scene.prototype.getCameraByID = function (id) { for (var index = 0; index < this.cameras.length; index++) { if (this.cameras[index].id === id) { return this.cameras[index]; } } return null; }; /** * Gets a camera using its unique id * @param uniqueId defines the unique id to look for * @returns the camera or null if not found */ Scene.prototype.getCameraByUniqueID = function (uniqueId) { for (var index = 0; index < this.cameras.length; index++) { if (this.cameras[index].uniqueId === uniqueId) { return this.cameras[index]; } } return null; }; /** * Gets a camera using its name * @param name defines the camera's name * @return the camera or null if none found. */ Scene.prototype.getCameraByName = function (name) { for (var index = 0; index < this.cameras.length; index++) { if (this.cameras[index].name === name) { return this.cameras[index]; } } return null; }; /** * Gets a bone using its id * @param id defines the bone's id * @return the bone or null if not found */ Scene.prototype.getBoneByID = function (id) { for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) { var skeleton = this.skeletons[skeletonIndex]; for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) { if (skeleton.bones[boneIndex].id === id) { return skeleton.bones[boneIndex]; } } } return null; }; /** * Gets a bone using its id * @param name defines the bone's name * @return the bone or null if not found */ Scene.prototype.getBoneByName = function (name) { for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) { var skeleton = this.skeletons[skeletonIndex]; for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) { if (skeleton.bones[boneIndex].name === name) { return skeleton.bones[boneIndex]; } } } return null; }; /** * Gets a light node using its name * @param name defines the the light's name * @return the light or null if none found. */ Scene.prototype.getLightByName = function (name) { for (var index = 0; index < this.lights.length; index++) { if (this.lights[index].name === name) { return this.lights[index]; } } return null; }; /** * Gets a light node using its id * @param id defines the light's id * @return the light or null if none found. */ Scene.prototype.getLightByID = function (id) { for (var index = 0; index < this.lights.length; index++) { if (this.lights[index].id === id) { return this.lights[index]; } } return null; }; /** * Gets a light node using its scene-generated unique ID * @param uniqueId defines the light's unique id * @return the light or null if none found. */ Scene.prototype.getLightByUniqueID = function (uniqueId) { for (var index = 0; index < this.lights.length; index++) { if (this.lights[index].uniqueId === uniqueId) { return this.lights[index]; } } return null; }; /** * Gets a particle system by id * @param id defines the particle system id * @return the corresponding system or null if none found */ Scene.prototype.getParticleSystemByID = function (id) { for (var index = 0; index < this.particleSystems.length; index++) { if (this.particleSystems[index].id === id) { return this.particleSystems[index]; } } return null; }; /** * Gets a geometry using its ID * @param id defines the geometry's id * @return the geometry or null if none found. */ Scene.prototype.getGeometryByID = function (id) { for (var index = 0; index < this._geometries.length; index++) { if (this._geometries[index].id === id) { return this._geometries[index]; } } return null; }; /** * Add a new geometry to this scene * @param geometry defines the geometry to be added to the scene. * @param force defines if the geometry must be pushed even if a geometry with this id already exists * @return a boolean defining if the geometry was added or not */ Scene.prototype.pushGeometry = function (geometry, force) { if (!force && this.getGeometryByID(geometry.id)) { return false; } this._geometries.push(geometry); //notify the collision coordinator if (this.collisionCoordinator) { this.collisionCoordinator.onGeometryAdded(geometry); } this.onNewGeometryAddedObservable.notifyObservers(geometry); return true; }; /** * Removes an existing geometry * @param geometry defines the geometry to be removed from the scene * @return a boolean defining if the geometry was removed or not */ Scene.prototype.removeGeometry = function (geometry) { var index = this._geometries.indexOf(geometry); if (index > -1) { this._geometries.splice(index, 1); //notify the collision coordinator if (this.collisionCoordinator) { this.collisionCoordinator.onGeometryDeleted(geometry); } this.onGeometryRemovedObservable.notifyObservers(geometry); return true; } return false; }; /** * Gets the list of geometries attached to the scene * @returns an array of Geometry */ Scene.prototype.getGeometries = function () { return this._geometries; }; /** * Gets the first added mesh found of a given ID * @param id defines the id to search for * @return the mesh found or null if not found at all */ Scene.prototype.getMeshByID = function (id) { for (var index = 0; index < this.meshes.length; index++) { if (this.meshes[index].id === id) { return this.meshes[index]; } } return null; }; /** * Gets a list of meshes using their id * @param id defines the id to search for * @returns a list of meshes */ Scene.prototype.getMeshesByID = function (id) { return this.meshes.filter(function (m) { return m.id === id; }); }; /** * Gets the first added transform node found of a given ID * @param id defines the id to search for * @return the found transform node or null if not found at all. */ Scene.prototype.getTransformNodeByID = function (id) { for (var index = 0; index < this.transformNodes.length; index++) { if (this.transformNodes[index].id === id) { return this.transformNodes[index]; } } return null; }; /** * Gets a list of transform nodes using their id * @param id defines the id to search for * @returns a list of transform nodes */ Scene.prototype.getTransformNodesByID = function (id) { return this.transformNodes.filter(function (m) { return m.id === id; }); }; /** * Gets a mesh with its auto-generated unique id * @param uniqueId defines the unique id to search for * @return the found mesh or null if not found at all. */ Scene.prototype.getMeshByUniqueID = function (uniqueId) { for (var index = 0; index < this.meshes.length; index++) { if (this.meshes[index].uniqueId === uniqueId) { return this.meshes[index]; } } return null; }; /** * Gets a the last added mesh using a given id * @param id defines the id to search for * @return the found mesh or null if not found at all. */ Scene.prototype.getLastMeshByID = function (id) { for (var index = this.meshes.length - 1; index >= 0; index--) { if (this.meshes[index].id === id) { return this.meshes[index]; } } return null; }; /** * Gets a the last added node (Mesh, Camera, Light) using a given id * @param id defines the id to search for * @return the found node or null if not found at all */ Scene.prototype.getLastEntryByID = function (id) { var index; for (index = this.meshes.length - 1; index >= 0; index--) { if (this.meshes[index].id === id) { return this.meshes[index]; } } for (index = this.transformNodes.length - 1; index >= 0; index--) { if (this.transformNodes[index].id === id) { return this.transformNodes[index]; } } for (index = this.cameras.length - 1; index >= 0; index--) { if (this.cameras[index].id === id) { return this.cameras[index]; } } for (index = this.lights.length - 1; index >= 0; index--) { if (this.lights[index].id === id) { return this.lights[index]; } } return null; }; /** * Gets a node (Mesh, Camera, Light) using a given id * @param id defines the id to search for * @return the found node or null if not found at all */ Scene.prototype.getNodeByID = function (id) { var mesh = this.getMeshByID(id); if (mesh) { return mesh; } var light = this.getLightByID(id); if (light) { return light; } var camera = this.getCameraByID(id); if (camera) { return camera; } var bone = this.getBoneByID(id); return bone; }; /** * Gets a node (Mesh, Camera, Light) using a given name * @param name defines the name to search for * @return the found node or null if not found at all. */ Scene.prototype.getNodeByName = function (name) { var mesh = this.getMeshByName(name); if (mesh) { return mesh; } var light = this.getLightByName(name); if (light) { return light; } var camera = this.getCameraByName(name); if (camera) { return camera; } var bone = this.getBoneByName(name); return bone; }; /** * Gets a mesh using a given name * @param name defines the name to search for * @return the found mesh or null if not found at all. */ Scene.prototype.getMeshByName = function (name) { for (var index = 0; index < this.meshes.length; index++) { if (this.meshes[index].name === name) { return this.meshes[index]; } } return null; }; /** * Gets a transform node using a given name * @param name defines the name to search for * @return the found transform node or null if not found at all. */ Scene.prototype.getTransformNodeByName = function (name) { for (var index = 0; index < this.transformNodes.length; index++) { if (this.transformNodes[index].name === name) { return this.transformNodes[index]; } } return null; }; /** * Gets a sound using a given name * @param name defines the name to search for * @return the found sound or null if not found at all. */ Scene.prototype.getSoundByName = function (name) { var index; if (BABYLON.AudioEngine) { for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) { if (this.mainSoundTrack.soundCollection[index].name === name) { return this.mainSoundTrack.soundCollection[index]; } } 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; }; /** * Gets a skeleton using a given id (if many are found, this function will pick the last one) * @param id defines the id to search for * @return the found skeleton or null if not found at all. */ Scene.prototype.getLastSkeletonByID = function (id) { for (var index = this.skeletons.length - 1; index >= 0; index--) { if (this.skeletons[index].id === id) { return this.skeletons[index]; } } return null; }; /** * Gets a skeleton using a given id (if many are found, this function will pick the first one) * @param id defines the id to search for * @return the found skeleton or null if not found at all. */ Scene.prototype.getSkeletonById = function (id) { for (var index = 0; index < this.skeletons.length; index++) { if (this.skeletons[index].id === id) { return this.skeletons[index]; } } return null; }; /** * Gets a skeleton using a given name * @param name defines the name to search for * @return the found skeleton or null if not found at all. */ Scene.prototype.getSkeletonByName = function (name) { for (var index = 0; index < this.skeletons.length; index++) { if (this.skeletons[index].name === name) { return this.skeletons[index]; } } return null; }; /** * Gets a morph target manager using a given id (if many are found, this function will pick the last one) * @param id defines the id to search for * @return the found morph target manager or null if not found at all. */ Scene.prototype.getMorphTargetManagerById = function (id) { for (var index = 0; index < this.morphTargetManagers.length; index++) { if (this.morphTargetManagers[index].uniqueId === id) { return this.morphTargetManagers[index]; } } return null; }; /** * Gets a boolean indicating if the given mesh is active * @param mesh defines the mesh to look for * @returns true if the mesh is in the active list */ Scene.prototype.isActiveMesh = function (mesh) { return (this._activeMeshes.indexOf(mesh) !== -1); }; /** * Return a the first highlight layer of the scene with a given name. * @param name The name of the highlight layer to look for. * @return The highlight layer if found otherwise null. */ Scene.prototype.getHighlightLayerByName = function (name) { for (var index = 0; index < this.effectLayers.length; index++) { if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) { return this.effectLayers[index]; } } return null; }; /** * Return a the first highlight layer of the scene with a given name. * @param name The name of the highlight layer to look for. * @return The highlight layer if found otherwise null. */ Scene.prototype.getGlowLayerByName = function (name) { for (var index = 0; index < this.effectLayers.length; index++) { if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) { return this.effectLayers[index]; } } return null; }; Object.defineProperty(Scene.prototype, "uid", { /** * Return a unique id as a string which can serve as an identifier for the scene */ get: function () { if (!this._uid) { this._uid = BABYLON.Tools.RandomId(); } return this._uid; }, enumerable: true, configurable: true }); /** * 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 */ Scene.prototype.addExternalData = function (key, data) { if (!this._externalData) { this._externalData = new BABYLON.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 */ Scene.prototype.getExternalData = function (key) { if (!this._externalData) { return null; } 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. */ Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) { if (!this._externalData) { this._externalData = new BABYLON.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 */ Scene.prototype.removeExternalData = function (key) { return this._externalData.remove(key); }; Scene.prototype._evaluateSubMesh = function (subMesh, mesh) { if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) { if (mesh.showSubMeshesBoundingBox) { var boundingInfo = subMesh.getBoundingInfo(); if (boundingInfo !== null && boundingInfo !== undefined) { this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox); } } var material = subMesh.getMaterial(); if (material !== null && material !== undefined) { // Render targets if (material.getRenderTargetTextures !== undefined) { if (this._processedMaterials.indexOf(material) === -1) { this._processedMaterials.push(material); this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures()); } } // Dispatch this._activeIndices.addCount(subMesh.indexCount, false); this._renderingManager.dispatch(subMesh, mesh, material); } } }; /** * Clear the processed materials smart array preventing retention point in material dispose. */ Scene.prototype.freeProcessedMaterials = function () { this._processedMaterials.dispose(); }; /** * Clear the active meshes smart array preventing retention point in mesh dispose. */ Scene.prototype.freeActiveMeshes = function () { this._activeMeshes.dispose(); if (this.activeCamera && this.activeCamera._activeMeshes) { this.activeCamera._activeMeshes.dispose(); } if (this.activeCameras) { for (var i = 0; i < this.activeCameras.length; i++) { var activeCamera = this.activeCameras[i]; if (activeCamera && activeCamera._activeMeshes) { activeCamera._activeMeshes.dispose(); } } } }; /** * Clear the info related to rendering groups preventing retention points during dispose. */ Scene.prototype.freeRenderingGroups = function () { if (this._renderingManager) { this._renderingManager.freeRenderingGroups(); } if (this.textures) { for (var i = 0; i < this.textures.length; i++) { var texture = this.textures[i]; if (texture && texture.renderList) { texture.freeRenderingGroups(); } } } }; /** @hidden */ Scene.prototype._isInIntermediateRendering = function () { return this._intermediateRendering; }; /** * Defines the current active mesh candidate provider * @param provider defines the provider to use */ Scene.prototype.setActiveMeshCandidateProvider = function (provider) { this._activeMeshCandidateProvider = provider; }; /** * Gets the current active mesh candidate provider * @returns the current active mesh candidate provider */ Scene.prototype.getActiveMeshCandidateProvider = function () { return this._activeMeshCandidateProvider; }; /** * Use this function to stop evaluating active meshes. The current list will be keep alive between frames * @returns the current scene */ Scene.prototype.freezeActiveMeshes = function () { if (!this.activeCamera) { return this; } if (!this._frustumPlanes) { this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix()); } this._evaluateActiveMeshes(); this._activeMeshesFrozen = true; return this; }; /** * Use this function to restart evaluating active meshes on every frame * @returns the current scene */ Scene.prototype.unfreezeActiveMeshes = function () { this._activeMeshesFrozen = false; return this; }; Scene.prototype._evaluateActiveMeshes = function () { if (this._activeMeshesFrozen && this._activeMeshes.length) { return; } if (!this.activeCamera) { return; } this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this); this.activeCamera._activeMeshes.reset(); this._activeMeshes.reset(); this._renderingManager.reset(); this._processedMaterials.reset(); this._activeParticleSystems.reset(); this._activeSkeletons.reset(); this._softwareSkinnedMeshes.reset(); if (this._boundingBoxRenderer) { this._boundingBoxRenderer.reset(); } // Meshes var meshes; var len; var checkIsEnabled = true; // Determine mesh candidates if (this._activeMeshCandidateProvider !== undefined) { // Use _activeMeshCandidateProvider meshes = this._activeMeshCandidateProvider.getMeshes(this); checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false; if (meshes !== undefined) { len = meshes.length; } else { len = 0; } } else if (this._selectionOctree !== undefined) { // Octree var selection = this._selectionOctree.select(this._frustumPlanes); meshes = selection.data; len = selection.length; } else { // Full scene traversal len = this.meshes.length; meshes = this.meshes; } // Check each mesh for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) { mesh = meshes[meshIndex]; if (mesh.isBlocked) { continue; } this._totalVertices.addCount(mesh.getTotalVertices(), false); if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) { continue; } mesh.computeWorldMatrix(); // Intersections if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) { this._meshesForIntersections.pushNoDuplicate(mesh); } // Switch to current LOD meshLOD = mesh.getLOD(this.activeCamera); if (meshLOD === undefined || meshLOD === null) { continue; } mesh._preActivate(); if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) { this._activeMeshes.push(mesh); this.activeCamera._activeMeshes.push(mesh); mesh._activate(this._renderId); if (meshLOD !== mesh) { meshLOD._activate(this._renderId); } this._activeMesh(mesh, meshLOD); } } this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this); // Particle systems if (this.particlesEnabled) { this.onBeforeParticlesRenderingObservable.notifyObservers(this); for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) { var particleSystem = this.particleSystems[particleIndex]; if (!particleSystem.isStarted() || !particleSystem.emitter) { continue; } var emitter = particleSystem.emitter; if (!emitter.position || emitter.isEnabled()) { this._activeParticleSystems.push(particleSystem); particleSystem.animate(); this._renderingManager.dispatchParticles(particleSystem); } } this.onAfterParticlesRenderingObservable.notifyObservers(this); } }; Scene.prototype._activeMesh = function (sourceMesh, mesh) { if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) { if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) { mesh.skeleton.prepare(); } if (!mesh.computeBonesUsingShaders) { this._softwareSkinnedMeshes.pushNoDuplicate(mesh); } } if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) { var boundingInfo = sourceMesh.getBoundingInfo(); this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox); } if (mesh !== undefined && mesh !== null && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) { // Submeshes Octrees var len; var subMeshes; if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) { var intersections = mesh._submeshesOctree.select(this._frustumPlanes); len = intersections.length; subMeshes = intersections.data; } else { subMeshes = mesh.subMeshes; len = subMeshes.length; } for (var subIndex = 0, subMesh; subIndex < len; subIndex++) { subMesh = subMeshes[subIndex]; this._evaluateSubMesh(subMesh, mesh); } } }; /** * Update the transform matrix to update from the current active camera * @param force defines a boolean used to force the update even if cache is up to date */ Scene.prototype.updateTransformMatrix = function (force) { if (!this.activeCamera) { return; } this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force)); }; /** * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view) * @param alternateCamera defines the camera to use */ Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) { this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix()); }; Scene.prototype._renderForCamera = function (camera, rigParent) { if (camera && camera._skipRendering) { return; } var engine = this._engine; this.activeCamera = camera; if (!this.activeCamera) throw new Error("Active camera not set"); BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name); // Viewport engine.setViewport(this.activeCamera.viewport); // Camera this.resetCachedMaterial(); this._renderId++; this.updateTransformMatrix(); if (camera._alternateCamera) { this.updateAlternateTransformMatrix(camera._alternateCamera); this._alternateRendering = true; } this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera); // Meshes this._evaluateActiveMeshes(); // Software skinning for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) { var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex]; mesh.applySkeleton(mesh.skeleton); } // Render targets this.onBeforeRenderTargetsRenderObservable.notifyObservers(this); var needsRestoreFrameBuffer = false; if (camera.customRenderTargets && camera.customRenderTargets.length > 0) { this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets); } if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) { this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets); } if (this.renderTargetsEnabled && this._renderTargets.length > 0) { this._intermediateRendering = true; BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0); for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) { var renderTarget = this._renderTargets.data[renderIndex]; if (renderTarget._shouldRender()) { this._renderId++; var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera; renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets); } } BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0); this._intermediateRendering = false; this._renderId++; needsRestoreFrameBuffer = true; // Restore back buffer } // Render EffecttLayer Texture var stencilState = this._engine.getStencilBuffer(); var renderEffects = false; var needStencil = false; if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) { this._intermediateRendering = true; for (var i = 0; i < this.effectLayers.length; i++) { var effectLayer = this.effectLayers[i]; if (effectLayer.shouldRender() && (!effectLayer.camera || (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) || (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) { renderEffects = true; needStencil = needStencil || effectLayer.needStencil(); var renderTarget = effectLayer._mainTexture; if (renderTarget._shouldRender()) { this._renderId++; renderTarget.render(false, false); needsRestoreFrameBuffer = true; } } } this._intermediateRendering = false; this._renderId++; } if (needsRestoreFrameBuffer) { engine.restoreDefaultFramebuffer(); // Restore back buffer } this.onAfterRenderTargetsRenderObservable.notifyObservers(this); // Prepare Frame this.postProcessManager._prepareFrame(); // Backgrounds var layerIndex; var layer; if (this.layers.length) { engine.setDepthBuffer(false); for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) { layer = this.layers[layerIndex]; if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) { layer.render(); } } engine.setDepthBuffer(true); } // Activate effect Layer stencil if (needStencil) { this._engine.setStencilBuffer(true); } // Render this.onBeforeDrawPhaseObservable.notifyObservers(this); this._renderingManager.render(null, null, true, true); this.onAfterDrawPhaseObservable.notifyObservers(this); // Restore effect Layer stencil if (needStencil) { this._engine.setStencilBuffer(stencilState); } // Bounding boxes if (this._boundingBoxRenderer) { this._boundingBoxRenderer.render(); } // Lens flares if (this.lensFlaresEnabled) { BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0); for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) { var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex]; if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) { lensFlareSystem.render(); } } BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0); } // Effect Layer if (renderEffects) { engine.setDepthBuffer(false); for (var i = 0; i < this.effectLayers.length; i++) { if (this.effectLayers[i].shouldRender()) { this.effectLayers[i].render(); } } engine.setDepthBuffer(true); } // Foregrounds if (this.layers.length) { engine.setDepthBuffer(false); for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) { layer = this.layers[layerIndex]; if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) { layer.render(); } } engine.setDepthBuffer(true); } // Finalize frame this.postProcessManager._finalizeFrame(camera.isIntermediate); // Reset some special arrays this._renderTargets.reset(); this._alternateRendering = false; this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera); BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name); }; Scene.prototype._processSubCameras = function (camera) { if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) { this._renderForCamera(camera); return; } // rig cameras for (var index = 0; index < camera._rigCameras.length; index++) { this._renderForCamera(camera._rigCameras[index], camera); } this.activeCamera = camera; this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix()); }; Scene.prototype._checkIntersections = function () { for (var index = 0; index < this._meshesForIntersections.length; index++) { var sourceMesh = this._meshesForIntersections.data[index]; if (!sourceMesh.actionManager) { continue; } for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) { var action = sourceMesh.actionManager.actions[actionIndex]; if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) { var parameters = action.getTriggerParameter(); var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh; var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection); var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh); if (areIntersecting && currentIntersectionInProgress === -1) { if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) { action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh)); sourceMesh._intersectionsInProgress.push(otherMesh); } else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) { sourceMesh._intersectionsInProgress.push(otherMesh); } } else if (!areIntersecting && currentIntersectionInProgress > -1) { //They intersected, and now they don't. //is this trigger an exit trigger? execute an event. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) { action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh)); } //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) { var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh; return otherMesh === parameterMesh; }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) { sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1); } } } } } }; /** * Render the scene * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default) */ Scene.prototype.render = function (updateCameras) { if (updateCameras === void 0) { updateCameras = true; } if (this.isDisposed) { return; } this._activeParticles.fetchNewFrame(); this._totalVertices.fetchNewFrame(); this._activeIndices.fetchNewFrame(); this._activeBones.fetchNewFrame(); this._meshesForIntersections.reset(); this.resetCachedMaterial(); this.onBeforeAnimationsObservable.notifyObservers(this); // Actions if (this.actionManager) { this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger); } //Simplification Queue if (this.simplificationQueue && !this.simplificationQueue.running) { this.simplificationQueue.executeNext(); } if (this._engine.isDeterministicLockStep()) { var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator; var defaultFPS = (60.0 / 1000.0); var defaultFrameTime = 1000 / 60; // frame time in MS if (this._physicsEngine) { defaultFrameTime = this._physicsEngine.getTimeStep() * 1000; } var stepsTaken = 0; var maxSubSteps = this._engine.getLockstepMaxSteps(); var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS)); internalSteps = Math.min(internalSteps, maxSubSteps); do { this.onBeforeStepObservable.notifyObservers(this); // Animations this._animationRatio = defaultFrameTime * defaultFPS; this._animate(); this.onAfterAnimationsObservable.notifyObservers(this); // Physics if (this._physicsEngine) { this.onBeforePhysicsObservable.notifyObservers(this); this._physicsEngine._step(defaultFrameTime / 1000); this.onAfterPhysicsObservable.notifyObservers(this); } this.onAfterStepObservable.notifyObservers(this); this._currentStepId++; stepsTaken++; deltaTime -= defaultFrameTime; } while (deltaTime > 0 && stepsTaken < internalSteps); this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime; } else { // Animations var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)); this._animationRatio = deltaTime * (60.0 / 1000.0); this._animate(); this.onAfterAnimationsObservable.notifyObservers(this); // Physics if (this._physicsEngine) { this.onBeforePhysicsObservable.notifyObservers(this); this._physicsEngine._step(deltaTime / 1000.0); this.onAfterPhysicsObservable.notifyObservers(this); } } // update gamepad manager if (this._gamepadManager && this._gamepadManager._isMonitoring) { this._gamepadManager._checkGamepadsStatus(); } // Update Cameras if (updateCameras) { if (this.activeCameras.length > 0) { for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) { var camera = this.activeCameras[cameraIndex]; camera.update(); if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) { // rig cameras for (var index = 0; index < camera._rigCameras.length; index++) { camera._rigCameras[index].update(); } } } } else if (this.activeCamera) { this.activeCamera.update(); if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) { // rig cameras for (var index = 0; index < this.activeCamera._rigCameras.length; index++) { this.activeCamera._rigCameras[index].update(); } } } } // Before render this.onBeforeRenderObservable.notifyObservers(this); // Customs render targets this.onBeforeRenderTargetsRenderObservable.notifyObservers(this); var engine = this.getEngine(); var currentActiveCamera = this.activeCamera; if (this.renderTargetsEnabled) { BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0); this._intermediateRendering = true; for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) { var renderTarget = this.customRenderTargets[customIndex]; if (renderTarget._shouldRender()) { this._renderId++; this.activeCamera = renderTarget.activeCamera || this.activeCamera; if (!this.activeCamera) throw new Error("Active camera not set"); // Viewport engine.setViewport(this.activeCamera.viewport); // Camera this.updateTransformMatrix(); renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets); } } BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0); this._intermediateRendering = false; this._renderId++; } // Restore back buffer if (this.customRenderTargets.length > 0) { engine.restoreDefaultFramebuffer(); } this.onAfterRenderTargetsRenderObservable.notifyObservers(this); this.activeCamera = currentActiveCamera; // Procedural textures if (this.proceduralTexturesEnabled) { BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0); for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) { var proceduralTexture = this.proceduralTextures[proceduralIndex]; if (proceduralTexture._shouldRender()) { proceduralTexture.render(); } } BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0); } // Clear if (this.autoClearDepthAndStencil || this.autoClear) { this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil); } // Shadows if (this.shadowsEnabled) { for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) { var light = this.lights[lightIndex]; var shadowGenerator = light.getShadowGenerator(); if (light.isEnabled() && light.shadowEnabled && shadowGenerator) { var shadowMap = (shadowGenerator.getShadowMap()); if (this.textures.indexOf(shadowMap) !== -1) { this._renderTargets.push(shadowMap); } } } } // Depth renderer for (var key in this._depthRenderer) { this._renderTargets.push(this._depthRenderer[key].getDepthMap()); } // Geometry renderer if (this._geometryBufferRenderer) { this._renderTargets.push(this._geometryBufferRenderer.getGBuffer()); } // RenderPipeline if (this._postProcessRenderPipelineManager) { this._postProcessRenderPipelineManager.update(); } // Multi-cameras? if (this.activeCameras.length > 0) { for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) { if (cameraIndex > 0) { this._engine.clear(null, false, true, true); } this._processSubCameras(this.activeCameras[cameraIndex]); } } else { if (!this.activeCamera) { throw new Error("No camera defined"); } this._processSubCameras(this.activeCamera); } // Intersection checks this._checkIntersections(); // Update the audio listener attached to the camera if (BABYLON.AudioEngine) { this._updateAudioParameters(); } // After render if (this.afterRender) { this.afterRender(); } this.onAfterRenderObservable.notifyObservers(this); // Cleaning for (var index = 0; index < this._toBeDisposed.length; index++) { var data = this._toBeDisposed.data[index]; if (data) { data.dispose(); } this._toBeDisposed[index] = null; } this._toBeDisposed.reset(); if (this.dumpNextRenderTargets) { this.dumpNextRenderTargets = false; } this._activeBones.addCount(0, true); this._activeIndices.addCount(0, true); this._activeParticles.addCount(0, true); }; Scene.prototype._updateAudioParameters = function () { if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) { return; } var listeningCamera; var audioEngine = BABYLON.Engine.audioEngine; if (this.activeCameras.length > 0) { listeningCamera = this.activeCameras[0]; } else { listeningCamera = this.activeCamera; } if (listeningCamera && audioEngine.canUseWebAudio && 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 = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix()); var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.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 < this.mainSoundTrack.soundCollection.length; i++) { var sound = this.mainSoundTrack.soundCollection[i]; if (sound.useCustomAttenuation) { sound.updateDistanceFromListener(); } } for (i = 0; i < this.soundTracks.length; i++) { for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) { sound = this.soundTracks[i].soundCollection[j]; if (sound.useCustomAttenuation) { sound.updateDistanceFromListener(); } } } } }; Object.defineProperty(Scene.prototype, "audioEnabled", { // Audio /** * Gets or sets if audio support is enabled * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music */ get: function () { return this._audioEnabled; }, set: function (value) { this._audioEnabled = value; if (BABYLON.AudioEngine) { if (this._audioEnabled) { this._enableAudio(); } else { this._disableAudio(); } } }, enumerable: true, configurable: true }); Scene.prototype._disableAudio = function () { var i; for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) { this.mainSoundTrack.soundCollection[i].pause(); } for (i = 0; i < this.soundTracks.length; i++) { for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) { this.soundTracks[i].soundCollection[j].pause(); } } }; Scene.prototype._enableAudio = function () { var i; for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) { if (this.mainSoundTrack.soundCollection[i].isPaused) { this.mainSoundTrack.soundCollection[i].play(); } } for (i = 0; i < this.soundTracks.length; i++) { for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) { if (this.soundTracks[i].soundCollection[j].isPaused) { this.soundTracks[i].soundCollection[j].play(); } } } }; Object.defineProperty(Scene.prototype, "headphone", { /** * Gets or sets if audio will be output to headphones * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music */ get: function () { return this._headphone; }, set: function (value) { this._headphone = value; if (BABYLON.AudioEngine) { if (this._headphone) { this._switchAudioModeForHeadphones(); } else { this._switchAudioModeForNormalSpeakers(); } } }, enumerable: true, configurable: true }); Scene.prototype._switchAudioModeForHeadphones = function () { this.mainSoundTrack.switchPanningModelToHRTF(); for (var i = 0; i < this.soundTracks.length; i++) { this.soundTracks[i].switchPanningModelToHRTF(); } }; Scene.prototype._switchAudioModeForNormalSpeakers = function () { this.mainSoundTrack.switchPanningModelToEqualPower(); for (var i = 0; i < this.soundTracks.length; i++) { this.soundTracks[i].switchPanningModelToEqualPower(); } }; /** * Creates a depth renderer a given camera which contains a depth map which can be used for post processing. * @param camera The camera to create the depth renderer on (default: scene's active camera) * @returns the created depth renderer */ Scene.prototype.enableDepthRenderer = function (camera) { camera = camera || this.activeCamera; if (!camera) { throw "No camera available to enable depth renderer"; } if (!this._depthRenderer[camera.id]) { var textureType = 0; if (this._engine.getCaps().textureHalfFloatRender) { textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT; } else if (this._engine.getCaps().textureFloatRender) { textureType = BABYLON.Engine.TEXTURETYPE_FLOAT; } else { throw "Depth renderer does not support int texture type"; } this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera); } return this._depthRenderer[camera.id]; }; /** * Disables a depth renderer for a given camera * @param camera The camera to disable the depth renderer on (default: scene's active camera) */ Scene.prototype.disableDepthRenderer = function (camera) { camera = camera || this.activeCamera; if (!camera || !this._depthRenderer[camera.id]) { return; } this._depthRenderer[camera.id].dispose(); delete this._depthRenderer[camera.id]; }; /** * Enables a GeometryBufferRender and associates it with the scene * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution) * @returns the GeometryBufferRenderer */ Scene.prototype.enableGeometryBufferRenderer = function (ratio) { if (ratio === void 0) { ratio = 1; } if (this._geometryBufferRenderer) { return this._geometryBufferRenderer; } this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio); if (!this._geometryBufferRenderer.isSupported) { this._geometryBufferRenderer = null; } return this._geometryBufferRenderer; }; /** * Disables the GeometryBufferRender associated with the scene */ Scene.prototype.disableGeometryBufferRenderer = function () { if (!this._geometryBufferRenderer) { return; } this._geometryBufferRenderer.dispose(); this._geometryBufferRenderer = null; }; /** * Freeze all materials * A frozen material will not be updatable but should be faster to render */ Scene.prototype.freezeMaterials = function () { for (var i = 0; i < this.materials.length; i++) { this.materials[i].freeze(); } }; /** * Unfreeze all materials * A frozen material will not be updatable but should be faster to render */ Scene.prototype.unfreezeMaterials = function () { for (var i = 0; i < this.materials.length; i++) { this.materials[i].unfreeze(); } }; /** * Releases all held ressources */ Scene.prototype.dispose = function () { this.beforeRender = null; this.afterRender = null; this.skeletons = []; this.morphTargetManagers = []; this.importedMeshesFiles = new Array(); this.stopAllAnimations(); this.resetCachedMaterial(); for (var key in this._depthRenderer) { this._depthRenderer[key].dispose(); } if (this._gamepadManager) { this._gamepadManager.dispose(); this._gamepadManager = null; } // Smart arrays if (this.activeCamera) { this.activeCamera._activeMeshes.dispose(); this.activeCamera = null; } this._activeMeshes.dispose(); this._renderingManager.dispose(); this._processedMaterials.dispose(); this._activeParticleSystems.dispose(); this._activeSkeletons.dispose(); this._softwareSkinnedMeshes.dispose(); this._renderTargets.dispose(); this._registeredForLateAnimationBindings.dispose(); if (this._boundingBoxRenderer) { this._boundingBoxRenderer.dispose(); } this._meshesForIntersections.dispose(); this._toBeDisposed.dispose(); // Abort active requests for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) { var request = _a[_i]; request.abort(); } // Debug layer if (this._debugLayer) { this._debugLayer.hide(); } // Events this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); this.onBeforeRenderObservable.clear(); this.onAfterRenderObservable.clear(); this.onBeforeRenderTargetsRenderObservable.clear(); this.onAfterRenderTargetsRenderObservable.clear(); this.onAfterStepObservable.clear(); this.onBeforeStepObservable.clear(); this.onBeforeActiveMeshesEvaluationObservable.clear(); this.onAfterActiveMeshesEvaluationObservable.clear(); this.onBeforeParticlesRenderingObservable.clear(); this.onAfterParticlesRenderingObservable.clear(); this.onBeforeSpritesRenderingObservable.clear(); this.onAfterSpritesRenderingObservable.clear(); this.onBeforeDrawPhaseObservable.clear(); this.onAfterDrawPhaseObservable.clear(); this.onBeforePhysicsObservable.clear(); this.onAfterPhysicsObservable.clear(); this.onBeforeAnimationsObservable.clear(); this.onAfterAnimationsObservable.clear(); this.onDataLoadedObservable.clear(); this.detachControl(); // Release sounds & sounds tracks if (BABYLON.AudioEngine) { this.disposeSounds(); } // VR Helper if (this.VRHelper) { this.VRHelper.dispose(); } // Detach cameras var canvas = this._engine.getRenderingCanvas(); if (canvas) { var index; for (index = 0; index < this.cameras.length; index++) { this.cameras[index].detachControl(canvas); } } // Release animation groups while (this.animationGroups.length) { this.animationGroups[0].dispose(); } // Release lights while (this.lights.length) { this.lights[0].dispose(); } // Release meshes while (this.meshes.length) { this.meshes[0].dispose(true); } while (this.transformNodes.length) { this.removeTransformNode(this.transformNodes[0]); } // Release cameras while (this.cameras.length) { this.cameras[0].dispose(); } // Release materials if (this.defaultMaterial) { this.defaultMaterial.dispose(); } while (this.multiMaterials.length) { this.multiMaterials[0].dispose(); } while (this.materials.length) { this.materials[0].dispose(); } // Release particles while (this.particleSystems.length) { this.particleSystems[0].dispose(); } // Release sprites while (this.spriteManagers.length) { this.spriteManagers[0].dispose(); } // Release postProcesses while (this.postProcesses.length) { this.postProcesses[0].dispose(); } // Release layers while (this.layers.length) { this.layers[0].dispose(); } while (this.effectLayers.length) { this.effectLayers[0].dispose(); } // Release textures while (this.textures.length) { this.textures[0].dispose(); } // Release UBO this._sceneUbo.dispose(); if (this._alternateSceneUbo) { this._alternateSceneUbo.dispose(); } // Post-processes this.postProcessManager.dispose(); if (this._postProcessRenderPipelineManager) { this._postProcessRenderPipelineManager.dispose(); } // Physics if (this._physicsEngine) { this.disablePhysicsEngine(); } // Remove from engine index = this._engine.scenes.indexOf(this); if (index > -1) { this._engine.scenes.splice(index, 1); } this._engine.wipeCaches(true); this._isDisposed = true; }; Object.defineProperty(Scene.prototype, "isDisposed", { /** * Gets if the scene is already disposed */ get: function () { return this._isDisposed; }, enumerable: true, configurable: true }); /** * Releases sounds & soundtracks */ Scene.prototype.disposeSounds = function () { if (!this._mainSoundTrack) { return; } this.mainSoundTrack.dispose(); for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) { this.soundTracks[scIndex].dispose(); } }; /** * Call this function to reduce memory footprint of the scene. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly) */ Scene.prototype.clearCachedVertexData = function () { for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) { var mesh = this.meshes[meshIndex]; var geometry = mesh.geometry; if (geometry) { geometry._indices = []; for (var vbName in geometry._vertexBuffers) { if (!geometry._vertexBuffers.hasOwnProperty(vbName)) { continue; } geometry._vertexBuffers[vbName]._buffer._data = null; } } } }; /** * This function will remove the local cached buffer data from texture. * It will save memory but will prevent the texture from being rebuilt */ Scene.prototype.cleanCachedTextureBuffer = function () { for (var _i = 0, _a = this.textures; _i < _a.length; _i++) { var baseTexture = _a[_i]; var buffer = baseTexture._buffer; if (buffer) { baseTexture._buffer = null; } } }; // Octrees /** * Get the world extend vectors with an optional filter * * @param filterPredicate the predicate - which meshes should be included when calculating the world size * @returns {{ min: Vector3; max: Vector3 }} min and max vectors */ Scene.prototype.getWorldExtends = function (filterPredicate) { var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); filterPredicate = filterPredicate || (function () { return true; }); this.meshes.filter(filterPredicate).forEach(function (mesh) { mesh.computeWorldMatrix(true); if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) { return; } var boundingInfo = mesh.getBoundingInfo(); var minBox = boundingInfo.boundingBox.minimumWorld; var maxBox = boundingInfo.boundingBox.maximumWorld; BABYLON.Tools.CheckExtends(minBox, min, max); BABYLON.Tools.CheckExtends(maxBox, min, max); }); return { min: min, max: max }; }; /** * Creates or updates the octree used to boost selection (picking) * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees * @param maxCapacity defines the maximum capacity per leaf * @param maxDepth defines the maximum depth of the octree * @returns an octree of AbstractMesh */ Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) { if (maxCapacity === void 0) { maxCapacity = 64; } if (maxDepth === void 0) { maxDepth = 2; } if (!this._selectionOctree) { this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth); } var worldExtends = this.getWorldExtends(); // Update octree this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes); return this._selectionOctree; }; // Picking /** * Creates a ray that can be used to pick in the scene * @param x defines the x coordinate of the origin (on-screen) * @param y defines the y coordinate of the origin (on-screen) * @param world defines the world matrix to use if you want to pick in object space (instead of world space) * @param camera defines the camera to use for the picking * @param cameraViewSpace defines if picking will be done in view space (false by default) * @returns a Ray */ Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) { if (cameraViewSpace === void 0) { cameraViewSpace = false; } var result = BABYLON.Ray.Zero(); this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace); return result; }; /** * Creates a ray that can be used to pick in the scene * @param x defines the x coordinate of the origin (on-screen) * @param y defines the y coordinate of the origin (on-screen) * @param world defines the world matrix to use if you want to pick in object space (instead of world space) * @param result defines the ray where to store the picking ray * @param camera defines the camera to use for the picking * @param cameraViewSpace defines if picking will be done in view space (false by default) * @returns the current scene */ Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) { if (cameraViewSpace === void 0) { cameraViewSpace = false; } var engine = this._engine; 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 / this._engine.getHardwareScalingLevel() - viewport.x; y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height); result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix()); return this; }; /** * Creates a ray that can be used to pick in the scene * @param x defines the x coordinate of the origin (on-screen) * @param y defines the y coordinate of the origin (on-screen) * @param camera defines the camera to use for the picking * @returns a Ray */ Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) { var result = BABYLON.Ray.Zero(); this.createPickingRayInCameraSpaceToRef(x, y, result, camera); return result; }; /** * Creates a ray that can be used to pick in the scene * @param x defines the x coordinate of the origin (on-screen) * @param y defines the y coordinate of the origin (on-screen) * @param result defines the ray where to store the picking ray * @param camera defines the camera to use for the picking * @returns the current scene */ Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) { if (!BABYLON.PickingInfo) { return this; } var engine = this._engine; 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 = BABYLON.Matrix.Identity(); // Moving coordinates to local viewport world x = x / this._engine.getHardwareScalingLevel() - viewport.x; y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height); result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix()); return this; }; Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) { if (!BABYLON.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); if (!result || !result.hit) continue; if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) continue; pickingInfo = result; if (fastCheck) { break; } } return pickingInfo || new BABYLON.PickingInfo(); }; Scene.prototype._internalMultiPick = function (rayFunction, predicate) { if (!BABYLON.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); if (!result || !result.hit) continue; pickingInfos.push(result); } return pickingInfos; }; Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) { if (!BABYLON.PickingInfo) { return null; } var pickingInfo = null; if (!camera) { if (!this.activeCamera) { return null; } camera = this.activeCamera; } if (this.spriteManagers.length > 0) { for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) { var spriteManager = this.spriteManagers[spriteIndex]; if (!spriteManager.isPickable) { continue; } var result = spriteManager.intersects(ray, camera, predicate, fastCheck); if (!result || !result.hit) continue; if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) continue; pickingInfo = result; if (fastCheck) { break; } } } return pickingInfo || new BABYLON.PickingInfo(); }; /** Launch a ray to try to pick a mesh in the scene * @param x position on screen * @param y position on screen * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used * @returns a PickingInfo */ Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) { var _this = this; if (!BABYLON.PickingInfo) { return null; } var result = this._internalPick(function (world) { _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null); return _this._tempPickingRay; }, predicate, fastCheck); if (result) { result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null); } return result; }; /** Launch a ray to try to pick a sprite in the scene * @param x position on screen * @param y position on screen * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used * @returns a PickingInfo */ Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) { this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera); return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera); }; /** Use the given ray to pick a mesh in the scene * @param ray The ray to use to pick meshes * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null * @returns a PickingInfo */ Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) { var _this = this; var result = this._internalPick(function (world) { if (!_this._pickWithRayInverseMatrix) { _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity(); } world.invertToRef(_this._pickWithRayInverseMatrix); if (!_this._cachedRayForTransform) { _this._cachedRayForTransform = BABYLON.Ray.Zero(); } BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform); return _this._cachedRayForTransform; }, predicate, fastCheck); if (result) { result.ray = ray; } return result; }; /** * Launch a ray to try to pick a mesh in the scene * @param x X position on screen * @param y Y position on screen * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used * @returns an array of PickingInfo */ Scene.prototype.multiPick = function (x, y, predicate, camera) { var _this = this; return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate); }; /** * Launch a ray to try to pick a mesh in the scene * @param ray Ray to use * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true * @returns an array of PickingInfo */ Scene.prototype.multiPickWithRay = function (ray, predicate) { var _this = this; return this._internalMultiPick(function (world) { if (!_this._pickWithRayInverseMatrix) { _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity(); } world.invertToRef(_this._pickWithRayInverseMatrix); if (!_this._cachedRayForTransform) { _this._cachedRayForTransform = BABYLON.Ray.Zero(); } BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform); return _this._cachedRayForTransform; }, predicate); }; /** * Force the value of meshUnderPointer * @param mesh defines the mesh to use */ Scene.prototype.setPointerOverMesh = function (mesh) { if (this._pointerOverMesh === mesh) { return; } if (this._pointerOverMesh && this._pointerOverMesh.actionManager) { this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh)); } this._pointerOverMesh = mesh; if (this._pointerOverMesh && this._pointerOverMesh.actionManager) { this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh)); } }; /** * Gets the mesh under the pointer * @returns a Mesh or null if no mesh is under the pointer */ Scene.prototype.getPointerOverMesh = function () { return this._pointerOverMesh; }; /** * Force the sprite under the pointer * @param sprite defines the sprite to use */ Scene.prototype.setPointerOverSprite = function (sprite) { if (this._pointerOverSprite === sprite) { return; } if (this._pointerOverSprite && this._pointerOverSprite.actionManager) { this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this)); } this._pointerOverSprite = sprite; if (this._pointerOverSprite && this._pointerOverSprite.actionManager) { this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this)); } }; /** * Gets the sprite under the pointer * @returns a Sprite or null if no sprite is under the pointer */ Scene.prototype.getPointerOverSprite = function () { return this._pointerOverSprite; }; // Physics /** * Gets the current physics engine * @returns a PhysicsEngine or null if none attached */ Scene.prototype.getPhysicsEngine = function () { return this._physicsEngine; }; /** * Enables physics to the current scene * @param gravity defines the scene's gravity for the physics engine * @param plugin defines the physics engine to be used. defaults to OimoJS. * @return a boolean indicating if the physics engine was initialized */ Scene.prototype.enablePhysics = function (gravity, plugin) { if (gravity === void 0) { gravity = null; } if (this._physicsEngine) { return true; } try { this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin); return true; } catch (e) { BABYLON.Tools.Error(e.message); return false; } }; /** * Disables and disposes the physics engine associated with the scene */ Scene.prototype.disablePhysicsEngine = function () { if (!this._physicsEngine) { return; } this._physicsEngine.dispose(); this._physicsEngine = null; }; /** * Gets a boolean indicating if there is an active physics engine * @returns a boolean indicating if there is an active physics engine */ Scene.prototype.isPhysicsEnabled = function () { return this._physicsEngine !== undefined; }; /** * Deletes a physics compound impostor * @param compound defines the compound to delete */ Scene.prototype.deleteCompoundImpostor = function (compound) { var mesh = compound.parts[0].mesh; if (mesh.physicsImpostor) { mesh.physicsImpostor.dispose( /*true*/); mesh.physicsImpostor = null; } }; // Misc. /** @hidden */ Scene.prototype._rebuildGeometries = function () { for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) { var geometry = _a[_i]; geometry._rebuild(); } for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) { var mesh = _c[_b]; mesh._rebuild(); } if (this.postProcessManager) { this.postProcessManager._rebuild(); } for (var _d = 0, _e = this.layers; _d < _e.length; _d++) { var layer = _e[_d]; layer._rebuild(); } for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) { var effectLayer = _g[_f]; effectLayer._rebuild(); } if (this._boundingBoxRenderer) { this._boundingBoxRenderer._rebuild(); } for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) { var system = _j[_h]; system.rebuild(); } if (this._postProcessRenderPipelineManager) { this._postProcessRenderPipelineManager._rebuild(); } }; /** @hidden */ Scene.prototype._rebuildTextures = function () { for (var _i = 0, _a = this.textures; _i < _a.length; _i++) { var texture = _a[_i]; texture._rebuild(); } this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag); }; /** * Creates a default light for the scene. * @param replace Whether to replace the existing lights in the scene. */ 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 BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this); } }; /** * Creates a default camera for the scene. * @param createArcRotateCamera Whether to create an arc rotate or a free camera. * @param replace Whether to replace the existing active camera in the scene. * @param attachCameraControls Whether to attach camera controls to the canvas. */ 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 BABYLON.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 BABYLON.FreeCamera("default camera", new BABYLON.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); } } }; /** * Creates a default camera and a default light * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera * @param replace defines if the camera and/or light will replace the existing ones * @param attachCameraControls defines if attachControl will be called on the new camera */ 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); }; /** * Creates a new sky box * @see http://doc.babylonjs.com/babylon101/environment#skybox * @param environmentTexture defines the texture to use as environment texture * @param pbr defines if PBRMaterial must be used instead of StandardMaterial * @param scale defines the overall scale of the skybox * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true) * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default) * @returns a new mesh holding the sky box */ 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) { BABYLON.Tools.Warn("Can not create default skybox without environment texture."); return null; } if (setGlobalEnvTexture) { if (environmentTexture) { this.environmentTexture = environmentTexture; } } // Skybox var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this); if (pbr) { var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this); hdrSkyboxMaterial.backFaceCulling = false; hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone(); if (hdrSkyboxMaterial.reflectionTexture) { hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE; } hdrSkyboxMaterial.microSurface = 1.0 - blur; hdrSkyboxMaterial.disableLighting = true; hdrSkyboxMaterial.twoSidedLighting = true; hdrSkybox.infiniteDistance = true; hdrSkybox.material = hdrSkyboxMaterial; } else { var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this); skyboxMaterial.backFaceCulling = false; skyboxMaterial.reflectionTexture = environmentTexture.clone(); if (skyboxMaterial.reflectionTexture) { skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE; } skyboxMaterial.disableLighting = true; hdrSkybox.infiniteDistance = true; hdrSkybox.material = skyboxMaterial; } return hdrSkybox; }; /** * Creates a new environment * @see http://doc.babylonjs.com/babylon101/environment#skybox * @param options defines the options you can use to configure the environment * @returns the new EnvironmentHelper */ Scene.prototype.createDefaultEnvironment = function (options) { if (BABYLON.EnvironmentHelper) { return new BABYLON.EnvironmentHelper(options, this); } return null; }; /** * Creates a new VREXperienceHelper * @see http://doc.babylonjs.com/how_to/webvr_helper * @param webVROptions defines the options used to create the new VREXperienceHelper * @returns a new VREXperienceHelper */ Scene.prototype.createDefaultVRExperience = function (webVROptions) { if (webVROptions === void 0) { webVROptions = {}; } return new BABYLON.VRExperienceHelper(this, webVROptions); }; // Tags Scene.prototype._getByTags = function (list, tagsQuery, forEach) { if (tagsQuery === undefined) { // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here) return list; } var listByTags = []; forEach = forEach || (function (item) { return; }); for (var i in list) { var item = list[i]; if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) { listByTags.push(item); forEach(item); } } return listByTags; }; /** * Get a list of meshes by tags * @param tagsQuery defines the tags query to use * @param forEach defines a predicate used to filter results * @returns an array of Mesh */ Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) { return this._getByTags(this.meshes, tagsQuery, forEach); }; /** * Get a list of cameras by tags * @param tagsQuery defines the tags query to use * @param forEach defines a predicate used to filter results * @returns an array of Camera */ Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) { return this._getByTags(this.cameras, tagsQuery, forEach); }; /** * Get a list of lights by tags * @param tagsQuery defines the tags query to use * @param forEach defines a predicate used to filter results * @returns an array of Light */ Scene.prototype.getLightsByTags = function (tagsQuery, forEach) { return this._getByTags(this.lights, tagsQuery, forEach); }; /** * Get a list of materials by tags * @param tagsQuery defines the tags query to use * @param forEach defines a predicate used to filter results * @returns an array of Material */ Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) { return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach)); }; /** * 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. */ Scene.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. * @param depth Automatically clears depth between groups if true and autoClear is true. * @param stencil Automatically clears stencil between groups if true and autoClear is true. */ Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) { if (depth === void 0) { depth = true; } if (stencil === void 0) { stencil = true; } this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil); }; /** * Will flag all materials as dirty to trigger new shader compilation * @param flag defines the flag used to specify which material part must be marked as dirty * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty */ Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) { for (var _i = 0, _a = this.materials; _i < _a.length; _i++) { var material = _a[_i]; if (predicate && !predicate(material)) { continue; } material.markAsDirty(flag); } }; /** @hidden */ Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) { var _this = this; var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError); this._activeRequests.push(request); request.onCompleteObservable.add(function (request) { _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1); }); return request; }; /** @hidden */ Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) { var _this = this; return new Promise(function (resolve, reject) { _this._loadFile(url, function (data) { resolve(data); }, undefined, useDatabase, useArrayBuffer, function (request, exception) { reject(exception); }); }); }; // Statics Scene._FOGMODE_NONE = 0; Scene._FOGMODE_EXP = 1; Scene._FOGMODE_EXP2 = 2; Scene._FOGMODE_LINEAR = 3; Scene._uniqueIdCounter = 0; /** * Gets or sets the minimum deltatime when deterministic lock step is enabled * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep */ Scene.MinDeltaTime = 1.0; /** * Gets or sets the maximum deltatime when deterministic lock step is enabled * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep */ Scene.MaxDeltaTime = 1000.0; /** The distance in pixel that you have to move to prevent some events */ Scene.DragMovementThreshold = 10; // in pixels /** Time in milliseconds to wait to raise long press events if button is still pressed */ Scene.LongPressDelay = 500; // in milliseconds /** Time in milliseconds with two consecutive clicks will be considered as a double click */ Scene.DoubleClickDelay = 300; // in milliseconds /** If you need to check double click without raising a single click at first click, enable this flag */ Scene.ExclusiveDoubleClickMode = false; return Scene; }()); BABYLON.Scene = Scene; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.scene.js.map var BABYLON; (function (BABYLON) { /** * Set of assets to keep when moving a scene into an asset container. */ var KeepAssets = /** @class */ (function () { function KeepAssets() { /** * Cameras to keep. */ this.cameras = new Array(); /** * Lights to keep. */ this.lights = new Array(); /** * Meshes to keep. */ this.meshes = new Array(); /** * Skeletons to keep. */ this.skeletons = new Array(); /** * ParticleSystems to keep. */ this.particleSystems = new Array(); /** * Animations to keep. */ this.animations = new Array(); /** * AnimationGroups to keep. */ this.animationGroups = new Array(); /** * MultiMaterials to keep. */ this.multiMaterials = new Array(); /** * Materials to keep. */ this.materials = new Array(); /** * MorphTargetManagers to keep. */ this.morphTargetManagers = new Array(); /** * Geometries to keep. */ this.geometries = new Array(); /** * TransformNodes to keep. */ this.transformNodes = new Array(); /** * LensFlareSystems to keep. */ this.lensFlareSystems = new Array(); /** * ShadowGenerators to keep. */ this.shadowGenerators = new Array(); /** * ActionManagers to keep. */ this.actionManagers = new Array(); /** * Sounds to keep. */ this.sounds = new Array(); /** * Textures to keep. */ this.textures = new Array(); /** * Effect layers to keep. */ this.effectLayers = new Array(); } return KeepAssets; }()); BABYLON.KeepAssets = KeepAssets; /** * Container with a set of assets that can be added or removed from a scene. */ var AssetContainer = /** @class */ (function () { /** * Instantiates an AssetContainer. * @param scene The scene the AssetContainer belongs to. */ function AssetContainer(scene) { // Objects /** * Cameras populated in the container. */ this.cameras = new Array(); /** * Lights populated in the container. */ this.lights = new Array(); /** * Meshes populated in the container. */ this.meshes = new Array(); /** * Skeletons populated in the container. */ this.skeletons = new Array(); /** * ParticleSystems populated in the container. */ this.particleSystems = new Array(); /** * Animations populated in the container. */ this.animations = new Array(); /** * AnimationGroups populated in the container. */ this.animationGroups = new Array(); /** * MultiMaterials populated in the container. */ this.multiMaterials = new Array(); /** * Materials populated in the container. */ this.materials = new Array(); /** * MorphTargetManagers populated in the container. */ this.morphTargetManagers = new Array(); /** * Geometries populated in the container. */ this.geometries = new Array(); /** * TransformNodes populated in the container. */ this.transformNodes = new Array(); /** * LensFlareSystems populated in the container. */ this.lensFlareSystems = new Array(); /** * ShadowGenerators populated in the container. */ this.shadowGenerators = new Array(); /** * ActionManagers populated in the container. */ this.actionManagers = new Array(); /** * Sounds populated in the container. */ this.sounds = new Array(); /** * Textures populated in the container. */ this.textures = new Array(); /** * Effect layers populated in the container. */ this.effectLayers = new Array(); this.scene = scene; } /** * Adds all the assets from the container to the scene. */ AssetContainer.prototype.addAllToScene = function () { var _this = this; this.cameras.forEach(function (o) { _this.scene.addCamera(o); }); this.lights.forEach(function (o) { _this.scene.addLight(o); }); this.meshes.forEach(function (o) { _this.scene.addMesh(o); }); this.skeletons.forEach(function (o) { _this.scene.addSkeleton(o); }); this.particleSystems.forEach(function (o) { _this.scene.addParticleSystem(o); }); this.animations.forEach(function (o) { _this.scene.addAnimation(o); }); this.animationGroups.forEach(function (o) { _this.scene.addAnimationGroup(o); }); this.multiMaterials.forEach(function (o) { _this.scene.addMultiMaterial(o); }); this.materials.forEach(function (o) { _this.scene.addMaterial(o); }); this.morphTargetManagers.forEach(function (o) { _this.scene.addMorphTargetManager(o); }); this.geometries.forEach(function (o) { _this.scene.addGeometry(o); }); this.transformNodes.forEach(function (o) { _this.scene.addTransformNode(o); }); this.lensFlareSystems.forEach(function (o) { _this.scene.addLensFlareSystem(o); }); this.actionManagers.forEach(function (o) { _this.scene.addActionManager(o); }); this.sounds.forEach(function (o) { o.play(); o.autoplay = true; _this.scene.mainSoundTrack.AddSound(o); }); this.textures.forEach(function (o) { _this.scene.addTexture(o); }); this.effectLayers.forEach(function (o) { _this.scene.addEffectLayer(o); }); }; /** * Removes all the assets in the container from the scene */ AssetContainer.prototype.removeAllFromScene = function () { var _this = this; this.cameras.forEach(function (o) { _this.scene.removeCamera(o); }); this.lights.forEach(function (o) { _this.scene.removeLight(o); }); this.meshes.forEach(function (o) { _this.scene.removeMesh(o); }); this.skeletons.forEach(function (o) { _this.scene.removeSkeleton(o); }); this.particleSystems.forEach(function (o) { _this.scene.removeParticleSystem(o); }); this.animations.forEach(function (o) { _this.scene.removeAnimation(o); }); this.animationGroups.forEach(function (o) { _this.scene.removeAnimationGroup(o); }); this.multiMaterials.forEach(function (o) { _this.scene.removeMultiMaterial(o); }); this.materials.forEach(function (o) { _this.scene.removeMaterial(o); }); this.morphTargetManagers.forEach(function (o) { _this.scene.removeMorphTargetManager(o); }); this.geometries.forEach(function (o) { _this.scene.removeGeometry(o); }); this.transformNodes.forEach(function (o) { _this.scene.removeTransformNode(o); }); this.lensFlareSystems.forEach(function (o) { _this.scene.removeLensFlareSystem(o); }); this.actionManagers.forEach(function (o) { _this.scene.removeActionManager(o); }); this.sounds.forEach(function (o) { o.stop(); o.autoplay = false; _this.scene.mainSoundTrack.RemoveSound(o); }); this.textures.forEach(function (o) { _this.scene.removeTexture(o); }); this.effectLayers.forEach(function (o) { _this.scene.removeEffectLayer(o); }); }; AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) { for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) { var asset = sourceAssets_1[_i]; var move = true; for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) { var keepAsset = keepAssets_1[_a]; if (asset === keepAsset) { move = false; break; } } if (move) { targetAssets.push(asset); } } }; /** * Removes all the assets contained in the scene and adds them to the container. * @param keepAssets Set of assets to keep in the scene. (default: empty) */ AssetContainer.prototype.moveAllFromScene = function (keepAssets) { if (keepAssets === undefined) { keepAssets = new KeepAssets(); } this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras); this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes); this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries); this._moveAssets(this.scene.materials, this.materials, keepAssets.materials); this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers); this._moveAssets(this.scene.animations, this.animations, keepAssets.animations); this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups); this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems); this._moveAssets(this.scene.lights, this.lights, keepAssets.lights); this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers); this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials); this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons); this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems); this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds); this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes); this._moveAssets(this.scene.textures, this.textures, keepAssets.textures); this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers); this.removeAllFromScene(); }; /** * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer. * @returns the root mesh */ AssetContainer.prototype.createRootMesh = function () { var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene); this.meshes.forEach(function (m) { if (!m.parent) { rootMesh.addChild(m); } }); this.meshes.unshift(rootMesh); return rootMesh; }; return AssetContainer; }()); BABYLON.AssetContainer = AssetContainer; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.assetContainer.js.map var BABYLON; (function (BABYLON) { var Buffer = /** @class */ (function () { /** * Constructor * @param engine the engine * @param data the data to use for this buffer * @param updatable whether the data is updatable * @param stride the stride (optional) * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional) * @param instanced whether the buffer is instanced (optional) * @param useBytes set to true if the stride in in bytes (optional) */ function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) { if (stride === void 0) { stride = 0; } if (postponeInternalCreation === void 0) { postponeInternalCreation = false; } if (instanced === void 0) { instanced = false; } if (useBytes === void 0) { useBytes = false; } if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine' this._engine = engine.getScene().getEngine(); } else { this._engine = engine; } this._updatable = updatable; this._instanced = instanced; this._data = data; this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT; if (!postponeInternalCreation) { // by default this.create(); } } /** * Create a new {BABYLON.VertexBuffer} based on the current buffer * @param kind defines the vertex buffer kind (position, normal, etc.) * @param offset defines offset in the buffer (0 by default) * @param size defines the size in floats of attributes (position is 3 for instance) * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved) * @param instanced defines if the vertex buffer contains indexed data * @param useBytes defines if the offset and stride are in bytes * @returns the new vertex buffer */ Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) { if (useBytes === void 0) { useBytes = false; } var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT; var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride; // a lot of these parameters are ignored as they are overriden by the buffer return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true); }; // Properties Buffer.prototype.isUpdatable = function () { return this._updatable; }; Buffer.prototype.getData = function () { return this._data; }; Buffer.prototype.getBuffer = function () { return this._buffer; }; /** * Gets the stride in float32 units (i.e. byte stride / 4). * May not be an integer if the byte stride is not divisible by 4. * DEPRECATED. Use byteStride instead. * @returns the stride in float32 units */ Buffer.prototype.getStrideSize = function () { return this.byteStride / Float32Array.BYTES_PER_ELEMENT; }; // Methods Buffer.prototype.create = function (data) { if (data === void 0) { data = null; } if (!data && this._buffer) { return; // nothing to do } data = data || this._data; if (!data) { return; } if (!this._buffer) { // create buffer if (this._updatable) { this._buffer = this._engine.createDynamicVertexBuffer(data); this._data = data; } else { this._buffer = this._engine.createVertexBuffer(data); } } else if (this._updatable) { // update buffer this._engine.updateDynamicVertexBuffer(this._buffer, data); this._data = data; } }; Buffer.prototype._rebuild = function () { this._buffer = null; this.create(this._data); }; Buffer.prototype.update = function (data) { this.create(data); }; /** * Updates the data directly. * @param data the new data * @param offset the new offset * @param vertexCount the vertex count (optional) * @param useBytes set to true if the offset is in bytes */ Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) { if (useBytes === void 0) { useBytes = false; } if (!this._buffer) { return; } if (this._updatable) { // update buffer this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined)); this._data = null; } }; Buffer.prototype.dispose = function () { if (!this._buffer) { return; } if (this._engine._releaseBuffer(this._buffer)) { this._buffer = null; } }; return Buffer; }()); BABYLON.Buffer = Buffer; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.buffer.js.map var BABYLON; (function (BABYLON) { var VertexBuffer = /** @class */ (function () { /** * Constructor * @param engine the engine * @param data the data to use for this vertex buffer * @param kind the vertex buffer kind * @param updatable whether the data is updatable * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional) * @param stride the stride (optional) * @param instanced whether the buffer is instanced (optional) * @param offset the offset of the data (optional) * @param size the number of components (optional) * @param type the type of the component (optional) * @param normalized whether the data contains normalized data (optional) * @param useBytes set to true if stride and offset are in bytes (optional) */ function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) { if (normalized === void 0) { normalized = false; } if (useBytes === void 0) { useBytes = false; } if (data instanceof BABYLON.Buffer) { this._buffer = data; this._ownsBuffer = false; } else { this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes); this._ownsBuffer = true; } this._kind = kind; if (type == undefined) { var data_1 = this.getData(); this.type = VertexBuffer.FLOAT; if (data_1 instanceof Int8Array) this.type = VertexBuffer.BYTE; else if (data_1 instanceof Uint8Array) this.type = VertexBuffer.UNSIGNED_BYTE; else if (data_1 instanceof Int16Array) this.type = VertexBuffer.SHORT; else if (data_1 instanceof Uint16Array) this.type = VertexBuffer.UNSIGNED_SHORT; else if (data_1 instanceof Int32Array) this.type = VertexBuffer.INT; else if (data_1 instanceof Uint32Array) this.type = VertexBuffer.UNSIGNED_INT; } else { this.type = type; } var typeByteLength = VertexBuffer.GetTypeByteLength(this.type); if (useBytes) { this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind)); this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength); this.byteOffset = offset || 0; } else { this._size = size || stride || VertexBuffer.DeduceStride(kind); this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength)); this.byteOffset = (offset || 0) * typeByteLength; } this.normalized = normalized; this._instanced = instanced !== undefined ? instanced : false; this._instanceDivisor = instanced ? 1 : 0; } Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", { /** * Gets or sets the instance divisor when in instanced mode */ get: function () { return this._instanceDivisor; }, set: function (value) { this._instanceDivisor = value; if (value == 0) { this._instanced = false; } else { this._instanced = true; } }, enumerable: true, configurable: true }); VertexBuffer.prototype._rebuild = function () { if (!this._buffer) { return; } this._buffer._rebuild(); }; /** * Returns the kind of the VertexBuffer (string). */ VertexBuffer.prototype.getKind = function () { return this._kind; }; // Properties /** * Boolean : is the VertexBuffer updatable ? */ VertexBuffer.prototype.isUpdatable = function () { return this._buffer.isUpdatable(); }; /** * Returns an array of numbers or a typed array containing the VertexBuffer data. */ VertexBuffer.prototype.getData = function () { return this._buffer.getData(); }; /** * Returns the WebGLBuffer associated to the VertexBuffer. */ VertexBuffer.prototype.getBuffer = function () { return this._buffer.getBuffer(); }; /** * Returns the stride as a multiple of the type byte length. * DEPRECATED. Use byteStride instead. */ VertexBuffer.prototype.getStrideSize = function () { return this.byteStride / VertexBuffer.GetTypeByteLength(this.type); }; /** * Returns the offset as a multiple of the type byte length. * DEPRECATED. Use byteOffset instead. */ VertexBuffer.prototype.getOffset = function () { return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type); }; /** * Returns the number of components per vertex attribute (integer). */ VertexBuffer.prototype.getSize = function () { return this._size; }; /** * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ? */ VertexBuffer.prototype.getIsInstanced = function () { return this._instanced; }; /** * Returns the instancing divisor, zero for non-instanced (integer). */ VertexBuffer.prototype.getInstanceDivisor = function () { return this._instanceDivisor; }; // Methods /** * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array. * Returns the created WebGLBuffer. */ VertexBuffer.prototype.create = function (data) { return this._buffer.create(data); }; /** * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array. * This function will create a new buffer if the current one is not updatable * Returns the updated WebGLBuffer. */ VertexBuffer.prototype.update = function (data) { return this._buffer.update(data); }; /** * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array. * Returns the directly updated WebGLBuffer. * @param data the new data * @param offset the new offset * @param useBytes set to true if the offset is in bytes */ VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) { if (useBytes === void 0) { useBytes = false; } this._buffer.updateDirectly(data, offset, undefined, useBytes); }; /** * Disposes the VertexBuffer and the underlying WebGLBuffer. */ VertexBuffer.prototype.dispose = function () { if (this._ownsBuffer) { this._buffer.dispose(); } }; /** * Enumerates each value of this vertex buffer as numbers. * @param count the number of values to enumerate * @param callback the callback function called for each value */ VertexBuffer.prototype.forEach = function (count, callback) { VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback); }; Object.defineProperty(VertexBuffer, "PositionKind", { get: function () { return VertexBuffer._PositionKind; }, enumerable: true, configurable: true }); Object.defineProperty(VertexBuffer, "NormalKind", { get: function () { return VertexBuffer._NormalKind; }, enumerable: true, configurable: true }); Object.defineProperty(VertexBuffer, "TangentKind", { get: function () { return VertexBuffer._TangentKind; }, enumerable: true, configurable: true }); Object.defineProperty(VertexBuffer, "UVKind", { get: function () { return VertexBuffer._UVKind; }, enumerable: true, configurable: true }); Object.defineProperty(VertexBuffer, "UV2Kind", { get: function () { return VertexBuffer._UV2Kind; }, enumerable: true, configurable: true }); Object.defineProperty(VertexBuffer, "UV3Kind", { get: function () { return VertexBuffer._UV3Kind; }, enumerable: true, configurable: true }); Object.defineProperty(VertexBuffer, "UV4Kind", { get: function () { return VertexBuffer._UV4Kind; }, enumerable: true, configurable: true }); Object.defineProperty(VertexBuffer, "UV5Kind", { get: function () { return VertexBuffer._UV5Kind; }, enumerable: true, configurable: true }); Object.defineProperty(VertexBuffer, "UV6Kind", { get: function () { return VertexBuffer._UV6Kind; }, enumerable: true, configurable: true }); Object.defineProperty(VertexBuffer, "ColorKind", { get: function () { return VertexBuffer._ColorKind; }, enumerable: true, configurable: true }); Object.defineProperty(VertexBuffer, "MatricesIndicesKind", { get: function () { return VertexBuffer._MatricesIndicesKind; }, enumerable: true, configurable: true }); Object.defineProperty(VertexBuffer, "MatricesWeightsKind", { get: function () { return VertexBuffer._MatricesWeightsKind; }, enumerable: true, configurable: true }); Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", { get: function () { return VertexBuffer._MatricesIndicesExtraKind; }, enumerable: true, configurable: true }); Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", { get: function () { return VertexBuffer._MatricesWeightsExtraKind; }, enumerable: true, configurable: true }); /** * Deduces the stride given a kind. * @param kind The kind string to deduce * @returns The deduced stride */ VertexBuffer.DeduceStride = function (kind) { switch (kind) { case VertexBuffer.UVKind: case VertexBuffer.UV2Kind: case VertexBuffer.UV3Kind: case VertexBuffer.UV4Kind: case VertexBuffer.UV5Kind: case VertexBuffer.UV6Kind: return 2; case VertexBuffer.NormalKind: case VertexBuffer.PositionKind: return 3; case VertexBuffer.ColorKind: case VertexBuffer.MatricesIndicesKind: case VertexBuffer.MatricesIndicesExtraKind: case VertexBuffer.MatricesWeightsKind: case VertexBuffer.MatricesWeightsExtraKind: case VertexBuffer.TangentKind: return 4; default: throw new Error("Invalid kind '" + kind + "'"); } }; /** * Gets the byte length of the given type. * @param type the type * @returns the number of bytes */ VertexBuffer.GetTypeByteLength = function (type) { switch (type) { case VertexBuffer.BYTE: case VertexBuffer.UNSIGNED_BYTE: return 1; case VertexBuffer.SHORT: case VertexBuffer.UNSIGNED_SHORT: return 2; case VertexBuffer.INT: case VertexBuffer.FLOAT: return 4; default: throw new Error("Invalid type '" + type + "'"); } }; /** * Enumerates each value of the given parameters as numbers. * @param data the data to enumerate * @param byteOffset the byte offset of the data * @param byteStride the byte stride of the data * @param componentCount the number of components per element * @param componentType the type of the component * @param count the total number of components * @param normalized whether the data is normalized * @param callback the callback function called for each value */ VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) { if (data instanceof Array) { var offset = byteOffset / 4; var stride = byteStride / 4; for (var index = 0; index < count; index += componentCount) { for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) { callback(data[offset + componentIndex], index + componentIndex); } offset += stride; } } else { var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength); var componentByteLength = VertexBuffer.GetTypeByteLength(componentType); for (var index = 0; index < count; index += componentCount) { var componentByteOffset = byteOffset; for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) { var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized); callback(value, index + componentIndex); componentByteOffset += componentByteLength; } byteOffset += byteStride; } } }; VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) { switch (type) { case VertexBuffer.BYTE: { var value = dataView.getInt8(byteOffset); if (normalized) { value = Math.max(value / 127, -1); } return value; } case VertexBuffer.UNSIGNED_BYTE: { var value = dataView.getUint8(byteOffset); if (normalized) { value = value / 255; } return value; } case VertexBuffer.SHORT: { var value = dataView.getInt16(byteOffset, true); if (normalized) { value = Math.max(value / 16383, -1); } return value; } case VertexBuffer.UNSIGNED_SHORT: { var value = dataView.getUint16(byteOffset, true); if (normalized) { value = value / 65535; } return value; } case VertexBuffer.FLOAT: { return dataView.getFloat32(byteOffset, true); } default: { throw new Error("Invalid component type " + type); } } }; /** * The byte type. */ VertexBuffer.BYTE = 5120; /** * The unsigned byte type. */ VertexBuffer.UNSIGNED_BYTE = 5121; /** * The short type. */ VertexBuffer.SHORT = 5122; /** * The unsigned short type. */ VertexBuffer.UNSIGNED_SHORT = 5123; /** * The integer type. */ VertexBuffer.INT = 5124; /** * The unsigned integer type. */ VertexBuffer.UNSIGNED_INT = 5125; /** * The float type. */ VertexBuffer.FLOAT = 5126; // Enums VertexBuffer._PositionKind = "position"; VertexBuffer._NormalKind = "normal"; VertexBuffer._TangentKind = "tangent"; VertexBuffer._UVKind = "uv"; VertexBuffer._UV2Kind = "uv2"; VertexBuffer._UV3Kind = "uv3"; VertexBuffer._UV4Kind = "uv4"; VertexBuffer._UV5Kind = "uv5"; VertexBuffer._UV6Kind = "uv6"; VertexBuffer._ColorKind = "color"; VertexBuffer._MatricesIndicesKind = "matricesIndices"; VertexBuffer._MatricesWeightsKind = "matricesWeights"; VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra"; VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra"; return VertexBuffer; }()); BABYLON.VertexBuffer = VertexBuffer; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.vertexBuffer.js.map var BABYLON; (function (BABYLON) { /** * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context */ var DummyInternalTextureTracker = /** @class */ (function () { function DummyInternalTextureTracker() { /** * Gets or set the previous tracker in the list */ this.previous = null; /** * Gets or set the next tracker in the list */ this.next = null; } return DummyInternalTextureTracker; }()); BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.internalTextureTracker.js.map var BABYLON; (function (BABYLON) { /** * 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 */ function InternalTexture(engine, dataSource) { /** * Observable called when the texture is loaded */ this.onLoadedObservable = new BABYLON.Observable(); /** * Gets or set the previous tracker in the list */ this.previous = null; /** * Gets or set the next tracker in the list */ this.next = null; // Private /** @hidden */ this._initialSlot = -1; /** @hidden */ this._designatedSlot = -1; /** @hidden */ this._dataSource = InternalTexture.DATASOURCE_UNKNOWN; /** @hidden */ this._comparisonFunction = 0; /** @hidden */ this._isRGBD = false; /** @hidden */ this._references = 1; this._engine = engine; this._dataSource = dataSource; 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 BABYLON.InternalTexture.DATASOURCE_XXXX) */ get: function () { return this._dataSource; }, enumerable: true, configurable: true }); /** * Increments the number of references (ie. the number of {BABYLON.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 () { _this.isReady = true; }, null, this._buffer, undefined, this.format); proxy._swapAndDie(this); 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); // 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 BABYLON.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 !== BABYLON.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 () { _this.isReady = true; }, null, this.format, this._extension); proxy._swapAndDie(this); 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_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; } }; InternalTexture.prototype._swapAndDie = function (target) { target._webGLTexture = this._webGLTexture; 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; this.previous = null; this.next = null; } }; /** * 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; return InternalTexture; }()); BABYLON.InternalTexture = InternalTexture; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.internalTexture.js.map var BABYLON; (function (BABYLON) { var BaseTexture = /** @class */ (function () { function BaseTexture(scene) { this._hasAlpha = false; this.getAlphaFromRGB = false; this.level = 1; this.coordinatesIndex = 0; this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE; /** * | Value | Type | Description | * | ----- | ------------------ | ----------- | * | 0 | CLAMP_ADDRESSMODE | | * | 1 | WRAP_ADDRESSMODE | | * | 2 | MIRROR_ADDRESSMODE | | */ this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE; /** * | Value | Type | Description | * | ----- | ------------------ | ----------- | * | 0 | CLAMP_ADDRESSMODE | | * | 1 | WRAP_ADDRESSMODE | | * | 2 | MIRROR_ADDRESSMODE | | */ this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE; /** * | Value | Type | Description | * | ----- | ------------------ | ----------- | * | 0 | CLAMP_ADDRESSMODE | | * | 1 | WRAP_ADDRESSMODE | | * | 2 | MIRROR_ADDRESSMODE | | */ this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE; this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL; this.isCube = false; this.is3D = false; this.gammaSpace = true; this.invertZ = false; this.lodLevelInAlpha = false; this.isRenderTarget = false; this.animations = new Array(); /** * An event triggered when the texture is disposed. */ this.onDisposeObservable = new BABYLON.Observable(); this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE; this._scene = scene || BABYLON.Engine.LastCreatedScene; if (this._scene) { this._scene.textures.push(this); } this._uid = null; } Object.defineProperty(BaseTexture.prototype, "hasAlpha", { get: function () { return this._hasAlpha; }, set: function (value) { if (this._hasAlpha === value) { return; } this._hasAlpha = value; if (this._scene) { this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.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(BABYLON.Material.TextureDirtyFlag); } }, 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, "lodGenerationOffset", { 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", { 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", { get: function () { if (!this._uid) { this._uid = BABYLON.Tools.RandomId(); } return this._uid; }, enumerable: true, configurable: true }); BaseTexture.prototype.toString = function () { return this.name; }; BaseTexture.prototype.getClassName = function () { return "BaseTexture"; }; Object.defineProperty(BaseTexture.prototype, "onDispose", { 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", { get: function () { return true; }, enumerable: true, configurable: true }); BaseTexture.prototype.getScene = function () { return this._scene; }; BaseTexture.prototype.getTextureMatrix = function () { return BABYLON.Matrix.IdentityReadOnly; }; BaseTexture.prototype.getReflectionTextureMatrix = function () { return BABYLON.Matrix.IdentityReadOnly; }; BaseTexture.prototype.getInternalTexture = function () { return this._texture; }; BaseTexture.prototype.isReadyOrNotBlocking = function () { return !this.isBlocking || this.isReady(); }; BaseTexture.prototype.isReady = function () { if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) { this.delayLoad(); return false; } if (this._texture) { return this._texture.isReady; } return false; }; BaseTexture.prototype.getSize = function () { if (this._texture && this._texture.width) { return new BABYLON.Size(this._texture.width, this._texture.height); } if (this._texture && this._texture._size) { return new BABYLON.Size(this._texture._size, this._texture._size); } return BABYLON.Size.Zero(); }; BaseTexture.prototype.getBaseSize = function () { if (!this.isReady() || !this._texture) return BABYLON.Size.Zero(); if (this._texture._size) { return new BABYLON.Size(this._texture._size, this._texture._size); } return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight); }; BaseTexture.prototype.scale = function (ratio) { }; Object.defineProperty(BaseTexture.prototype, "canRescale", { get: function () { return false; }, enumerable: true, configurable: true }); BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) { if (!this._scene) { return null; } var texturesCache = this._scene.getEngine().getLoadedTexturesCache(); for (var index = 0; index < texturesCache.length; index++) { var texturesCacheEntry = texturesCache[index]; if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) { if (!sampling || sampling === texturesCacheEntry.samplingMode) { texturesCacheEntry.incrementReferences(); return texturesCacheEntry; } } } return null; }; BaseTexture.prototype._rebuild = function () { }; BaseTexture.prototype.delayLoad = function () { }; BaseTexture.prototype.clone = function () { return null; }; Object.defineProperty(BaseTexture.prototype, "textureType", { get: function () { if (!this._texture) { return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; } return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }, enumerable: true, configurable: true }); Object.defineProperty(BaseTexture.prototype, "textureFormat", { get: function () { if (!this._texture) { return BABYLON.Engine.TEXTUREFORMAT_RGBA; } return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.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 The face of the texture to read (in case of cube texture) * @param level The LOD level of the texture to read (in case of Mip Maps) * @returns The Array buffer containing the pixels data. */ BaseTexture.prototype.readPixels = function (faceIndex, level) { if (faceIndex === void 0) { faceIndex = 0; } if (level === void 0) { level = 0; } 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); } return engine._readTexturePixels(this._texture, width, height, -1, level); }; BaseTexture.prototype.releaseInternalTexture = function () { if (this._texture) { this._texture.dispose(); this._texture = null; } }; Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", { get: function () { if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) { return null; } if (!this._texture._sphericalPolynomial) { this._texture._sphericalPolynomial = BABYLON.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", { get: function () { if (this._texture) { return this._texture._lodTextureHigh; } return null; }, enumerable: true, configurable: true }); Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", { get: function () { if (this._texture) { return this._texture._lodTextureMid; } return null; }, enumerable: true, configurable: true }); Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", { get: function () { if (this._texture) { return this._texture._lodTextureLow; } return null; }, enumerable: true, configurable: true }); 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); } if (this._texture === undefined) { return; } // Release this.releaseInternalTexture(); // Callback this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); }; BaseTexture.prototype.serialize = function () { if (!this.name) { return null; } var serializationObject = BABYLON.SerializationHelper.Serialize(this); // Animations BABYLON.Animation.AppendSerializedAnimations(this, serializationObject); return serializationObject; }; 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(); } }; BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4; __decorate([ BABYLON.serialize() ], BaseTexture.prototype, "name", void 0); __decorate([ BABYLON.serialize("hasAlpha") ], BaseTexture.prototype, "_hasAlpha", void 0); __decorate([ BABYLON.serialize() ], BaseTexture.prototype, "getAlphaFromRGB", void 0); __decorate([ BABYLON.serialize() ], BaseTexture.prototype, "level", void 0); __decorate([ BABYLON.serialize() ], BaseTexture.prototype, "coordinatesIndex", void 0); __decorate([ BABYLON.serialize("coordinatesMode") ], BaseTexture.prototype, "_coordinatesMode", void 0); __decorate([ BABYLON.serialize() ], BaseTexture.prototype, "wrapU", void 0); __decorate([ BABYLON.serialize() ], BaseTexture.prototype, "wrapV", void 0); __decorate([ BABYLON.serialize() ], BaseTexture.prototype, "wrapR", void 0); __decorate([ BABYLON.serialize() ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0); __decorate([ BABYLON.serialize() ], BaseTexture.prototype, "isCube", void 0); __decorate([ BABYLON.serialize() ], BaseTexture.prototype, "is3D", void 0); __decorate([ BABYLON.serialize() ], BaseTexture.prototype, "gammaSpace", void 0); __decorate([ BABYLON.serialize() ], BaseTexture.prototype, "invertZ", void 0); __decorate([ BABYLON.serialize() ], BaseTexture.prototype, "lodLevelInAlpha", void 0); __decorate([ BABYLON.serialize() ], BaseTexture.prototype, "lodGenerationOffset", null); __decorate([ BABYLON.serialize() ], BaseTexture.prototype, "lodGenerationScale", null); __decorate([ BABYLON.serialize() ], BaseTexture.prototype, "isRenderTarget", void 0); return BaseTexture; }()); BABYLON.BaseTexture = BaseTexture; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.baseTexture.js.map var BABYLON; (function (BABYLON) { var Texture = /** @class */ (function (_super) { __extends(Texture, _super); 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; _this.uOffset = 0; _this.vOffset = 0; _this.uScale = 1.0; _this.vScale = 1.0; _this.uAng = 0; _this.vAng = 0; _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; _this._isBlocking = true; _this.name = url || ""; _this.url = url; _this._noMipmap = noMipmap; _this._invertY = invertY; _this._samplingMode = 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._onLoadObservable && _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); if (!_this._texture) { if (!scene.useDelayedTextureLoading) { _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format); if (deleteBuffer) { delete _this._buffer; } } else { _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED; _this._delayedOnLoad = load; _this._delayedOnError = onError; } } else { if (_this._texture.isReady) { BABYLON.Tools.SetImmediate(function () { return load(); }); } else { _this._texture.onLoadedObservable.add(load); } } return _this; } Object.defineProperty(Texture.prototype, "noMipmap", { get: function () { return this._noMipmap; }, enumerable: true, configurable: true }); Object.defineProperty(Texture.prototype, "isBlocking", { get: function () { return this._isBlocking; }, set: function (value) { this._isBlocking = value; }, enumerable: true, configurable: true }); Object.defineProperty(Texture.prototype, "samplingMode", { get: function () { return this._samplingMode; }, 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) */ Texture.prototype.updateURL = function (url, buffer) { if (buffer === void 0) { buffer = null; } if (this.url) { throw new Error("URL is already set"); } this.url = url; this._buffer = buffer; this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED; this.delayLoad(); }; Texture.prototype.delayLoad = function () { if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) { return; } var scene = this.getScene(); if (!scene) { return; } this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED; this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode); 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) { BABYLON.Tools.SetImmediate(this._delayedOnLoad); } else { this._texture.onLoadedObservable.add(this._delayedOnLoad); } } } this._delayedOnLoad = null; this._delayedOnError = null; }; Texture.prototype.updateSamplingMode = function (samplingMode) { if (!this._texture) { return; } var scene = this.getScene(); if (!scene) { return; } this._samplingMode = samplingMode; scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture); }; 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; BABYLON.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; }; 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 = BABYLON.Matrix.Zero(); this._rowGenerationMatrix = new BABYLON.Matrix(); this._t0 = BABYLON.Vector3.Zero(); this._t1 = BABYLON.Vector3.Zero(); this._t2 = BABYLON.Vector3.Zero(); } BABYLON.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); BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix); this._cachedTextureMatrix.m[0] = this._t1.x; this._cachedTextureMatrix.m[1] = this._t1.y; this._cachedTextureMatrix.m[2] = this._t1.z; this._cachedTextureMatrix.m[4] = this._t2.x; this._cachedTextureMatrix.m[5] = this._t2.y; this._cachedTextureMatrix.m[6] = this._t2.z; this._cachedTextureMatrix.m[8] = this._t0.x; this._cachedTextureMatrix.m[9] = this._t0.y; this._cachedTextureMatrix.m[10] = this._t0.z; var scene = this.getScene(); if (!scene) { return this._cachedTextureMatrix; } scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) { return mat.hasTexture(_this); }); return this._cachedTextureMatrix; }; 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 = BABYLON.Matrix.Zero(); } if (!this._projectionModeMatrix) { this._projectionModeMatrix = BABYLON.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: BABYLON.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: BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix); this._projectionModeMatrix.m[0] = 0.5; this._projectionModeMatrix.m[5] = -0.5; this._projectionModeMatrix.m[10] = 0.0; this._projectionModeMatrix.m[12] = 0.5; this._projectionModeMatrix.m[13] = 0.5; this._projectionModeMatrix.m[14] = 1.0; this._projectionModeMatrix.m[15] = 1.0; var projectionMatrix = scene.getProjectionMatrix(); this._cachedProjectionMatrixId = projectionMatrix.updateFlag; projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix); break; default: BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix); break; } scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) { return (mat.getActiveTextures().indexOf(_this) !== -1); }); return this._cachedTextureMatrix; }; Texture.prototype.clone = function () { var _this = this; return BABYLON.SerializationHelper.Clone(function () { return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode); }, this); }; Object.defineProperty(Texture.prototype, "onLoadObservable", { get: function () { if (!this._onLoadObservable) { this._onLoadObservable = new BABYLON.Observable(); } return this._onLoadObservable; }, enumerable: true, configurable: true }); 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; }; Texture.prototype.getClassName = function () { return "Texture"; }; Texture.prototype.dispose = function () { _super.prototype.dispose.call(this); if (this.onLoadObservable) { this.onLoadObservable.clear(); this._onLoadObservable = null; } this._delayedOnLoad = null; this._delayedOnError = null; }; // Statics 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 = BABYLON.Engine.TEXTUREFORMAT_RGBA; } return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format); }; Texture.Parse = function (parsedTexture, scene, rootUrl) { if (parsedTexture.customType) { var customTexture = BABYLON.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) { return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl); } if (!parsedTexture.name && !parsedTexture.isRenderTarget) { return null; } var texture = BABYLON.SerializationHelper.Parse(function () { var generateMipMaps = true; if (parsedTexture.noMipmap) { generateMipMaps = false; } if (parsedTexture.mirrorPlane) { var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps); mirrorTexture._waitingRenderList = parsedTexture.renderList; mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane); return mirrorTexture; } else if (parsedTexture.isRenderTarget) { var renderTargetTexture = new BABYLON.RenderTargetTexture(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._samplingMode !== sampling) { texture.updateSamplingMode(sampling); } } // Animations if (parsedTexture.animations) { for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) { var parsedAnimation = parsedTexture.animations[animationIndex]; texture.animations.push(BABYLON.Animation.Parse(parsedAnimation)); } } return 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 = BABYLON.Engine.TEXTUREFORMAT_RGBA; } if (name.substr(0, 5) !== "data:") { name = "data:" + name; } return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format); }; // Constants Texture.NEAREST_SAMPLINGMODE = 1; Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear Texture.BILINEAR_SAMPLINGMODE = 2; Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest Texture.TRILINEAR_SAMPLINGMODE = 3; Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear Texture.NEAREST_NEAREST_MIPNEAREST = 4; Texture.NEAREST_LINEAR_MIPNEAREST = 5; Texture.NEAREST_LINEAR_MIPLINEAR = 6; Texture.NEAREST_LINEAR = 7; Texture.NEAREST_NEAREST = 8; Texture.LINEAR_NEAREST_MIPNEAREST = 9; Texture.LINEAR_NEAREST_MIPLINEAR = 10; Texture.LINEAR_LINEAR = 11; Texture.LINEAR_NEAREST = 12; Texture.EXPLICIT_MODE = 0; Texture.SPHERICAL_MODE = 1; Texture.PLANAR_MODE = 2; Texture.CUBIC_MODE = 3; Texture.PROJECTION_MODE = 4; Texture.SKYBOX_MODE = 5; Texture.INVCUBIC_MODE = 6; Texture.EQUIRECTANGULAR_MODE = 7; Texture.FIXED_EQUIRECTANGULAR_MODE = 8; Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9; Texture.CLAMP_ADDRESSMODE = 0; Texture.WRAP_ADDRESSMODE = 1; Texture.MIRROR_ADDRESSMODE = 2; /** * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file */ Texture.UseSerializedUrlIfAny = false; __decorate([ BABYLON.serialize() ], Texture.prototype, "url", void 0); __decorate([ BABYLON.serialize() ], Texture.prototype, "uOffset", void 0); __decorate([ BABYLON.serialize() ], Texture.prototype, "vOffset", void 0); __decorate([ BABYLON.serialize() ], Texture.prototype, "uScale", void 0); __decorate([ BABYLON.serialize() ], Texture.prototype, "vScale", void 0); __decorate([ BABYLON.serialize() ], Texture.prototype, "uAng", void 0); __decorate([ BABYLON.serialize() ], Texture.prototype, "vAng", void 0); __decorate([ BABYLON.serialize() ], Texture.prototype, "wAng", void 0); __decorate([ BABYLON.serialize() ], Texture.prototype, "uRotationCenter", void 0); __decorate([ BABYLON.serialize() ], Texture.prototype, "vRotationCenter", void 0); __decorate([ BABYLON.serialize() ], Texture.prototype, "wRotationCenter", void 0); __decorate([ BABYLON.serialize() ], Texture.prototype, "isBlocking", null); return Texture; }(BABYLON.BaseTexture)); BABYLON.Texture = Texture; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.texture.js.map var BABYLON; (function (BABYLON) { /** * @hidden **/ var _InstancesBatch = /** @class */ (function () { function _InstancesBatch() { this.mustReturn = false; this.visibleInstances = new Array(); this.renderSelf = new Array(); } return _InstancesBatch; }()); BABYLON._InstancesBatch = _InstancesBatch; var Mesh = /** @class */ (function (_super) { __extends(Mesh, _super); /** * @constructor * @param {string} name The value used by scene.getMeshByName() to do a lookup. * @param {Scene} scene The scene to add this mesh to. * @param {Node} parent The parent of this mesh, if it has one * @param {Mesh} source An optional Mesh from which geometry is shared, cloned. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False. * When false, achieved by calling a clone(), also passing False. * This will make creation of children, recursive. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True. */ function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) { if (scene === void 0) { scene = null; } if (parent === void 0) { parent = null; } if (source === void 0) { source = null; } if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; } var _this = _super.call(this, name, scene) || this; // Events /** * An event triggered before rendering the mesh */ _this.onBeforeRenderObservable = new BABYLON.Observable(); /** * An event triggered after rendering the mesh */ _this.onAfterRenderObservable = new BABYLON.Observable(); /** * An event triggered before drawing the mesh */ _this.onBeforeDrawObservable = new BABYLON.Observable(); // Members _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE; _this.instances = new Array(); _this._LODLevels = new Array(); _this._visibleInstances = {}; _this._renderIdForInstances = new Array(); _this._batchCache = new _InstancesBatch(); _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances // Use by builder only to know what orientation were the mesh build in. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE; _this.overrideMaterialSideOrientation = null; _this._areNormalsFrozen = false; // Will be used by ribbons mainly // Will be used to save a source mesh reference, If any _this._source = null; scene = _this.getScene(); if (source) { // Geometry if (source._geometry) { source._geometry.applyToMesh(_this); } // Deep copy BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]); // Source mesh _this._source = source; // Metadata if (source.metadata && source.metadata.clone) { _this.metadata = source.metadata.clone(); } else { _this.metadata = source.metadata; } // Tags if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) { BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true)); } // Parent _this.parent = source.parent; // Pivot _this.setPivotMatrix(source.getPivotMatrix()); _this.id = name + "." + source.id; // Material _this.material = source.material; var index; if (!doNotCloneChildren) { // Children var directDescendants = source.getDescendants(true); for (var index_1 = 0; index_1 < directDescendants.length; index_1++) { var child = directDescendants[index_1]; if (child.clone) { child.clone(name + "." + child.name, _this); } } } // Physics clone var physicsEngine = _this.getScene().getPhysicsEngine(); if (clonePhysicsImpostor && physicsEngine) { var impostor = physicsEngine.getImpostorForPhysicsObject(source); if (impostor) { _this.physicsImpostor = impostor.clone(_this); } } // Particles for (index = 0; index < scene.particleSystems.length; index++) { var system = scene.particleSystems[index]; if (system.emitter === source) { system.clone(system.name, _this); } } _this.computeWorldMatrix(true); } // Parent if (parent !== null) { _this.parent = parent; } return _this; } Object.defineProperty(Mesh, "FRONTSIDE", { /** * Mesh side orientation : usually the external or front surface */ get: function () { return Mesh._FRONTSIDE; }, enumerable: true, configurable: true }); Object.defineProperty(Mesh, "BACKSIDE", { /** * Mesh side orientation : usually the internal or back surface */ get: function () { return Mesh._BACKSIDE; }, enumerable: true, configurable: true }); Object.defineProperty(Mesh, "DOUBLESIDE", { /** * Mesh side orientation : both internal and external or front and back surfaces */ get: function () { return Mesh._DOUBLESIDE; }, enumerable: true, configurable: true }); Object.defineProperty(Mesh, "DEFAULTSIDE", { /** * Mesh side orientation : by default, `FRONTSIDE` */ get: function () { return Mesh._DEFAULTSIDE; }, enumerable: true, configurable: true }); Object.defineProperty(Mesh, "NO_CAP", { /** * Mesh cap setting : no cap */ get: function () { return Mesh._NO_CAP; }, enumerable: true, configurable: true }); Object.defineProperty(Mesh, "CAP_START", { /** * Mesh cap setting : one cap at the beginning of the mesh */ get: function () { return Mesh._CAP_START; }, enumerable: true, configurable: true }); Object.defineProperty(Mesh, "CAP_END", { /** * Mesh cap setting : one cap at the end of the mesh */ get: function () { return Mesh._CAP_END; }, enumerable: true, configurable: true }); Object.defineProperty(Mesh, "CAP_ALL", { /** * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh */ get: function () { return Mesh._CAP_ALL; }, enumerable: true, configurable: true }); Object.defineProperty(Mesh.prototype, "onBeforeDraw", { set: function (callback) { if (this._onBeforeDrawObserver) { this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver); } this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(Mesh.prototype, "morphTargetManager", { get: function () { return this._morphTargetManager; }, set: function (value) { if (this._morphTargetManager === value) { return; } this._morphTargetManager = value; this._syncGeometryWithMorphTargetManager(); }, enumerable: true, configurable: true }); Object.defineProperty(Mesh.prototype, "source", { get: function () { return this._source; }, enumerable: true, configurable: true }); Object.defineProperty(Mesh.prototype, "isUnIndexed", { get: function () { return this._unIndexed; }, set: function (value) { if (this._unIndexed !== value) { this._unIndexed = value; this._markSubMeshesAsAttributesDirty(); } }, enumerable: true, configurable: true }); // Methods /** * Returns the string "Mesh". */ Mesh.prototype.getClassName = function () { return "Mesh"; }; /** * Returns a string. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading */ Mesh.prototype.toString = function (fullDetails) { var ret = _super.prototype.toString.call(this, fullDetails); ret += ", n vertices: " + this.getTotalVertices(); ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE")); if (this.animations) { for (var i = 0; i < this.animations.length; i++) { ret += ", animation[0]: " + this.animations[i].toString(fullDetails); } } if (fullDetails) { if (this._geometry) { var ib = this.getIndices(); var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind); if (vb && ib) { ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO"); } } else { ret += ", flat shading: UNKNOWN"; } } return ret; }; Mesh.prototype._unBindEffect = function () { _super.prototype._unBindEffect.call(this); for (var _i = 0, _a = this.instances; _i < _a.length; _i++) { var instance = _a[_i]; instance._unBindEffect(); } }; Object.defineProperty(Mesh.prototype, "hasLODLevels", { /** * True if the mesh has some Levels Of Details (LOD). * Returns a boolean. */ get: function () { return this._LODLevels.length > 0; }, enumerable: true, configurable: true }); /** * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh * @returns an array of {BABYLON.MeshLODLevel} */ Mesh.prototype.getLODLevels = function () { return this._LODLevels; }; Mesh.prototype._sortLODLevels = function () { this._LODLevels.sort(function (a, b) { if (a.distance < b.distance) { return 1; } if (a.distance > b.distance) { return -1; } return 0; }); }; /** * Add a mesh as LOD level triggered at the given distance. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD * @param distance The distance from the center of the object to show this level * @param mesh The mesh to be added as LOD level (can be null) * @return This mesh (for chaining) */ Mesh.prototype.addLODLevel = function (distance, mesh) { if (mesh && mesh._masterMesh) { BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice"); return this; } var level = new BABYLON.MeshLODLevel(distance, mesh); this._LODLevels.push(level); if (mesh) { mesh._masterMesh = this; } this._sortLODLevels(); return this; }; /** * Returns the LOD level mesh at the passed distance or null if not found. * It is related to the method `addLODLevel(distance, mesh)`. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD * Returns an object Mesh or `null`. */ Mesh.prototype.getLODLevelAtDistance = function (distance) { for (var index = 0; index < this._LODLevels.length; index++) { var level = this._LODLevels[index]; if (level.distance === distance) { return level.mesh; } } return null; }; /** * Remove a mesh from the LOD array * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD * @param {Mesh} mesh The mesh to be removed. * @return {Mesh} This mesh (for chaining) */ Mesh.prototype.removeLODLevel = function (mesh) { for (var index = 0; index < this._LODLevels.length; index++) { if (this._LODLevels[index].mesh === mesh) { this._LODLevels.splice(index, 1); if (mesh) { mesh._masterMesh = null; } } } this._sortLODLevels(); return this; }; /** * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod */ Mesh.prototype.getLOD = function (camera, boundingSphere) { if (!this._LODLevels || this._LODLevels.length === 0) { return this; } var bSphere; if (boundingSphere) { bSphere = boundingSphere; } else { var boundingInfo = this.getBoundingInfo(); bSphere = boundingInfo.boundingSphere; } var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length(); if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) { if (this.onLODLevelSelection) { this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh); } return this; } for (var index = 0; index < this._LODLevels.length; index++) { var level = this._LODLevels[index]; if (level.distance < distanceToCamera) { if (level.mesh) { level.mesh._preActivate(); level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache); } if (this.onLODLevelSelection) { this.onLODLevelSelection(distanceToCamera, this, level.mesh); } return level.mesh; } } if (this.onLODLevelSelection) { this.onLODLevelSelection(distanceToCamera, this, this); } return this; }; Object.defineProperty(Mesh.prototype, "geometry", { /** * Returns the mesh internal Geometry object. */ get: function () { return this._geometry; }, enumerable: true, configurable: true }); /** * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry. */ Mesh.prototype.getTotalVertices = function () { if (this._geometry === null || this._geometry === undefined) { return 0; } return this._geometry.getTotalVertices(); }; /** * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc). * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one. * You can force the copy with forceCopy === true * Returns null if the mesh has no geometry or no vertex buffer. * Possible `kind` values : * - BABYLON.VertexBuffer.PositionKind * - BABYLON.VertexBuffer.UVKind * - BABYLON.VertexBuffer.UV2Kind * - BABYLON.VertexBuffer.UV3Kind * - BABYLON.VertexBuffer.UV4Kind * - BABYLON.VertexBuffer.UV5Kind * - BABYLON.VertexBuffer.UV6Kind * - BABYLON.VertexBuffer.ColorKind * - BABYLON.VertexBuffer.MatricesIndicesKind * - BABYLON.VertexBuffer.MatricesIndicesExtraKind * - BABYLON.VertexBuffer.MatricesWeightsKind * - BABYLON.VertexBuffer.MatricesWeightsExtraKind */ Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) { if (!this._geometry) { return null; } return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy); }; /** * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc. * Returns `null` if the mesh has no geometry. * Possible `kind` values : * - BABYLON.VertexBuffer.PositionKind * - BABYLON.VertexBuffer.UVKind * - BABYLON.VertexBuffer.UV2Kind * - BABYLON.VertexBuffer.UV3Kind * - BABYLON.VertexBuffer.UV4Kind * - BABYLON.VertexBuffer.UV5Kind * - BABYLON.VertexBuffer.UV6Kind * - BABYLON.VertexBuffer.ColorKind * - BABYLON.VertexBuffer.MatricesIndicesKind * - BABYLON.VertexBuffer.MatricesIndicesExtraKind * - BABYLON.VertexBuffer.MatricesWeightsKind * - BABYLON.VertexBuffer.MatricesWeightsExtraKind */ Mesh.prototype.getVertexBuffer = function (kind) { if (!this._geometry) { return null; } return this._geometry.getVertexBuffer(kind); }; Mesh.prototype.isVerticesDataPresent = function (kind) { if (!this._geometry) { if (this._delayInfo) { return this._delayInfo.indexOf(kind) !== -1; } return false; } return this._geometry.isVerticesDataPresent(kind); }; /** * Returns a boolean defining if the vertex data for the requested `kind` is updatable. * Possible `kind` values : * - BABYLON.VertexBuffer.PositionKind * - BABYLON.VertexBuffer.UVKind * - BABYLON.VertexBuffer.UV2Kind * - BABYLON.VertexBuffer.UV3Kind * - BABYLON.VertexBuffer.UV4Kind * - BABYLON.VertexBuffer.UV5Kind * - BABYLON.VertexBuffer.UV6Kind * - BABYLON.VertexBuffer.ColorKind * - BABYLON.VertexBuffer.MatricesIndicesKind * - BABYLON.VertexBuffer.MatricesIndicesExtraKind * - BABYLON.VertexBuffer.MatricesWeightsKind * - BABYLON.VertexBuffer.MatricesWeightsExtraKind */ Mesh.prototype.isVertexBufferUpdatable = function (kind) { if (!this._geometry) { if (this._delayInfo) { return this._delayInfo.indexOf(kind) !== -1; } return false; } return this._geometry.isVertexBufferUpdatable(kind); }; /** * Returns a string : the list of existing `kinds` of Vertex Data for this mesh. * Possible `kind` values : * - BABYLON.VertexBuffer.PositionKind * - BABYLON.VertexBuffer.UVKind * - BABYLON.VertexBuffer.UV2Kind * - BABYLON.VertexBuffer.UV3Kind * - BABYLON.VertexBuffer.UV4Kind * - BABYLON.VertexBuffer.UV5Kind * - BABYLON.VertexBuffer.UV6Kind * - BABYLON.VertexBuffer.ColorKind * - BABYLON.VertexBuffer.MatricesIndicesKind * - BABYLON.VertexBuffer.MatricesIndicesExtraKind * - BABYLON.VertexBuffer.MatricesWeightsKind * - BABYLON.VertexBuffer.MatricesWeightsExtraKind */ Mesh.prototype.getVerticesDataKinds = function () { if (!this._geometry) { var result = new Array(); if (this._delayInfo) { this._delayInfo.forEach(function (kind, index, array) { result.push(kind); }); } return result; } return this._geometry.getVerticesDataKinds(); }; /** * Returns a positive integer : the total number of indices in this mesh geometry. * Returns zero if the mesh has no geometry. */ Mesh.prototype.getTotalIndices = function () { if (!this._geometry) { return 0; } return this._geometry.getTotalIndices(); }; /** * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one. * Returns an empty array if the mesh has no geometry. */ Mesh.prototype.getIndices = function (copyWhenShared) { if (!this._geometry) { return []; } return this._geometry.getIndices(copyWhenShared); }; Object.defineProperty(Mesh.prototype, "isBlocked", { get: function () { return this._masterMesh !== null && this._masterMesh !== undefined; }, enumerable: true, configurable: true }); /** * Determine if the current mesh is ready to be rendered * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default) * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default) * @returns true if all associated assets are ready (material, textures, shaders) */ Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) { if (completeCheck === void 0) { completeCheck = false; } if (forceInstanceSupport === void 0) { forceInstanceSupport = false; } if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) { return false; } if (!_super.prototype.isReady.call(this, completeCheck)) { return false; } if (!this.subMeshes || this.subMeshes.length === 0) { return true; } if (!completeCheck) { return true; } var engine = this.getEngine(); var scene = this.getScene(); var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0; this.computeWorldMatrix(); var mat = this.material || scene.defaultMaterial; if (mat) { if (mat.storeEffectOnSubMeshes) { for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) { var subMesh = _a[_i]; var effectiveMaterial = subMesh.getMaterial(); if (effectiveMaterial) { if (effectiveMaterial.storeEffectOnSubMeshes) { if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) { return false; } } else { if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) { return false; } } } } } else { if (!mat.isReady(this, hardwareInstancedRendering)) { return false; } } } // Shadows for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) { var light = _c[_b]; var generator = light.getShadowGenerator(); if (generator) { for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) { var subMesh = _e[_d]; if (!generator.isReady(subMesh, hardwareInstancedRendering)) { return false; } } } } // LOD for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) { var lod = _g[_f]; if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) { return false; } } return true; }; Object.defineProperty(Mesh.prototype, "areNormalsFrozen", { /** * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update. * This property is pertinent only for updatable parametric shapes. */ get: function () { return this._areNormalsFrozen; }, enumerable: true, configurable: true }); /** * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. * It has no effect at all on other shapes. * It prevents the mesh normals from being recomputed on next `positions` array update. * Returns the Mesh. */ Mesh.prototype.freezeNormals = function () { this._areNormalsFrozen = true; return this; }; /** * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. * It has no effect at all on other shapes. * It reactivates the mesh normals computation if it was previously frozen. * Returns the Mesh. */ Mesh.prototype.unfreezeNormals = function () { this._areNormalsFrozen = false; return this; }; Object.defineProperty(Mesh.prototype, "overridenInstanceCount", { /** * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs */ set: function (count) { this._overridenInstanceCount = count; }, enumerable: true, configurable: true }); // Methods Mesh.prototype._preActivate = function () { var sceneRenderId = this.getScene().getRenderId(); if (this._preActivateId === sceneRenderId) { return this; } this._preActivateId = sceneRenderId; this._visibleInstances = null; return this; }; Mesh.prototype._preActivateForIntermediateRendering = function (renderId) { if (this._visibleInstances) { this._visibleInstances.intermediateDefaultRenderId = renderId; } return this; }; Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) { if (!this._visibleInstances) { this._visibleInstances = {}; this._visibleInstances.defaultRenderId = renderId; this._visibleInstances.selfDefaultRenderId = this._renderId; } if (!this._visibleInstances[renderId]) { this._visibleInstances[renderId] = new Array(); } this._visibleInstances[renderId].push(instance); return this; }; /** * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked. * This means the mesh underlying bounding box and sphere are recomputed. * Returns the Mesh. */ Mesh.prototype.refreshBoundingInfo = function () { return this._refreshBoundingInfo(false); }; Mesh.prototype._refreshBoundingInfo = function (applySkeleton) { if (this._boundingInfo && this._boundingInfo.isLocked) { return this; } var data = this._getPositionData(applySkeleton); if (data) { var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices()); this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum); } if (this.subMeshes) { for (var index = 0; index < this.subMeshes.length; index++) { this.subMeshes[index].refreshBoundingInfo(); } } this._updateBoundingInfo(); return this; }; Mesh.prototype._getPositionData = function (applySkeleton) { var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind); if (data && applySkeleton && this.skeleton) { data = BABYLON.Tools.Slice(data); var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind); var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind); if (matricesWeightsData && matricesIndicesData) { var needExtras = this.numBoneInfluencers > 4; var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null; var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null; var skeletonMatrices = this.skeleton.getTransformMatrices(this); var tempVector = BABYLON.Tmp.Vector3[0]; var finalMatrix = BABYLON.Tmp.Matrix[0]; var tempMatrix = BABYLON.Tmp.Matrix[1]; var matWeightIdx = 0; for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) { finalMatrix.reset(); var inf; var weight; for (inf = 0; inf < 4; inf++) { weight = matricesWeightsData[matWeightIdx + inf]; if (weight <= 0) break; BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix); finalMatrix.addToSelf(tempMatrix); } if (needExtras) { for (inf = 0; inf < 4; inf++) { weight = matricesWeightsExtraData[matWeightIdx + inf]; if (weight <= 0) break; BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix); finalMatrix.addToSelf(tempMatrix); } } BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector); tempVector.toArray(data, index); } } } return data; }; Mesh.prototype._createGlobalSubMesh = function (force) { var totalVertices = this.getTotalVertices(); if (!totalVertices || !this.getIndices()) { return null; } // Check if we need to recreate the submeshes if (this.subMeshes && this.subMeshes.length > 0) { var ib = this.getIndices(); if (!ib) { return null; } var totalIndices = ib.length; var needToRecreate = false; if (force) { needToRecreate = true; } else { for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) { var submesh = _a[_i]; if (submesh.indexStart + submesh.indexCount >= totalIndices) { needToRecreate = true; break; } if (submesh.verticesStart + submesh.verticesCount >= totalVertices) { needToRecreate = true; break; } } } if (!needToRecreate) { return this.subMeshes[0]; } } this.releaseSubMeshes(); return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this); }; Mesh.prototype.subdivide = function (count) { if (count < 1) { return; } var totalIndices = this.getTotalIndices(); var subdivisionSize = (totalIndices / count) | 0; var offset = 0; // Ensure that subdivisionSize is a multiple of 3 while (subdivisionSize % 3 !== 0) { subdivisionSize++; } this.releaseSubMeshes(); for (var index = 0; index < count; index++) { if (offset >= totalIndices) { break; } BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this); offset += subdivisionSize; } this.synchronizeInstances(); }; Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) { if (updatable === void 0) { updatable = false; } if (!this._geometry) { var vertexData = new BABYLON.VertexData(); vertexData.set(data, kind); var scene = this.getScene(); new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this); } else { this._geometry.setVerticesData(kind, data, updatable, stride); } return this; }; Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) { if (updatable === void 0) { updatable = true; } var vb = this.getVertexBuffer(kind); if (!vb || vb.isUpdatable() === updatable) { return; } this.setVerticesData(kind, this.getVerticesData(kind), updatable); }; /** * Sets the mesh VertexBuffer. * Returns the Mesh. */ Mesh.prototype.setVerticesBuffer = function (buffer) { if (!this._geometry) { this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this); } this._geometry.setVerticesBuffer(buffer); return this; }; Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) { if (!this._geometry) { return this; } if (!makeItUnique) { this._geometry.updateVerticesData(kind, data, updateExtends); } else { this.makeGeometryUnique(); this.updateVerticesData(kind, data, updateExtends, false); } return this; }; /** * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update. * Returns the Mesh. */ Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) { if (computeNormals === void 0) { computeNormals = true; } var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind); if (!positions) { return this; } positionFunction(positions); this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false); if (computeNormals) { var indices = this.getIndices(); var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind); if (!normals) { return this; } BABYLON.VertexData.ComputeNormals(positions, indices, normals); this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false); } return this; }; /** * Creates a un-shared specific occurence of the geometry for the mesh. * Returns the Mesh. */ Mesh.prototype.makeGeometryUnique = function () { if (!this._geometry) { return this; } var oldGeometry = this._geometry; var geometry = this._geometry.copy(BABYLON.Geometry.RandomId()); oldGeometry.releaseForMesh(this, true); geometry.applyToMesh(this); return this; }; Mesh.prototype.setIndices = function (indices, totalVertices, updatable) { if (totalVertices === void 0) { totalVertices = null; } if (updatable === void 0) { updatable = false; } if (!this._geometry) { var vertexData = new BABYLON.VertexData(); vertexData.indices = indices; var scene = this.getScene(); new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this); } else { this._geometry.setIndices(indices, totalVertices, updatable); } return this; }; /** * Update the current index buffer * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array) * Returns the Mesh. */ Mesh.prototype.updateIndices = function (indices, offset) { if (!this._geometry) { return this; } this._geometry.updateIndices(indices, offset); return this; }; /** * Invert the geometry to move from a right handed system to a left handed one. * Returns the Mesh. */ Mesh.prototype.toLeftHanded = function () { if (!this._geometry) { return this; } this._geometry.toLeftHanded(); return this; }; Mesh.prototype._bind = function (subMesh, effect, fillMode) { if (!this._geometry) { return this; } var engine = this.getScene().getEngine(); // Wireframe var indexToBind; if (this._unIndexed) { indexToBind = null; } else { switch (fillMode) { case BABYLON.Material.PointFillMode: indexToBind = null; break; case BABYLON.Material.WireFrameFillMode: indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine); break; default: case BABYLON.Material.TriangleFillMode: indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer(); break; } } // VBOs this._geometry._bind(effect, indexToBind); return this; }; Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) { if (alternate === void 0) { alternate = false; } if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) { return this; } this.onBeforeDrawObservable.notifyObservers(this); var scene = this.getScene(); var engine = scene.getEngine(); if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) { // or triangles as points engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount); } else if (fillMode == BABYLON.Material.WireFrameFillMode) { // Triangles as wireframe engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount); } else { engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount); } if (scene._isAlternateRenderingEnabled && !alternate) { var effect = subMesh.effect || this._effectiveMaterial.getEffect(); if (!effect || !scene.activeCamera) { return this; } scene._switchToAlternateCameraConfiguration(true); this._effectiveMaterial.bindView(effect); this._effectiveMaterial.bindViewProjection(effect); engine.setViewport(scene.activeCamera._alternateCamera.viewport); this._draw(subMesh, fillMode, instancesCount, true); engine.setViewport(scene.activeCamera.viewport); scene._switchToAlternateCameraConfiguration(false); this._effectiveMaterial.bindView(effect); this._effectiveMaterial.bindViewProjection(effect); } return this; }; /** * Registers for this mesh a javascript function called just before the rendering process. * This function is passed the current mesh. * Return the Mesh. */ Mesh.prototype.registerBeforeRender = function (func) { this.onBeforeRenderObservable.add(func); return this; }; /** * Disposes a previously registered javascript function called before the rendering. * This function is passed the current mesh. * Returns the Mesh. */ Mesh.prototype.unregisterBeforeRender = function (func) { this.onBeforeRenderObservable.removeCallback(func); return this; }; /** * Registers for this mesh a javascript function called just after the rendering is complete. * This function is passed the current mesh. * Returns the Mesh. */ Mesh.prototype.registerAfterRender = function (func) { this.onAfterRenderObservable.add(func); return this; }; /** * Disposes a previously registered javascript function called after the rendering. * This function is passed the current mesh. * Return the Mesh. */ Mesh.prototype.unregisterAfterRender = function (func) { this.onAfterRenderObservable.removeCallback(func); return this; }; Mesh.prototype._getInstancesRenderList = function (subMeshId) { var scene = this.getScene(); this._batchCache.mustReturn = false; this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible; this._batchCache.visibleInstances[subMeshId] = null; if (this._visibleInstances) { var currentRenderId = scene.getRenderId(); var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId); this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId]; var selfRenderId = this._renderId; if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) { this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId]; currentRenderId = Math.max(defaultRenderId, currentRenderId); selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId); } var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId]; if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) { if (this._renderIdForInstances[subMeshId] === currentRenderId) { this._batchCache.mustReturn = true; return this._batchCache; } if (currentRenderId !== selfRenderId) { this._batchCache.renderSelf[subMeshId] = false; } } this._renderIdForInstances[subMeshId] = currentRenderId; } return this._batchCache; }; Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) { var visibleInstances = batch.visibleInstances[subMesh._id]; if (!visibleInstances) { return this; } var matricesCount = visibleInstances.length + 1; var bufferSize = matricesCount * 16 * 4; var currentInstancesBufferSize = this._instancesBufferSize; var instancesBuffer = this._instancesBuffer; while (this._instancesBufferSize < bufferSize) { this._instancesBufferSize *= 2; } if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) { this._instancesData = new Float32Array(this._instancesBufferSize / 4); } var offset = 0; var instancesCount = 0; var world = this.getWorldMatrix(); if (batch.renderSelf[subMesh._id]) { world.copyToArray(this._instancesData, offset); offset += 16; instancesCount++; } if (visibleInstances) { for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) { var instance = visibleInstances[instanceIndex]; instance.getWorldMatrix().copyToArray(this._instancesData, offset); offset += 16; instancesCount++; } } if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) { if (instancesBuffer) { instancesBuffer.dispose(); } instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true); this._instancesBuffer = instancesBuffer; this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4)); this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4)); this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4)); this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4)); } else { instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount); } this._bind(subMesh, effect, fillMode); this._draw(subMesh, fillMode, instancesCount); engine.unbindInstanceAttributes(); return this; }; Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) { var scene = this.getScene(); var engine = scene.getEngine(); if (hardwareInstancedRendering) { this._renderWithInstances(subMesh, fillMode, batch, effect, engine); } else { if (batch.renderSelf[subMesh._id]) { // Draw if (onBeforeDraw) { onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial); } this._draw(subMesh, fillMode, this._overridenInstanceCount); } var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id]; if (visibleInstancesForSubMesh) { for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) { var instance = visibleInstancesForSubMesh[instanceIndex]; // World var world = instance.getWorldMatrix(); if (onBeforeDraw) { onBeforeDraw(true, world, effectiveMaterial); } // Draw this._draw(subMesh, fillMode); } } } return this; }; /** * Triggers the draw call for the mesh. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager. * Returns the Mesh. */ Mesh.prototype.render = function (subMesh, enableAlphaMode) { this._checkOcclusionQuery(); if (this._isOccluded) { return this; } var scene = this.getScene(); // Managing instances var batch = this._getInstancesRenderList(subMesh._id); if (batch.mustReturn) { return this; } // Checking geometry state if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) { return this; } this.onBeforeRenderObservable.notifyObservers(this); var engine = scene.getEngine(); var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined); // Material var material = subMesh.getMaterial(); if (!material) { return this; } this._effectiveMaterial = material; if (this._effectiveMaterial.storeEffectOnSubMeshes) { if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) { return this; } } else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) { return this; } // Alpha mode if (enableAlphaMode) { engine.setAlphaMode(this._effectiveMaterial.alphaMode); } // Outline - step 1 var savedDepthWrite = engine.getDepthWrite(); if (this.renderOutline) { engine.setDepthWrite(false); scene.getOutlineRenderer().render(subMesh, batch); engine.setDepthWrite(savedDepthWrite); } var effect; if (this._effectiveMaterial.storeEffectOnSubMeshes) { effect = subMesh.effect; } else { effect = this._effectiveMaterial.getEffect(); } if (!effect) { return this; } var sideOrientation = this.overrideMaterialSideOrientation; if (sideOrientation == null) { sideOrientation = this._effectiveMaterial.sideOrientation; if (this._getWorldMatrixDeterminant() < 0) { sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation); } } var reverse = this._effectiveMaterial._preBind(effect, sideOrientation); if (this._effectiveMaterial.forceDepthWrite) { engine.setDepthWrite(true); } // Bind var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode); if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB this._bind(subMesh, effect, fillMode); } var world = this.getWorldMatrix(); if (this._effectiveMaterial.storeEffectOnSubMeshes) { this._effectiveMaterial.bindForSubMesh(world, this, subMesh); } else { this._effectiveMaterial.bind(world, this); } if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) { engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse); this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial); engine.setState(true, this._effectiveMaterial.zOffset, false, reverse); } // Draw this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial); // Unbind this._effectiveMaterial.unbind(); // Outline - step 2 if (this.renderOutline && savedDepthWrite) { engine.setDepthWrite(true); engine.setColorWrite(false); scene.getOutlineRenderer().render(subMesh, batch); engine.setColorWrite(true); } // Overlay if (this.renderOverlay) { var currentMode = engine.getAlphaMode(); engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE); scene.getOutlineRenderer().render(subMesh, batch, true); engine.setAlphaMode(currentMode); } this.onAfterRenderObservable.notifyObservers(this); return this; }; Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) { if (isInstance && effectiveMaterial) { effectiveMaterial.bindOnlyWorldMatrix(world); } }; /** * Returns an array populated with ParticleSystem objects whose the mesh is the emitter. */ Mesh.prototype.getEmittedParticleSystems = function () { var results = new Array(); for (var index = 0; index < this.getScene().particleSystems.length; index++) { var particleSystem = this.getScene().particleSystems[index]; if (particleSystem.emitter === this) { results.push(particleSystem); } } return results; }; /** * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter. */ Mesh.prototype.getHierarchyEmittedParticleSystems = function () { var results = new Array(); var descendants = this.getDescendants(); descendants.push(this); for (var index = 0; index < this.getScene().particleSystems.length; index++) { var particleSystem = this.getScene().particleSystems[index]; var emitter = particleSystem.emitter; if (emitter.position && descendants.indexOf(emitter) !== -1) { results.push(particleSystem); } } return results; }; /** * Normalize matrix weights so that all vertices have a total weight set to 1 */ Mesh.prototype.cleanMatrixWeights = function () { var epsilon = 1e-3; var noInfluenceBoneIndex = 0.0; if (this.skeleton) { noInfluenceBoneIndex = this.skeleton.bones.length; } else { return; } var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind); var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind); var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind); var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind); var influencers = this.numBoneInfluencers; var size = matricesWeights.length; for (var i = 0; i < size; i += 4) { var weight = 0.0; var firstZeroWeight = -1; for (var j = 0; j < 4; j++) { var w = matricesWeights[i + j]; weight += w; if (w < epsilon && firstZeroWeight < 0) { firstZeroWeight = j; } } if (matricesWeightsExtra) { for (var j = 0; j < 4; j++) { var w = matricesWeightsExtra[i + j]; weight += w; if (w < epsilon && firstZeroWeight < 0) { firstZeroWeight = j + 4; } } } if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) { firstZeroWeight = influencers - 1; } if (weight > epsilon) { var mweight = 1.0 / weight; for (var j = 0; j < 4; j++) { matricesWeights[i + j] *= mweight; } if (matricesWeightsExtra) { for (var j = 0; j < 4; j++) { matricesWeightsExtra[i + j] *= mweight; } } } else { if (firstZeroWeight >= 4) { matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight; matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex; } else { matricesWeights[i + firstZeroWeight] = 1.0 - weight; matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex; } } } this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices); if (matricesIndicesExtra) { this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra); } this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights); if (matricesWeightsExtra) { this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra); } }; Mesh.prototype._checkDelayState = function () { var scene = this.getScene(); if (this._geometry) { this._geometry.load(scene); } else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) { this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING; this._queueLoad(scene); } return this; }; Mesh.prototype._queueLoad = function (scene) { var _this = this; scene._addPendingData(this); var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1); BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) { if (data instanceof ArrayBuffer) { _this._delayLoadingFunction(data, _this); } else { _this._delayLoadingFunction(JSON.parse(data), _this); } _this.instances.forEach(function (instance) { instance._syncSubMeshes(); }); _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED; scene._removePendingData(_this); }, function () { }, scene.database, getBinaryData); return this; }; /** * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter. */ Mesh.prototype.isInFrustum = function (frustumPlanes) { if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) { return false; } if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) { return false; } this._checkDelayState(); return true; }; /** * Sets the mesh material by the material or multiMaterial `id` property. * The material `id` is a string identifying the material or the multiMaterial. * This method returns the Mesh. */ Mesh.prototype.setMaterialByID = function (id) { var materials = this.getScene().materials; var index; for (index = materials.length - 1; index > -1; index--) { if (materials[index].id === id) { this.material = materials[index]; return this; } } // Multi var multiMaterials = this.getScene().multiMaterials; for (index = multiMaterials.length - 1; index > -1; index--) { if (multiMaterials[index].id === id) { this.material = multiMaterials[index]; return this; } } return this; }; /** * Returns as a new array populated with the mesh material and/or skeleton, if any. */ Mesh.prototype.getAnimatables = function () { var results = new Array(); if (this.material) { results.push(this.material); } if (this.skeleton) { results.push(this.skeleton); } return results; }; /** * Modifies the mesh geometry according to the passed transformation matrix. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable. * The mesh normals are modified accordingly the same transformation. * tuto : http://doc.babylonjs.com/resources/baking_transformations * Note that, under the hood, this method sets a new VertexBuffer each call. * Returns the Mesh. */ Mesh.prototype.bakeTransformIntoVertices = function (transform) { // Position if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) { return this; } var submeshes = this.subMeshes.splice(0); this._resetPointsArrayCache(); var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind); var temp = new Array(); var index; for (index = 0; index < data.length; index += 3) { BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index); } this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()); // Normals if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) { return this; } data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind); temp = []; for (index = 0; index < data.length; index += 3) { BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index); } this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()); // flip faces? if (transform.m[0] * transform.m[5] * transform.m[10] < 0) { this.flipFaces(); } // Restore submeshes this.releaseSubMeshes(); this.subMeshes = submeshes; return this; }; /** * Modifies the mesh geometry according to its own current World Matrix. * The mesh World Matrix is then reset. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations * Note that, under the hood, this method sets a new VertexBuffer each call. * Returns the Mesh. */ Mesh.prototype.bakeCurrentTransformIntoVertices = function () { this.bakeTransformIntoVertices(this.computeWorldMatrix(true)); this.scaling.copyFromFloats(1, 1, 1); this.position.copyFromFloats(0, 0, 0); this.rotation.copyFromFloats(0, 0, 0); //only if quaternion is already set if (this.rotationQuaternion) { this.rotationQuaternion = BABYLON.Quaternion.Identity(); } this._worldMatrix = BABYLON.Matrix.Identity(); return this; }; Object.defineProperty(Mesh.prototype, "_positions", { // Cache get: function () { if (this._geometry) { return this._geometry._positions; } return null; }, enumerable: true, configurable: true }); Mesh.prototype._resetPointsArrayCache = function () { if (this._geometry) { this._geometry._resetPointsArrayCache(); } return this; }; Mesh.prototype._generatePointsArray = function () { if (this._geometry) { return this._geometry._generatePointsArray(); } return false; }; /** * Returns a new Mesh object generated from the current mesh properties. * This method must not get confused with createInstance(). * The parameter `name` is a string, the name given to the new mesh. * The optional parameter `newParent` can be any Node object (default `null`). * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any. */ Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) { if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; } return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor); }; /** * Releases resources associated with this mesh. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default) * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default) */ Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) { var _this = this; if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; } this.morphTargetManager = null; if (this._geometry) { this._geometry.releaseForMesh(this, true); } // Sources var meshes = this.getScene().meshes; meshes.forEach(function (abstractMesh) { var mesh = abstractMesh; if (mesh._source && mesh._source === _this) { mesh._source = null; } }); this._source = null; // Instances if (this._instancesBuffer) { this._instancesBuffer.dispose(); this._instancesBuffer = null; } while (this.instances.length) { this.instances[0].dispose(); } // Effect layers. var effectLayers = this.getScene().effectLayers; for (var i = 0; i < effectLayers.length; i++) { var effectLayer = effectLayers[i]; if (effectLayer) { effectLayer._disposeMesh(this); } } _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures); }; /** * Modifies the mesh geometry according to a displacement map. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated. * This method returns nothing. * The parameter `url` is a string, the URL from the image file is to be downloaded. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing. * The parameter `uvOffset` is an optional vector2 used to offset UV. * The parameter `uvScale` is an optional vector2 used to scale UV. * * Returns the Mesh. */ Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) { var _this = this; var scene = this.getScene(); var onload = function (img) { // Getting height map data var canvas = document.createElement("canvas"); var context = canvas.getContext("2d"); var heightMapWidth = img.width; var heightMapHeight = img.height; canvas.width = heightMapWidth; canvas.height = heightMapHeight; context.drawImage(img, 0, 0); // Create VertexData from map data //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949 var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data; _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale); //execute success callback, if set if (onSuccess) { onSuccess(_this); } }; BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database); return this; }; /** * Modifies the mesh geometry according to a displacementMap buffer. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated. * This method returns nothing. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement. * The parameter `uvOffset` is an optional vector2 used to offset UV. * The parameter `uvScale` is an optional vector2 used to scale UV. * * Returns the Mesh. */ Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) { if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) { BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"); return this; } var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind); var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind); var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind); var position = BABYLON.Vector3.Zero(); var normal = BABYLON.Vector3.Zero(); var uv = BABYLON.Vector2.Zero(); uvOffset = uvOffset || BABYLON.Vector2.Zero(); uvScale = uvScale || new BABYLON.Vector2(1, 1); for (var index = 0; index < positions.length; index += 3) { BABYLON.Vector3.FromArrayToRef(positions, index, position); BABYLON.Vector3.FromArrayToRef(normals, index, normal); BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv); // Compute height var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0; var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0; var pos = (u + v * heightMapWidth) * 4; var r = buffer[pos] / 255.0; var g = buffer[pos + 1] / 255.0; var b = buffer[pos + 2] / 255.0; var gradient = r * 0.3 + g * 0.59 + b * 0.11; normal.normalize(); normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient); position = position.add(normal); position.toArray(positions, index); } BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals); this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions); this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals); return this; }; /** * Modify the mesh to get a flat shading rendering. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result. * This method returns the Mesh. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated. */ Mesh.prototype.convertToFlatShadedMesh = function () { /// Update normals and vertices to get a flat shading rendering. /// Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face var kinds = this.getVerticesDataKinds(); var vbs = {}; var data = {}; var newdata = {}; var updatableNormals = false; var kindIndex; var kind; for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) { kind = kinds[kindIndex]; var vertexBuffer = this.getVertexBuffer(kind); if (kind === BABYLON.VertexBuffer.NormalKind) { updatableNormals = vertexBuffer.isUpdatable(); kinds.splice(kindIndex, 1); kindIndex--; continue; } vbs[kind] = vertexBuffer; data[kind] = vbs[kind].getData(); newdata[kind] = []; } // Save previous submeshes var previousSubmeshes = this.subMeshes.slice(0); var indices = this.getIndices(); var totalIndices = this.getTotalIndices(); // Generating unique vertices per face var index; for (index = 0; index < totalIndices; index++) { var vertexIndex = indices[index]; for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) { kind = kinds[kindIndex]; var stride = vbs[kind].getStrideSize(); for (var offset = 0; offset < stride; offset++) { newdata[kind].push(data[kind][vertexIndex * stride + offset]); } } } // Updating faces & normal var normals = []; var positions = newdata[BABYLON.VertexBuffer.PositionKind]; for (index = 0; index < totalIndices; index += 3) { indices[index] = index; indices[index + 1] = index + 1; indices[index + 2] = index + 2; var p1 = BABYLON.Vector3.FromArray(positions, index * 3); var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3); var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3); var p1p2 = p1.subtract(p2); var p3p2 = p3.subtract(p2); var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2)); // Store same normals for every vertex for (var localIndex = 0; localIndex < 3; localIndex++) { normals.push(normal.x); normals.push(normal.y); normals.push(normal.z); } } this.setIndices(indices); this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals); // Updating vertex buffers for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) { kind = kinds[kindIndex]; this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable()); } // Updating submeshes this.releaseSubMeshes(); for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) { var previousOne = previousSubmeshes[submeshIndex]; BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this); } this.synchronizeInstances(); return this; }; /** * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers. * In other words, more vertices, no more indices and a single bigger VBO. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated. * Returns the Mesh. */ Mesh.prototype.convertToUnIndexedMesh = function () { /// Remove indices by unfolding faces into buffers /// Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face var kinds = this.getVerticesDataKinds(); var vbs = {}; var data = {}; var newdata = {}; var kindIndex; var kind; for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) { kind = kinds[kindIndex]; var vertexBuffer = this.getVertexBuffer(kind); vbs[kind] = vertexBuffer; data[kind] = vbs[kind].getData(); newdata[kind] = []; } // Save previous submeshes var previousSubmeshes = this.subMeshes.slice(0); var indices = this.getIndices(); var totalIndices = this.getTotalIndices(); // Generating unique vertices per face var index; for (index = 0; index < totalIndices; index++) { var vertexIndex = indices[index]; for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) { kind = kinds[kindIndex]; var stride = vbs[kind].getStrideSize(); for (var offset = 0; offset < stride; offset++) { newdata[kind].push(data[kind][vertexIndex * stride + offset]); } } } // Updating indices for (index = 0; index < totalIndices; index += 3) { indices[index] = index; indices[index + 1] = index + 1; indices[index + 2] = index + 2; } this.setIndices(indices); // Updating vertex buffers for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) { kind = kinds[kindIndex]; this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable()); } // Updating submeshes this.releaseSubMeshes(); for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) { var previousOne = previousSubmeshes[submeshIndex]; BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this); } this._unIndexed = true; this.synchronizeInstances(); return this; }; /** * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true. * This method returns the Mesh. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call. */ Mesh.prototype.flipFaces = function (flipNormals) { if (flipNormals === void 0) { flipNormals = false; } var vertex_data = BABYLON.VertexData.ExtractFromMesh(this); var i; if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) { for (i = 0; i < vertex_data.normals.length; i++) { vertex_data.normals[i] *= -1; } } if (vertex_data.indices) { var temp; for (i = 0; i < vertex_data.indices.length; i += 3) { // reassign indices temp = vertex_data.indices[i + 1]; vertex_data.indices[i + 1] = vertex_data.indices[i + 2]; vertex_data.indices[i + 2] = temp; } } vertex_data.applyToMesh(this); return this; }; // Instances /** * Creates a new InstancedMesh object from the mesh model. * An instance shares the same properties and the same material than its model. * Only these properties of each instance can then be set individually : * - position * - rotation * - rotationQuaternion * - setPivotMatrix * - scaling * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances * Warning : this method is not supported for Line mesh and LineSystem */ Mesh.prototype.createInstance = function (name) { return new BABYLON.InstancedMesh(name, this); }; /** * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any. * After this call, all the mesh instances have the same submeshes than the current mesh. * This method returns the Mesh. */ Mesh.prototype.synchronizeInstances = function () { for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) { var instance = this.instances[instanceIndex]; instance._syncSubMeshes(); } return this; }; /** * Simplify the mesh according to the given array of settings. * Function will return immediately and will simplify async. It returns the Mesh. * @param settings a collection of simplification settings. * @param parallelProcessing should all levels calculate parallel or one after the other. * @param type the type of simplification to run. * @param successCallback optional success callback to be called after the simplification finished processing all settings. */ Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) { if (parallelProcessing === void 0) { parallelProcessing = true; } if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; } this.getScene().simplificationQueue.addTask({ settings: settings, parallelProcessing: parallelProcessing, mesh: this, simplificationType: simplificationType, successCallback: successCallback }); return this; }; /** * Optimization of the mesh's indices, in case a mesh has duplicated vertices. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes. * This should be used together with the simplification to avoid disappearing triangles. * Returns the Mesh. * @param successCallback an optional success callback to be called after the optimization finished. */ Mesh.prototype.optimizeIndices = function (successCallback) { var _this = this; var indices = this.getIndices(); var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind); if (!positions || !indices) { return this; } var vectorPositions = new Array(); for (var pos = 0; pos < positions.length; pos = pos + 3) { vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos)); } var dupes = new Array(); BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) { var realPos = vectorPositions.length - 1 - iteration; var testedPosition = vectorPositions[realPos]; for (var j = 0; j < realPos; ++j) { var againstPosition = vectorPositions[j]; if (testedPosition.equals(againstPosition)) { dupes[realPos] = j; break; } } }, function () { for (var i = 0; i < indices.length; ++i) { indices[i] = dupes[indices[i]] || indices[i]; } //indices are now reordered var originalSubMeshes = _this.subMeshes.slice(0); _this.setIndices(indices); _this.subMeshes = originalSubMeshes; if (successCallback) { successCallback(_this); } }); return this; }; Mesh.prototype.serialize = function (serializationObject) { serializationObject.name = this.name; serializationObject.id = this.id; serializationObject.type = this.getClassName(); if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) { serializationObject.tags = BABYLON.Tags.GetTags(this); } serializationObject.position = this.position.asArray(); if (this.rotationQuaternion) { serializationObject.rotationQuaternion = this.rotationQuaternion.asArray(); } else if (this.rotation) { serializationObject.rotation = this.rotation.asArray(); } serializationObject.scaling = this.scaling.asArray(); serializationObject.localMatrix = this.getPivotMatrix().asArray(); serializationObject.isEnabled = this.isEnabled(false); serializationObject.isVisible = this.isVisible; serializationObject.infiniteDistance = this.infiniteDistance; serializationObject.pickable = this.isPickable; serializationObject.receiveShadows = this.receiveShadows; serializationObject.billboardMode = this.billboardMode; serializationObject.visibility = this.visibility; serializationObject.checkCollisions = this.checkCollisions; serializationObject.isBlocker = this.isBlocker; // Parent if (this.parent) { serializationObject.parentId = this.parent.id; } // Geometry serializationObject.isUnIndexed = this.isUnIndexed; var geometry = this._geometry; if (geometry) { var geometryId = geometry.id; serializationObject.geometryId = geometryId; // SubMeshes serializationObject.subMeshes = []; for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) { var subMesh = this.subMeshes[subIndex]; serializationObject.subMeshes.push({ materialIndex: subMesh.materialIndex, verticesStart: subMesh.verticesStart, verticesCount: subMesh.verticesCount, indexStart: subMesh.indexStart, indexCount: subMesh.indexCount }); } } // Material if (this.material) { serializationObject.materialId = this.material.id; } else { this.material = null; } // Morph targets if (this.morphTargetManager) { serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId; } // Skeleton if (this.skeleton) { serializationObject.skeletonId = this.skeleton.id; } // Physics //TODO implement correct serialization for physics impostors. var impostor = this.getPhysicsImpostor(); if (impostor) { serializationObject.physicsMass = impostor.getParam("mass"); serializationObject.physicsFriction = impostor.getParam("friction"); serializationObject.physicsRestitution = impostor.getParam("mass"); serializationObject.physicsImpostor = impostor.type; } // Metadata if (this.metadata) { serializationObject.metadata = this.metadata; } // Instances serializationObject.instances = []; for (var index = 0; index < this.instances.length; index++) { var instance = this.instances[index]; var serializationInstance = { name: instance.name, id: instance.id, position: instance.position.asArray(), scaling: instance.scaling.asArray() }; if (instance.rotationQuaternion) { serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray(); } else if (instance.rotation) { serializationInstance.rotation = instance.rotation.asArray(); } serializationObject.instances.push(serializationInstance); // Animations BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance); serializationInstance.ranges = instance.serializeAnimationRanges(); } // // Animations BABYLON.Animation.AppendSerializedAnimations(this, serializationObject); serializationObject.ranges = this.serializeAnimationRanges(); // Layer mask serializationObject.layerMask = this.layerMask; // Alpha serializationObject.alphaIndex = this.alphaIndex; serializationObject.hasVertexAlpha = this.hasVertexAlpha; // Overlay serializationObject.overlayAlpha = this.overlayAlpha; serializationObject.overlayColor = this.overlayColor.asArray(); serializationObject.renderOverlay = this.renderOverlay; // Fog serializationObject.applyFog = this.applyFog; // Action Manager if (this.actionManager) { serializationObject.actions = this.actionManager.serialize(this.name); } }; Mesh.prototype._syncGeometryWithMorphTargetManager = function () { if (!this.geometry) { return; } this._markSubMeshesAsAttributesDirty(); var morphTargetManager = this._morphTargetManager; if (morphTargetManager && morphTargetManager.vertexCount) { if (morphTargetManager.vertexCount !== this.getTotalVertices()) { BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count."); this.morphTargetManager = null; return; } for (var index = 0; index < morphTargetManager.numInfluencers; index++) { var morphTarget = morphTargetManager.getActiveTarget(index); var positions = morphTarget.getPositions(); if (!positions) { BABYLON.Tools.Error("Invalid morph target. Target must have positions."); return; } this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3); var normals = morphTarget.getNormals(); if (normals) { this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3); } var tangents = morphTarget.getTangents(); if (tangents) { this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3); } } } else { var index = 0; // Positions while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) { this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index); if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) { this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index); } if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) { this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index); } index++; } } }; // Statics /** * Returns a new Mesh object parsed from the source provided. * The parameter `parsedMesh` is the source. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with */ Mesh.Parse = function (parsedMesh, scene, rootUrl) { var mesh; if (parsedMesh.type && parsedMesh.type === "GroundMesh") { mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene); } else { mesh = new Mesh(parsedMesh.name, scene); } mesh.id = parsedMesh.id; if (BABYLON.Tags) { BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags); } mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position); if (parsedMesh.metadata !== undefined) { mesh.metadata = parsedMesh.metadata; } if (parsedMesh.rotationQuaternion) { mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion); } else if (parsedMesh.rotation) { mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation); } mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling); if (parsedMesh.localMatrix) { mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix)); } else if (parsedMesh.pivotMatrix) { mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix)); } mesh.setEnabled(parsedMesh.isEnabled); mesh.isVisible = parsedMesh.isVisible; mesh.infiniteDistance = parsedMesh.infiniteDistance; mesh.showBoundingBox = parsedMesh.showBoundingBox; mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox; if (parsedMesh.applyFog !== undefined) { mesh.applyFog = parsedMesh.applyFog; } if (parsedMesh.pickable !== undefined) { mesh.isPickable = parsedMesh.pickable; } if (parsedMesh.alphaIndex !== undefined) { mesh.alphaIndex = parsedMesh.alphaIndex; } mesh.receiveShadows = parsedMesh.receiveShadows; mesh.billboardMode = parsedMesh.billboardMode; if (parsedMesh.visibility !== undefined) { mesh.visibility = parsedMesh.visibility; } mesh.checkCollisions = parsedMesh.checkCollisions; if (parsedMesh.isBlocker !== undefined) { mesh.isBlocker = parsedMesh.isBlocker; } mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading; // freezeWorldMatrix if (parsedMesh.freezeWorldMatrix) { mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix; } // Parent if (parsedMesh.parentId) { mesh._waitingParentId = parsedMesh.parentId; } // Actions if (parsedMesh.actions !== undefined) { mesh._waitingActions = parsedMesh.actions; } // Overlay if (parsedMesh.overlayAlpha !== undefined) { mesh.overlayAlpha = parsedMesh.overlayAlpha; } if (parsedMesh.overlayColor !== undefined) { mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor); } if (parsedMesh.renderOverlay !== undefined) { mesh.renderOverlay = parsedMesh.renderOverlay; } // Geometry mesh.isUnIndexed = !!parsedMesh.isUnIndexed; mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha; if (parsedMesh.delayLoadingFile) { mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED; mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile; mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum)); if (parsedMesh._binaryInfo) { mesh._binaryInfo = parsedMesh._binaryInfo; } mesh._delayInfo = []; if (parsedMesh.hasUVs) { mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind); } if (parsedMesh.hasUVs2) { mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind); } if (parsedMesh.hasUVs3) { mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind); } if (parsedMesh.hasUVs4) { mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind); } if (parsedMesh.hasUVs5) { mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind); } if (parsedMesh.hasUVs6) { mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind); } if (parsedMesh.hasColors) { mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind); } if (parsedMesh.hasMatricesIndices) { mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind); } if (parsedMesh.hasMatricesWeights) { mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind); } mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry; if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) { mesh._checkDelayState(); } } else { BABYLON.Geometry._ImportGeometry(parsedMesh, mesh); } // Material if (parsedMesh.materialId) { mesh.setMaterialByID(parsedMesh.materialId); } else { mesh.material = null; } // Morph targets if (parsedMesh.morphTargetManagerId > -1) { mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId); } // Skeleton if (parsedMesh.skeletonId > -1) { mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId); if (parsedMesh.numBoneInfluencers) { mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers; } } // Animations if (parsedMesh.animations) { for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) { var parsedAnimation = parsedMesh.animations[animationIndex]; mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation)); } BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene); } if (parsedMesh.autoAnimate) { scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0); } // Layer Mask if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) { mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask)); } else { mesh.layerMask = 0x0FFFFFFF; } // Physics if (parsedMesh.physicsImpostor) { mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, { mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution }, scene); } // Instances if (parsedMesh.instances) { for (var index = 0; index < parsedMesh.instances.length; index++) { var parsedInstance = parsedMesh.instances[index]; var instance = mesh.createInstance(parsedInstance.name); if (parsedInstance.id) { instance.id = parsedInstance.id; } if (BABYLON.Tags) { BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags); } instance.position = BABYLON.Vector3.FromArray(parsedInstance.position); if (parsedInstance.parentId) { instance._waitingParentId = parsedInstance.parentId; } if (parsedInstance.rotationQuaternion) { instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion); } else if (parsedInstance.rotation) { instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation); } instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling); instance.checkCollisions = mesh.checkCollisions; if (parsedMesh.animations) { for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) { parsedAnimation = parsedMesh.animations[animationIndex]; instance.animations.push(BABYLON.Animation.Parse(parsedAnimation)); } BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene); if (parsedMesh.autoAnimate) { scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0); } } } } return mesh; }; /** * Creates a ribbon mesh. * Please consider using the same method from the MeshBuilder class instead. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters. * * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) { if (closeArray === void 0) { closeArray = false; } if (updatable === void 0) { updatable = false; } return BABYLON.MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: closeArray, closePath: closePath, offset: offset, updatable: updatable, sideOrientation: sideOrientation, instance: instance }, scene); }; /** * Creates a plane polygonal mesh. By default, this is a disc. * Please consider using the same method from the MeshBuilder class instead. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5). * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) { if (scene === void 0) { scene = null; } var options = { radius: radius, tessellation: tessellation, sideOrientation: sideOrientation, updatable: updatable }; return BABYLON.MeshBuilder.CreateDisc(name, options, scene); }; /** * Creates a box mesh. * Please consider using the same method from the MeshBuilder class instead. * The parameter `size` sets the size (float) of each box side (default 1). * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) { if (scene === void 0) { scene = null; } var options = { size: size, sideOrientation: sideOrientation, updatable: updatable }; return BABYLON.MeshBuilder.CreateBox(name, options, scene); }; /** * Creates a sphere mesh. * Please consider using the same method from the MeshBuilder class instead. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1). * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32). * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) { var options = { segments: segments, diameterX: diameter, diameterY: diameter, diameterZ: diameter, sideOrientation: sideOrientation, updatable: updatable }; return BABYLON.MeshBuilder.CreateSphere(name, options, scene); }; /** * Creates a cylinder or a cone mesh. * Please consider using the same method from the MeshBuilder class instead. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2). * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1). * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1). * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) { if (scene === undefined || !(scene instanceof BABYLON.Scene)) { if (scene !== undefined) { sideOrientation = updatable || Mesh.DEFAULTSIDE; updatable = scene; } scene = subdivisions; subdivisions = 1; } var options = { height: height, diameterTop: diameterTop, diameterBottom: diameterBottom, tessellation: tessellation, subdivisions: subdivisions, sideOrientation: sideOrientation, updatable: updatable }; return BABYLON.MeshBuilder.CreateCylinder(name, options, scene); }; // Torus (Code from SharpDX.org) /** * Creates a torus mesh. * Please consider using the same method from the MeshBuilder class instead. * The parameter `diameter` sets the diameter size (float) of the torus (default 1). * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5). * The parameter `tessellation` sets the number of torus sides (postive integer, default 16). * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) { var options = { diameter: diameter, thickness: thickness, tessellation: tessellation, sideOrientation: sideOrientation, updatable: updatable }; return BABYLON.MeshBuilder.CreateTorus(name, options, scene); }; /** * Creates a torus knot mesh. * Please consider using the same method from the MeshBuilder class instead. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2). * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32). * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32). * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3). * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) { var options = { radius: radius, tube: tube, radialSegments: radialSegments, tubularSegments: tubularSegments, p: p, q: q, sideOrientation: sideOrientation, updatable: updatable }; return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene); }; /** * Creates a line mesh. * Please consider using the same method from the MeshBuilder class instead. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function. * The parameter `points` is an array successive Vector3. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines * When updating an instance, remember that only point positions can change, not the number of points. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ Mesh.CreateLines = function (name, points, scene, updatable, instance) { if (scene === void 0) { scene = null; } if (updatable === void 0) { updatable = false; } if (instance === void 0) { instance = null; } var options = { points: points, updatable: updatable, instance: instance }; return BABYLON.MeshBuilder.CreateLines(name, options, scene); }; /** * Creates a dashed line mesh. * Please consider using the same method from the MeshBuilder class instead. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function. * The parameter `points` is an array successive Vector3. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200). * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3). * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1). * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines * When updating an instance, remember that only point positions can change, not the number of points. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) { if (scene === void 0) { scene = null; } var options = { points: points, dashSize: dashSize, gapSize: gapSize, dashNb: dashNb, updatable: updatable, instance: instance }; return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene); }; /** * Creates a polygon mesh. * Please consider using the same method from the MeshBuilder class instead. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh. * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. * Remember you can only change the shape positions, not their number when updating a polygon. */ Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) { var options = { shape: shape, holes: holes, updatable: updatable, sideOrientation: sideOrientation }; return BABYLON.MeshBuilder.CreatePolygon(name, options, scene); }; /** * Creates an extruded polygon mesh, with depth in the Y direction. * Please consider using the same method from the MeshBuilder class instead. */ Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) { var options = { shape: shape, holes: holes, depth: depth, updatable: updatable, sideOrientation: sideOrientation }; return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene); }; /** * Creates an extruded shape mesh. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters. * Please consider using the same method from the MeshBuilder class instead. * * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be * extruded along the Z axis. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve. * The parameter `scale` (float, default 1) is the value to scale the shape. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape * Remember you can only change the shape or path point positions, not their number when updating an extruded shape. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) { if (scene === void 0) { scene = null; } var options = { shape: shape, path: path, scale: scale, rotation: rotation, cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP, sideOrientation: sideOrientation, instance: instance, updatable: updatable }; return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene); }; /** * Creates an custom extruded shape mesh. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters. * Please consider using the same method from the MeshBuilder class instead. * * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be * extruded along the Z axis. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path * and the distance of this point from the begining of the path : * ```javascript * var rotationFunction = function(i, distance) { * // do things * return rotationValue; } * ``` * It must returns a float value that will be the rotation in radians applied to the shape on each path point. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path * and the distance of this point from the begining of the path : * ```javascript * var scaleFunction = function(i, distance) { * // do things * return scaleValue;} * ``` * It must returns a float value that will be the scale value applied to the shape on each path point. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape * Remember you can only change the shape or path point positions, not their number when updating an extruded shape. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) { var options = { shape: shape, path: path, scaleFunction: scaleFunction, rotationFunction: rotationFunction, ribbonCloseArray: ribbonCloseArray, ribbonClosePath: ribbonClosePath, cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP, sideOrientation: sideOrientation, instance: instance, updatable: updatable }; return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene); }; /** * Creates lathe mesh. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe. * Please consider using the same method from the MeshBuilder class instead. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero. * The parameter `radius` (positive float, default 1) is the radius value of the lathe. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) { var options = { shape: shape, radius: radius, tessellation: tessellation, sideOrientation: sideOrientation, updatable: updatable }; return BABYLON.MeshBuilder.CreateLathe(name, options, scene); }; /** * Creates a plane mesh. * Please consider using the same method from the MeshBuilder class instead. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1). * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) { var options = { size: size, width: size, height: size, sideOrientation: sideOrientation, updatable: updatable }; return BABYLON.MeshBuilder.CreatePlane(name, options, scene); }; /** * Creates a ground mesh. * Please consider using the same method from the MeshBuilder class instead. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) { var options = { width: width, height: height, subdivisions: subdivisions, updatable: updatable }; return BABYLON.MeshBuilder.CreateGround(name, options, scene); }; /** * Creates a tiled ground mesh. * Please consider using the same method from the MeshBuilder class instead. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the * numbers of subdivisions on the ground width and height. Each subdivision is called a tile. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the * numbers of subdivisions on the ground width and height of each tile. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) { var options = { xmin: xmin, zmin: zmin, xmax: xmax, zmax: zmax, subdivisions: subdivisions, precision: precision, updatable: updatable }; return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene); }; /** * Creates a ground mesh from a height map. * tuto : http://doc.babylonjs.com/babylon101/height_map * Please consider using the same method from the MeshBuilder class instead. * The parameter `url` sets the URL of the height map image resource. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time). * This function is passed the newly built mesh : * ```javascript * function(mesh) { // do things * return; } * ``` * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) { var options = { width: width, height: height, subdivisions: subdivisions, minHeight: minHeight, maxHeight: maxHeight, updatable: updatable, onReady: onReady }; return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene); }; /** * Creates a tube mesh. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters. * Please consider using the same method from the MeshBuilder class instead. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube. * The parameter `radius` (positive float, default 1) sets the tube radius size. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. * It must return a radius value (positive float) : * ```javascript * var radiusFunction = function(i, distance) { * // do things * return radius; } * ``` * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) { var options = { path: path, radius: radius, tessellation: tessellation, radiusFunction: radiusFunction, arc: 1, cap: cap, updatable: updatable, sideOrientation: sideOrientation, instance: instance }; return BABYLON.MeshBuilder.CreateTube(name, options, scene); }; /** * Creates a polyhedron mesh. * Please consider using the same method from the MeshBuilder class instead. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial * to choose the wanted type. * The parameter `size` (positive float, default 1) sets the polygon size. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value). * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`). * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ Mesh.CreatePolyhedron = function (name, options, scene) { return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene); }; /** * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided. * Please consider using the same method from the MeshBuilder class instead. * The parameter `radius` sets the radius size (float) of the icosphere (default 1). * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`). * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. */ Mesh.CreateIcoSphere = function (name, options, scene) { return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene); }; /** * Creates a decal mesh. * Please consider using the same method from the MeshBuilder class instead. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal. */ Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) { var options = { position: position, normal: normal, size: size, angle: angle }; return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options); }; // Skeletons /** * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh. */ Mesh.prototype.setPositionsForCPUSkinning = function () { if (!this._sourcePositions) { var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind); if (!source) { return this._sourcePositions; } this._sourcePositions = new Float32Array(source); if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) { this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true); } } return this._sourcePositions; }; /** * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh. */ Mesh.prototype.setNormalsForCPUSkinning = function () { if (!this._sourceNormals) { var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind); if (!source) { return this._sourceNormals; } this._sourceNormals = new Float32Array(source); if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) { this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true); } } return this._sourceNormals; }; /** * Updates the vertex buffer by applying transformation from the bones. * Returns the Mesh. * * @param {skeleton} skeleton to apply */ Mesh.prototype.applySkeleton = function (skeleton) { if (!this.geometry) { return this; } if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) { return this; } this.geometry._softwareSkinningRenderId = this.getScene().getRenderId(); if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) { return this; } if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) { return this; } if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) { return this; } if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) { return this; } if (!this._sourcePositions) { var submeshes = this.subMeshes.slice(); this.setPositionsForCPUSkinning(); this.subMeshes = submeshes; } if (!this._sourceNormals) { this.setNormalsForCPUSkinning(); } // positionsData checks for not being Float32Array will only pass at most once var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind); if (!positionsData) { return this; } if (!(positionsData instanceof Float32Array)) { positionsData = new Float32Array(positionsData); } // normalsData checks for not being Float32Array will only pass at most once var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind); if (!normalsData) { return this; } if (!(normalsData instanceof Float32Array)) { normalsData = new Float32Array(normalsData); } var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind); var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind); if (!matricesWeightsData || !matricesIndicesData) { return this; } var needExtras = this.numBoneInfluencers > 4; var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null; var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null; var skeletonMatrices = skeleton.getTransformMatrices(this); var tempVector3 = BABYLON.Vector3.Zero(); var finalMatrix = new BABYLON.Matrix(); var tempMatrix = new BABYLON.Matrix(); var matWeightIdx = 0; var inf; for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) { var weight; for (inf = 0; inf < 4; inf++) { weight = matricesWeightsData[matWeightIdx + inf]; if (weight > 0) { BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix); finalMatrix.addToSelf(tempMatrix); } else break; } if (needExtras) { for (inf = 0; inf < 4; inf++) { weight = matricesWeightsExtraData[matWeightIdx + inf]; if (weight > 0) { BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix); finalMatrix.addToSelf(tempMatrix); } else break; } } BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3); tempVector3.toArray(positionsData, index); BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3); tempVector3.toArray(normalsData, index); finalMatrix.reset(); } this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData); this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData); return this; }; // Tools /** * Returns an object `{min:` Vector3`, max:` Vector3`}` * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system */ Mesh.MinMax = function (meshes) { var minVector = null; var maxVector = null; meshes.forEach(function (mesh, index, array) { var boundingInfo = mesh.getBoundingInfo(); var boundingBox = boundingInfo.boundingBox; if (!minVector || !maxVector) { minVector = boundingBox.minimumWorld; maxVector = boundingBox.maximumWorld; } else { minVector.minimizeInPlace(boundingBox.minimumWorld); maxVector.maximizeInPlace(boundingBox.maximumWorld); } }); if (!minVector || !maxVector) { return { min: BABYLON.Vector3.Zero(), max: BABYLON.Vector3.Zero() }; } return { min: minVector, max: maxVector }; }; /** * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array. */ Mesh.Center = function (meshesOrMinMaxVector) { var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector; return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max); }; /** * Merge the array of meshes into a single mesh for performance reasons. * @param {Array} meshes - The vertices source. They should all be of the same material. Entries can empty * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source. */ Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) { if (disposeSource === void 0) { disposeSource = true; } var index; if (!allow32BitsIndices) { var totalVertices = 0; // Counting vertices for (index = 0; index < meshes.length; index++) { if (meshes[index]) { totalVertices += meshes[index].getTotalVertices(); if (totalVertices > 65536) { BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"); return null; } } } } // Merge var vertexData = null; var otherVertexData; var indiceArray = new Array(); var source = null; for (index = 0; index < meshes.length; index++) { if (meshes[index]) { meshes[index].computeWorldMatrix(true); otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true); otherVertexData.transform(meshes[index].getWorldMatrix()); if (vertexData) { vertexData.merge(otherVertexData); } else { vertexData = otherVertexData; source = meshes[index]; } if (subdivideWithSubMeshes) { indiceArray.push(meshes[index].getTotalIndices()); } } } source = source; if (!meshSubclass) { meshSubclass = new Mesh(source.name + "_merged", source.getScene()); } vertexData.applyToMesh(meshSubclass); // Setting properties meshSubclass.material = source.material; meshSubclass.checkCollisions = source.checkCollisions; // Cleaning if (disposeSource) { for (index = 0; index < meshes.length; index++) { if (meshes[index]) { meshes[index].dispose(); } } } // Subdivide if (subdivideWithSubMeshes) { //-- removal of global submesh meshSubclass.releaseSubMeshes(); index = 0; var offset = 0; //-- apply subdivision according to index table while (index < indiceArray.length) { BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass); offset += indiceArray[index]; index++; } } return meshSubclass; }; // Consts Mesh._FRONTSIDE = 0; Mesh._BACKSIDE = 1; Mesh._DOUBLESIDE = 2; Mesh._DEFAULTSIDE = 0; Mesh._NO_CAP = 0; Mesh._CAP_START = 1; Mesh._CAP_END = 2; Mesh._CAP_ALL = 3; return Mesh; }(BABYLON.AbstractMesh)); BABYLON.Mesh = Mesh; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.mesh.js.map var BABYLON; (function (BABYLON) { var BaseSubMesh = /** @class */ (function () { function BaseSubMesh() { } Object.defineProperty(BaseSubMesh.prototype, "effect", { get: function () { return this._materialEffect; }, enumerable: true, configurable: true }); BaseSubMesh.prototype.setEffect = function (effect, defines) { if (defines === void 0) { defines = null; } if (this._materialEffect === effect) { if (!effect) { this._materialDefines = null; } return; } this._materialDefines = defines; this._materialEffect = effect; }; return BaseSubMesh; }()); BABYLON.BaseSubMesh = BaseSubMesh; var SubMesh = /** @class */ (function (_super) { __extends(SubMesh, _super); function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) { if (createBoundingBox === void 0) { createBoundingBox = true; } var _this = _super.call(this) || this; _this.materialIndex = materialIndex; _this.verticesStart = verticesStart; _this.verticesCount = verticesCount; _this.indexStart = indexStart; _this.indexCount = indexCount; _this._renderId = 0; _this._mesh = mesh; _this._renderingMesh = renderingMesh || mesh; mesh.subMeshes.push(_this); _this._trianglePlanes = []; _this._id = mesh.subMeshes.length - 1; if (createBoundingBox) { _this.refreshBoundingInfo(); mesh.computeWorldMatrix(true); } return _this; } SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) { if (createBoundingBox === void 0) { createBoundingBox = true; } return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox); }; Object.defineProperty(SubMesh.prototype, "IsGlobal", { get: function () { return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices()); }, enumerable: true, configurable: true }); /** * Returns the submesh BoudingInfo object. */ SubMesh.prototype.getBoundingInfo = function () { if (this.IsGlobal) { return this._mesh.getBoundingInfo(); } return this._boundingInfo; }; /** * Sets the submesh BoundingInfo. * Return the SubMesh. */ SubMesh.prototype.setBoundingInfo = function (boundingInfo) { this._boundingInfo = boundingInfo; return this; }; /** * Returns the mesh of the current submesh. */ SubMesh.prototype.getMesh = function () { return this._mesh; }; /** * Returns the rendering mesh of the submesh. */ SubMesh.prototype.getRenderingMesh = function () { return this._renderingMesh; }; /** * Returns the submesh material. */ SubMesh.prototype.getMaterial = function () { var rootMaterial = this._renderingMesh.material; if (rootMaterial === null || rootMaterial === undefined) { return this._mesh.getScene().defaultMaterial; } else if (rootMaterial.getSubMaterial) { var multiMaterial = rootMaterial; var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex); if (this._currentMaterial !== effectiveMaterial) { this._currentMaterial = effectiveMaterial; this._materialDefines = null; } return effectiveMaterial; } return rootMaterial; }; // Methods /** * Sets a new updated BoundingInfo object to the submesh. * Returns the SubMesh. */ SubMesh.prototype.refreshBoundingInfo = function () { this._lastColliderWorldVertices = null; if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) { return this; } var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind); if (!data) { this._boundingInfo = this._mesh.getBoundingInfo(); return this; } var indices = this._renderingMesh.getIndices(); var extend; //is this the only submesh? if (this.indexStart === 0 && this.indexCount === indices.length) { var boundingInfo = this._renderingMesh.getBoundingInfo(); //the rendering mesh's bounding info can be used, it is the standard submesh for all indices. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() }; } else { extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias); } this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum); return this; }; SubMesh.prototype._checkCollision = function (collider) { var boundingInfo = this.getBoundingInfo(); return boundingInfo._checkCollision(collider); }; /** * Updates the submesh BoundingInfo. * Returns the Submesh. */ SubMesh.prototype.updateBoundingInfo = function (world) { var boundingInfo = this.getBoundingInfo(); if (!boundingInfo) { this.refreshBoundingInfo(); boundingInfo = this.getBoundingInfo(); } boundingInfo.update(world); return this; }; /** * True is the submesh bounding box intersects the frustum defined by the passed array of planes. * Boolean returned. */ SubMesh.prototype.isInFrustum = function (frustumPlanes) { var boundingInfo = this.getBoundingInfo(); if (!boundingInfo) { return false; } return boundingInfo.isInFrustum(frustumPlanes); }; /** * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes. * Boolean returned. */ SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) { var boundingInfo = this.getBoundingInfo(); if (!boundingInfo) { return false; } return boundingInfo.isCompletelyInFrustum(frustumPlanes); }; /** * Renders the submesh. * Returns it. */ SubMesh.prototype.render = function (enableAlphaMode) { this._renderingMesh.render(this, enableAlphaMode); return this; }; /** * Returns a new Index Buffer. * Type returned : WebGLBuffer. */ SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) { if (!this._linesIndexBuffer) { var linesIndices = []; for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) { linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]); } this._linesIndexBuffer = engine.createIndexBuffer(linesIndices); this.linesIndexCount = linesIndices.length; } return this._linesIndexBuffer; }; /** * True is the passed Ray intersects the submesh bounding box. * Boolean returned. */ SubMesh.prototype.canIntersects = function (ray) { var boundingInfo = this.getBoundingInfo(); if (!boundingInfo) { return false; } return ray.intersectsBox(boundingInfo.boundingBox); }; /** * Returns an object IntersectionInfo. */ SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) { var intersectInfo = null; var material = this.getMaterial(); if (!material) { return null; } switch (material.fillMode) { case BABYLON.Material.PointListDrawMode: case BABYLON.Material.LineListDrawMode: case BABYLON.Material.LineLoopDrawMode: case BABYLON.Material.LineStripDrawMode: case BABYLON.Material.TriangleFanDrawMode: case BABYLON.Material.TriangleStripDrawMode: return null; } // LineMesh first as it's also a Mesh... if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) { var lineMesh = this._mesh; // Line test for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) { var p0 = positions[indices[index]]; var p1 = positions[indices[index + 1]]; var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold); if (length < 0) { continue; } if (fastCheck || !intersectInfo || length < intersectInfo.distance) { intersectInfo = new BABYLON.IntersectionInfo(null, null, length); if (fastCheck) { break; } } } } else { // Triangles test for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) { var p0 = positions[indices[index]]; var p1 = positions[indices[index + 1]]; var p2 = positions[indices[index + 2]]; var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2); if (currentIntersectInfo) { if (currentIntersectInfo.distance < 0) { continue; } if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) { intersectInfo = currentIntersectInfo; intersectInfo.faceId = index / 3; if (fastCheck) { break; } } } } } return intersectInfo; }; SubMesh.prototype._rebuild = function () { if (this._linesIndexBuffer) { this._linesIndexBuffer = null; } }; // Clone /** * Creates a new Submesh from the passed Mesh. */ SubMesh.prototype.clone = function (newMesh, newRenderingMesh) { var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false); if (!this.IsGlobal) { var boundingInfo = this.getBoundingInfo(); if (!boundingInfo) { return result; } result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum); } return result; }; // Dispose /** * Disposes the Submesh. * Returns nothing. */ SubMesh.prototype.dispose = function () { if (this._linesIndexBuffer) { this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer); this._linesIndexBuffer = null; } // Remove from mesh var index = this._mesh.subMeshes.indexOf(this); this._mesh.subMeshes.splice(index, 1); }; // Statics /** * Creates a new Submesh from the passed parameters : * - materialIndex (integer) : the index of the main mesh material. * - startIndex (integer) : the index where to start the copy in the mesh indices array. * - indexCount (integer) : the number of indices to copy then from the startIndex. * - mesh (Mesh) : the main mesh to create the submesh from. * - renderingMesh (optional Mesh) : rendering mesh. */ SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) { var minVertexIndex = Number.MAX_VALUE; var maxVertexIndex = -Number.MAX_VALUE; renderingMesh = (renderingMesh || mesh); var indices = renderingMesh.getIndices(); for (var index = startIndex; index < startIndex + indexCount; index++) { var vertexIndex = indices[index]; if (vertexIndex < minVertexIndex) minVertexIndex = vertexIndex; if (vertexIndex > maxVertexIndex) maxVertexIndex = vertexIndex; } return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh); }; return SubMesh; }(BaseSubMesh)); BABYLON.SubMesh = SubMesh; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.subMesh.js.map var __assign = (this && this.__assign) || Object.assign || function(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; }; var BABYLON; (function (BABYLON) { /** * 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; }()); BABYLON.MaterialDefines = MaterialDefines; /** * 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) { /** * 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; /** * Specifies if the effect should be stored on sub meshes */ this.storeEffectOnSubMeshes = false; /** * An event triggered when the material is disposed */ this.onDisposeObservable = new BABYLON.Observable(); /** * An event triggered when the material is bound */ this.onBindObservable = new BABYLON.Observable(); /** * An event triggered when the material is unbound */ this.onUnBindObservable = new BABYLON.Observable(); /** * Stores the value of the alpha mode */ this._alphaMode = BABYLON.Engine.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; /** * Specifies if the material was previously ready */ this._wasPreviouslyReady = false; /** * Stores the fill mode state */ this._fillMode = Material.TriangleFillMode; this.name = name; this.id = name || BABYLON.Tools.RandomId(); this._scene = scene || BABYLON.Engine.LastCreatedScene; this.uniqueId = this._scene.getUniqueId(); if (this._scene.useRightHandedSystem) { this.sideOrientation = Material.ClockWiseSideOrientation; } else { this.sideOrientation = Material.CounterClockWiseSideOrientation; } this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine()); this._useUBO = this.getScene().getEngine().supportsUniformBuffers; if (!doNotAdd) { this._scene.materials.push(this); } } Object.defineProperty(Material, "TriangleFillMode", { /** * Returns the triangle fill mode */ get: function () { return Material._TriangleFillMode; }, enumerable: true, configurable: true }); Object.defineProperty(Material, "WireFrameFillMode", { /** * Returns the wireframe mode */ get: function () { return Material._WireFrameFillMode; }, enumerable: true, configurable: true }); Object.defineProperty(Material, "PointFillMode", { /** * Returns the point fill mode */ get: function () { return Material._PointFillMode; }, enumerable: true, configurable: true }); Object.defineProperty(Material, "PointListDrawMode", { /** * Returns the point list draw mode */ get: function () { return Material._PointListDrawMode; }, enumerable: true, configurable: true }); Object.defineProperty(Material, "LineListDrawMode", { /** * Returns the line list draw mode */ get: function () { return Material._LineListDrawMode; }, enumerable: true, configurable: true }); Object.defineProperty(Material, "LineLoopDrawMode", { /** * Returns the line loop draw mode */ get: function () { return Material._LineLoopDrawMode; }, enumerable: true, configurable: true }); Object.defineProperty(Material, "LineStripDrawMode", { /** * Returns the line strip draw mode */ get: function () { return Material._LineStripDrawMode; }, enumerable: true, configurable: true }); Object.defineProperty(Material, "TriangleStripDrawMode", { /** * Returns the triangle strip draw mode */ get: function () { return Material._TriangleStripDrawMode; }, enumerable: true, configurable: true }); Object.defineProperty(Material, "TriangleFanDrawMode", { /** * Returns the triangle fan draw mode */ get: function () { return Material._TriangleFanDrawMode; }, enumerable: true, configurable: true }); Object.defineProperty(Material, "ClockWiseSideOrientation", { /** * Returns the clock-wise side orientation */ get: function () { return Material._ClockWiseSideOrientation; }, enumerable: true, configurable: true }); Object.defineProperty(Material, "CounterClockWiseSideOrientation", { /** * Returns the counter clock-wise side orientation */ get: function () { return Material._CounterClockWiseSideOrientation; }, enumerable: true, configurable: true }); Object.defineProperty(Material, "TextureDirtyFlag", { /** * Returns the dirty texture flag value */ get: function () { return Material._TextureDirtyFlag; }, enumerable: true, configurable: true }); Object.defineProperty(Material, "LightDirtyFlag", { /** * Returns the dirty light flag value */ get: function () { return Material._LightDirtyFlag; }, enumerable: true, configurable: true }); Object.defineProperty(Material, "FresnelDirtyFlag", { /** * Returns the dirty fresnel flag value */ get: function () { return Material._FresnelDirtyFlag; }, enumerable: true, configurable: true }); Object.defineProperty(Material, "AttributesDirtyFlag", { /** * Returns the dirty attributes flag value */ get: function () { return Material._AttributesDirtyFlag; }, enumerable: true, configurable: true }); Object.defineProperty(Material, "MiscDirtyFlag", { /** * Returns the dirty misc flag value */ get: function () { return Material._MiscDirtyFlag; }, enumerable: true, configurable: true }); 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, "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, "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, "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 (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 () { 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 result = new Array(); for (var index = 0; index < this._scene.meshes.length; index++) { var mesh = this._scene.meshes[index]; if (mesh.material === this) { result.push(mesh); } } return result; }; /** * 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 = __assign({ clipPlane: false }, options); var subMesh = new BABYLON.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 BABYLON.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(mesh)) { 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 (flag & Material.TextureDirtyFlag) { this._markAllSubMeshesAsTexturesDirty(); } if (flag & Material.LightDirtyFlag) { this._markAllSubMeshesAsLightsDirty(); } if (flag & Material.FresnelDirtyFlag) { this._markAllSubMeshesAsFresnelDirty(); } if (flag & Material.AttributesDirtyFlag) { this._markAllSubMeshesAsAttributesDirty(); } if (flag & Material.MiscDirtyFlag) { this._markAllSubMeshesAsMiscDirty(); } 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) { for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) { var mesh = _a[_i]; if (!mesh.subMeshes) { continue; } for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) { var subMesh = _c[_b]; 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(function (defines) { return defines.markAsImageProcessingDirty(); }); }; /** * Indicates that textures need to be re-calculated for all submeshes */ Material.prototype._markAllSubMeshesAsTexturesDirty = function () { this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); }); }; /** * Indicates that fresnel needs to be re-calculated for all submeshes */ Material.prototype._markAllSubMeshesAsFresnelDirty = function () { this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); }); }; /** * Indicates that fresnel and misc need to be re-calculated for all submeshes */ Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () { this._markAllSubMeshesAsDirty(function (defines) { defines.markAsFresnelDirty(); defines.markAsMiscDirty(); }); }; /** * Indicates that lights need to be re-calculated for all submeshes */ Material.prototype._markAllSubMeshesAsLightsDirty = function () { this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); }); }; /** * Indicates that attributes need to be re-calculated for all submeshes */ Material.prototype._markAllSubMeshesAsAttributesDirty = function () { this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); }); }; /** * Indicates that misc needs to be re-calculated for all submeshes */ Material.prototype._markAllSubMeshesAsMiscDirty = function () { this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); }); }; /** * Indicates that textures and misc need to be re-calculated for all submeshes */ Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () { this._markAllSubMeshesAsDirty(function (defines) { defines.markAsTexturesDirty(); defines.markAsMiscDirty(); }); }; /** * Disposes the material * @param forceDisposeEffect specifies if effects should be forcefully disposed * @param forceDisposeTextures specifies if textures should be forcefully disposed */ Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) { // Animations this.getScene().stopAnimation(this); this.getScene().freeProcessedMaterials(); // Remove from scene var index = this._scene.materials.indexOf(this); if (index >= 0) { this._scene.materials.splice(index, 1); } // Remove from meshes for (index = 0; index < this._scene.meshes.length; index++) { var mesh = this._scene.meshes[index]; if (mesh.material === this) { mesh.material = null; if (mesh.geometry) { var geometry = (mesh.geometry); 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) { this._scene.getEngine()._releaseEffect(subMesh._materialEffect); } } } else { geometry._releaseVertexArrayObject(this._effect); } } } } 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) { this._scene.getEngine()._releaseEffect(this._effect); } this._effect = null; } // Callback this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); this.onBindObservable.clear(); this.onUnBindObservable.clear(); }; /** * Serializes this material * @returns the serialized material object */ Material.prototype.serialize = function () { return BABYLON.SerializationHelper.Serialize(this); }; /** * Creates a MultiMaterial from parsed MultiMaterial data. * @param parsedMultiMaterial defines parsed MultiMaterial data. * @param scene defines the hosting scene * @returns a new MultiMaterial */ Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) { var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene); multiMaterial.id = parsedMultiMaterial.id; if (BABYLON.Tags) { BABYLON.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; }; /** * 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") { return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl); } if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) { parsedMaterial.customType = "BABYLON.LegacyPBRMaterial"; if (!BABYLON.LegacyPBRMaterial) { BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."); return; } } var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType); return materialType.Parse(parsedMaterial, scene, rootUrl); }; // Triangle views Material._TriangleFillMode = 0; Material._WireFrameFillMode = 1; Material._PointFillMode = 2; // Draw modes Material._PointListDrawMode = 3; Material._LineListDrawMode = 4; Material._LineLoopDrawMode = 5; Material._LineStripDrawMode = 6; Material._TriangleStripDrawMode = 7; Material._TriangleFanDrawMode = 8; /** * Stores the clock-wise side orientation */ Material._ClockWiseSideOrientation = 0; /** * Stores the counter clock-wise side orientation */ Material._CounterClockWiseSideOrientation = 1; /** * The dirty texture flag value */ Material._TextureDirtyFlag = 1; /** * The dirty light flag value */ Material._LightDirtyFlag = 2; /** * The dirty fresnel flag value */ Material._FresnelDirtyFlag = 4; /** * The dirty attribute flag value */ Material._AttributesDirtyFlag = 8; /** * The dirty misc flag value */ Material._MiscDirtyFlag = 16; __decorate([ BABYLON.serialize() ], Material.prototype, "id", void 0); __decorate([ BABYLON.serialize() ], Material.prototype, "uniqueId", void 0); __decorate([ BABYLON.serialize() ], Material.prototype, "name", void 0); __decorate([ BABYLON.serialize() ], Material.prototype, "checkReadyOnEveryCall", void 0); __decorate([ BABYLON.serialize() ], Material.prototype, "checkReadyOnlyOnce", void 0); __decorate([ BABYLON.serialize() ], Material.prototype, "state", void 0); __decorate([ BABYLON.serialize("alpha") ], Material.prototype, "_alpha", void 0); __decorate([ BABYLON.serialize("backFaceCulling") ], Material.prototype, "_backFaceCulling", void 0); __decorate([ BABYLON.serialize() ], Material.prototype, "sideOrientation", void 0); __decorate([ BABYLON.serialize("alphaMode") ], Material.prototype, "_alphaMode", void 0); __decorate([ BABYLON.serialize() ], Material.prototype, "_needDepthPrePass", void 0); __decorate([ BABYLON.serialize() ], Material.prototype, "disableDepthWrite", void 0); __decorate([ BABYLON.serialize() ], Material.prototype, "forceDepthWrite", void 0); __decorate([ BABYLON.serialize() ], Material.prototype, "separateCullingPass", void 0); __decorate([ BABYLON.serialize("fogEnabled") ], Material.prototype, "_fogEnabled", void 0); __decorate([ BABYLON.serialize() ], Material.prototype, "pointSize", void 0); __decorate([ BABYLON.serialize() ], Material.prototype, "zOffset", void 0); __decorate([ BABYLON.serialize() ], Material.prototype, "wireframe", null); __decorate([ BABYLON.serialize() ], Material.prototype, "pointsCloud", null); __decorate([ BABYLON.serialize() ], Material.prototype, "fillMode", null); return Material; }()); BABYLON.Material = Material; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.material.js.map var BABYLON; (function (BABYLON) { var UniformBuffer = /** @class */ (function () { /** * Uniform buffer objects. * * Handles blocks of uniform on the GPU. * * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls. * * For more information, please refer to : * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object */ function UniformBuffer(engine, data, dynamic) { this._engine = engine; this._noUBO = !engine.supportsUniformBuffers; this._dynamic = dynamic; this._data = data || []; this._uniformLocations = {}; this._uniformSizes = {}; this._uniformLocationPointer = 0; this._needSync = false; if (this._noUBO) { this.updateMatrix3x3 = this._updateMatrix3x3ForEffect; this.updateMatrix2x2 = this._updateMatrix2x2ForEffect; this.updateFloat = this._updateFloatForEffect; this.updateFloat2 = this._updateFloat2ForEffect; this.updateFloat3 = this._updateFloat3ForEffect; this.updateFloat4 = this._updateFloat4ForEffect; this.updateMatrix = this._updateMatrixForEffect; this.updateVector3 = this._updateVector3ForEffect; this.updateVector4 = this._updateVector4ForEffect; this.updateColor3 = this._updateColor3ForEffect; this.updateColor4 = this._updateColor4ForEffect; } else { this._engine._uniformBuffers.push(this); this.updateMatrix3x3 = this._updateMatrix3x3ForUniform; this.updateMatrix2x2 = this._updateMatrix2x2ForUniform; this.updateFloat = this._updateFloatForUniform; this.updateFloat2 = this._updateFloat2ForUniform; this.updateFloat3 = this._updateFloat3ForUniform; this.updateFloat4 = this._updateFloat4ForUniform; this.updateMatrix = this._updateMatrixForUniform; this.updateVector3 = this._updateVector3ForUniform; this.updateVector4 = this._updateVector4ForUniform; this.updateColor3 = this._updateColor3ForUniform; this.updateColor4 = this._updateColor4ForUniform; } } Object.defineProperty(UniformBuffer.prototype, "useUbo", { // Properties /** * Indicates if the buffer is using the WebGL2 UBO implementation, * or just falling back on setUniformXXX calls. */ get: function () { return !this._noUBO; }, enumerable: true, configurable: true }); Object.defineProperty(UniformBuffer.prototype, "isSync", { /** * Indicates if the WebGL underlying uniform buffer is in sync * with the javascript cache data. */ get: function () { return !this._needSync; }, enumerable: true, configurable: true }); /** * Indicates if the WebGL underlying uniform buffer is dynamic. * Also, a dynamic UniformBuffer will disable cache verification and always * update the underlying WebGL uniform buffer to the GPU. */ UniformBuffer.prototype.isDynamic = function () { return this._dynamic !== undefined; }; /** * The data cache on JS side. */ UniformBuffer.prototype.getData = function () { return this._bufferData; }; /** * The underlying WebGL Uniform buffer. */ UniformBuffer.prototype.getBuffer = function () { return this._buffer; }; /** * std140 layout specifies how to align data within an UBO structure. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159 * for specs. */ UniformBuffer.prototype._fillAlignment = function (size) { // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components // and 4x4 matrices // TODO : change if other types are used var alignment; if (size <= 2) { alignment = size; } else { alignment = 4; } if ((this._uniformLocationPointer % alignment) !== 0) { var oldPointer = this._uniformLocationPointer; this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment); var diff = this._uniformLocationPointer - oldPointer; for (var i = 0; i < diff; i++) { this._data.push(0); } } }; /** * Adds an uniform in the buffer. * Warning : the subsequents calls of this function must be in the same order as declared in the shader * for the layout to be correct ! * @param {string} name Name of the uniform, as used in the uniform block in the shader. * @param {number|number[]} size Data size, or data directly. */ UniformBuffer.prototype.addUniform = function (name, size) { if (this._noUBO) { return; } if (this._uniformLocations[name] !== undefined) { // Already existing uniform return; } // This function must be called in the order of the shader layout ! // size can be the size of the uniform, or data directly var data; if (size instanceof Array) { data = size; size = data.length; } else { size = size; data = []; // Fill with zeros for (var i = 0; i < size; i++) { data.push(0); } } this._fillAlignment(size); this._uniformSizes[name] = size; this._uniformLocations[name] = this._uniformLocationPointer; this._uniformLocationPointer += size; for (var i = 0; i < size; i++) { this._data.push(data[i]); } this._needSync = true; }; /** * Wrapper for addUniform. * @param {string} name Name of the uniform, as used in the uniform block in the shader. * @param {Matrix} mat A 4x4 matrix. */ UniformBuffer.prototype.addMatrix = function (name, mat) { this.addUniform(name, Array.prototype.slice.call(mat.toArray())); }; /** * Wrapper for addUniform. * @param {string} name Name of the uniform, as used in the uniform block in the shader. * @param {number} x * @param {number} y */ UniformBuffer.prototype.addFloat2 = function (name, x, y) { var temp = [x, y]; this.addUniform(name, temp); }; /** * Wrapper for addUniform. * @param {string} name Name of the uniform, as used in the uniform block in the shader. * @param {number} x * @param {number} y * @param {number} z */ UniformBuffer.prototype.addFloat3 = function (name, x, y, z) { var temp = [x, y, z]; this.addUniform(name, temp); }; /** * Wrapper for addUniform. * @param {string} name Name of the uniform, as used in the uniform block in the shader. * @param {Color3} color */ UniformBuffer.prototype.addColor3 = function (name, color) { var temp = new Array(); color.toArray(temp); this.addUniform(name, temp); }; /** * Wrapper for addUniform. * @param {string} name Name of the uniform, as used in the uniform block in the shader. * @param {Color3} color * @param {number} alpha */ UniformBuffer.prototype.addColor4 = function (name, color, alpha) { var temp = new Array(); color.toArray(temp); temp.push(alpha); this.addUniform(name, temp); }; /** * Wrapper for addUniform. * @param {string} name Name of the uniform, as used in the uniform block in the shader. * @param {Vector3} vector */ UniformBuffer.prototype.addVector3 = function (name, vector) { var temp = new Array(); vector.toArray(temp); this.addUniform(name, temp); }; /** * Wrapper for addUniform. * @param {string} name Name of the uniform, as used in the uniform block in the shader. */ UniformBuffer.prototype.addMatrix3x3 = function (name) { this.addUniform(name, 12); }; /** * Wrapper for addUniform. * @param {string} name Name of the uniform, as used in the uniform block in the shader. */ UniformBuffer.prototype.addMatrix2x2 = function (name) { this.addUniform(name, 8); }; /** * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`. */ UniformBuffer.prototype.create = function () { if (this._noUBO) { return; } if (this._buffer) { return; // nothing to do } // See spec, alignment must be filled as a vec4 this._fillAlignment(4); this._bufferData = new Float32Array(this._data); this._rebuild(); this._needSync = true; }; UniformBuffer.prototype._rebuild = function () { if (this._noUBO) { return; } if (this._dynamic) { this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData); } else { this._buffer = this._engine.createUniformBuffer(this._bufferData); } }; /** * Updates the WebGL Uniform Buffer on the GPU. * If the `dynamic` flag is set to true, no cache comparison is done. * Otherwise, the buffer will be updated only if the cache differs. */ UniformBuffer.prototype.update = function () { if (!this._buffer) { this.create(); return; } if (!this._dynamic && !this._needSync) { return; } this._engine.updateUniformBuffer(this._buffer, this._bufferData); this._needSync = false; }; /** * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader. * @param {number[]|Float32Array} data Flattened data * @param {number} size Size of the data. */ UniformBuffer.prototype.updateUniform = function (uniformName, data, size) { var location = this._uniformLocations[uniformName]; if (location === undefined) { if (this._buffer) { // Cannot add an uniform if the buffer is already created BABYLON.Tools.Error("Cannot add an uniform after UBO has been created."); return; } this.addUniform(uniformName, size); location = this._uniformLocations[uniformName]; } if (!this._buffer) { this.create(); } if (!this._dynamic) { // Cache for static uniform buffers var changed = false; for (var i = 0; i < size; i++) { if (this._bufferData[location + i] !== data[i]) { changed = true; this._bufferData[location + i] = data[i]; } } this._needSync = this._needSync || changed; } else { // No cache for dynamic for (var i = 0; i < size; i++) { this._bufferData[location + i] = data[i]; } } }; // Update methods UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) { // To match std140, matrix must be realigned for (var i = 0; i < 3; i++) { UniformBuffer._tempBuffer[i * 4] = matrix[i * 3]; UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1]; UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2]; UniformBuffer._tempBuffer[i * 4 + 3] = 0.0; } this.updateUniform(name, UniformBuffer._tempBuffer, 12); }; UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) { this._currentEffect.setMatrix3x3(name, matrix); }; UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) { this._currentEffect.setMatrix2x2(name, matrix); }; UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) { // To match std140, matrix must be realigned for (var i = 0; i < 2; i++) { UniformBuffer._tempBuffer[i * 4] = matrix[i * 2]; UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1]; UniformBuffer._tempBuffer[i * 4 + 2] = 0.0; UniformBuffer._tempBuffer[i * 4 + 3] = 0.0; } this.updateUniform(name, UniformBuffer._tempBuffer, 8); }; UniformBuffer.prototype._updateFloatForEffect = function (name, x) { this._currentEffect.setFloat(name, x); }; UniformBuffer.prototype._updateFloatForUniform = function (name, x) { UniformBuffer._tempBuffer[0] = x; this.updateUniform(name, UniformBuffer._tempBuffer, 1); }; UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) { if (suffix === void 0) { suffix = ""; } this._currentEffect.setFloat2(name + suffix, x, y); }; UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) { if (suffix === void 0) { suffix = ""; } UniformBuffer._tempBuffer[0] = x; UniformBuffer._tempBuffer[1] = y; this.updateUniform(name, UniformBuffer._tempBuffer, 2); }; UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) { if (suffix === void 0) { suffix = ""; } this._currentEffect.setFloat3(name + suffix, x, y, z); }; UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) { if (suffix === void 0) { suffix = ""; } UniformBuffer._tempBuffer[0] = x; UniformBuffer._tempBuffer[1] = y; UniformBuffer._tempBuffer[2] = z; this.updateUniform(name, UniformBuffer._tempBuffer, 3); }; UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) { if (suffix === void 0) { suffix = ""; } this._currentEffect.setFloat4(name + suffix, x, y, z, w); }; UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) { if (suffix === void 0) { suffix = ""; } UniformBuffer._tempBuffer[0] = x; UniformBuffer._tempBuffer[1] = y; UniformBuffer._tempBuffer[2] = z; UniformBuffer._tempBuffer[3] = w; this.updateUniform(name, UniformBuffer._tempBuffer, 4); }; UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) { this._currentEffect.setMatrix(name, mat); }; UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) { this.updateUniform(name, mat.toArray(), 16); }; UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) { this._currentEffect.setVector3(name, vector); }; UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) { vector.toArray(UniformBuffer._tempBuffer); this.updateUniform(name, UniformBuffer._tempBuffer, 3); }; UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) { this._currentEffect.setVector4(name, vector); }; UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) { vector.toArray(UniformBuffer._tempBuffer); this.updateUniform(name, UniformBuffer._tempBuffer, 4); }; UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) { if (suffix === void 0) { suffix = ""; } this._currentEffect.setColor3(name + suffix, color); }; UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) { if (suffix === void 0) { suffix = ""; } color.toArray(UniformBuffer._tempBuffer); this.updateUniform(name, UniformBuffer._tempBuffer, 3); }; UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) { if (suffix === void 0) { suffix = ""; } this._currentEffect.setColor4(name + suffix, color, alpha); }; UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) { if (suffix === void 0) { suffix = ""; } color.toArray(UniformBuffer._tempBuffer); UniformBuffer._tempBuffer[3] = alpha; this.updateUniform(name, UniformBuffer._tempBuffer, 4); }; /** * Sets a sampler uniform on the effect. * @param {string} name Name of the sampler. * @param {Texture} texture */ UniformBuffer.prototype.setTexture = function (name, texture) { this._currentEffect.setTexture(name, texture); }; /** * Directly updates the value of the uniform in the cache AND on the GPU. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader. * @param {number[]|Float32Array} data Flattened data */ UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) { this.updateUniform(uniformName, data, data.length); this.update(); }; /** * Binds this uniform buffer to an effect. * @param {Effect} effect * @param {string} name Name of the uniform block in the shader. */ UniformBuffer.prototype.bindToEffect = function (effect, name) { this._currentEffect = effect; if (this._noUBO || !this._buffer) { return; } effect.bindUniformBuffer(this._buffer, name); }; /** * Disposes the uniform buffer. */ UniformBuffer.prototype.dispose = function () { if (this._noUBO) { return; } var index = this._engine._uniformBuffers.indexOf(this); if (index !== -1) { this._engine._uniformBuffers.splice(index, 1); } if (!this._buffer) { return; } if (this._engine._releaseBuffer(this._buffer)) { this._buffer = null; } }; // Pool for avoiding memory leaks UniformBuffer._MAX_UNIFORM_SIZE = 256; UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE); return UniformBuffer; }()); BABYLON.UniformBuffer = UniformBuffer; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.uniformBuffer.js.map var BABYLON; (function (BABYLON) { /** * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance */ var VertexData = /** @class */ (function () { function VertexData() { } /** * Uses the passed data array to set the set the values for the specified kind of data * @param data a linear array of floating numbers * @param kind the type of data that is being set, eg positions, colors etc */ VertexData.prototype.set = function (data, kind) { switch (kind) { case BABYLON.VertexBuffer.PositionKind: this.positions = data; break; case BABYLON.VertexBuffer.NormalKind: this.normals = data; break; case BABYLON.VertexBuffer.TangentKind: this.tangents = data; break; case BABYLON.VertexBuffer.UVKind: this.uvs = data; break; case BABYLON.VertexBuffer.UV2Kind: this.uvs2 = data; break; case BABYLON.VertexBuffer.UV3Kind: this.uvs3 = data; break; case BABYLON.VertexBuffer.UV4Kind: this.uvs4 = data; break; case BABYLON.VertexBuffer.UV5Kind: this.uvs5 = data; break; case BABYLON.VertexBuffer.UV6Kind: this.uvs6 = data; break; case BABYLON.VertexBuffer.ColorKind: this.colors = data; break; case BABYLON.VertexBuffer.MatricesIndicesKind: this.matricesIndices = data; break; case BABYLON.VertexBuffer.MatricesWeightsKind: this.matricesWeights = data; break; case BABYLON.VertexBuffer.MatricesIndicesExtraKind: this.matricesIndicesExtra = data; break; case BABYLON.VertexBuffer.MatricesWeightsExtraKind: this.matricesWeightsExtra = data; break; } }; /** * Associates the vertexData to the passed Mesh. * Sets it as updatable or not (default `false`) * @param mesh the mesh the vertexData is applied to * @param updatable when used and having the value true allows new data to update the vertexData * @returns the VertexData */ VertexData.prototype.applyToMesh = function (mesh, updatable) { this._applyTo(mesh, updatable); return this; }; /** * Associates the vertexData to the passed Geometry. * Sets it as updatable or not (default `false`) * @param geometry the geometry the vertexData is applied to * @param updatable when used and having the value true allows new data to update the vertexData * @returns VertexData */ VertexData.prototype.applyToGeometry = function (geometry, updatable) { this._applyTo(geometry, updatable); return this; }; /** * Updates the associated mesh * @param mesh the mesh to be updated * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false * @returns VertexData */ VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) { this._update(mesh); return this; }; /** * Updates the associated geometry * @param geometry the geometry to be updated * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false * @returns VertexData. */ VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) { this._update(geometry); return this; }; VertexData.prototype._applyTo = function (meshOrGeometry, updatable) { if (updatable === void 0) { updatable = false; } if (this.positions) { meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable); } if (this.normals) { meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable); } if (this.tangents) { meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable); } if (this.uvs) { meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable); } if (this.uvs2) { meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable); } if (this.uvs3) { meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable); } if (this.uvs4) { meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable); } if (this.uvs5) { meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable); } if (this.uvs6) { meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable); } if (this.colors) { meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable); } if (this.matricesIndices) { meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable); } if (this.matricesWeights) { meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable); } if (this.matricesIndicesExtra) { meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable); } if (this.matricesWeightsExtra) { meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable); } if (this.indices) { meshOrGeometry.setIndices(this.indices, null, updatable); } else { meshOrGeometry.setIndices([], null); } return this; }; VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) { if (this.positions) { meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique); } if (this.normals) { meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique); } if (this.tangents) { meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique); } if (this.uvs) { meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique); } if (this.uvs2) { meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique); } if (this.uvs3) { meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique); } if (this.uvs4) { meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique); } if (this.uvs5) { meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique); } if (this.uvs6) { meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique); } if (this.colors) { meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique); } if (this.matricesIndices) { meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique); } if (this.matricesWeights) { meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique); } if (this.matricesIndicesExtra) { meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique); } if (this.matricesWeightsExtra) { meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique); } if (this.indices) { meshOrGeometry.setIndices(this.indices, null); } return this; }; /** * Transforms each position and each normal of the vertexData according to the passed Matrix * @param matrix the transforming matrix * @returns the VertexData */ VertexData.prototype.transform = function (matrix) { var transformed = BABYLON.Vector3.Zero(); var index; if (this.positions) { var position = BABYLON.Vector3.Zero(); for (index = 0; index < this.positions.length; index += 3) { BABYLON.Vector3.FromArrayToRef(this.positions, index, position); BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed); this.positions[index] = transformed.x; this.positions[index + 1] = transformed.y; this.positions[index + 2] = transformed.z; } } if (this.normals) { var normal = BABYLON.Vector3.Zero(); for (index = 0; index < this.normals.length; index += 3) { BABYLON.Vector3.FromArrayToRef(this.normals, index, normal); BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed); this.normals[index] = transformed.x; this.normals[index + 1] = transformed.y; this.normals[index + 2] = transformed.z; } } if (this.tangents) { var tangent = BABYLON.Vector4.Zero(); var tangentTransformed = BABYLON.Vector4.Zero(); for (index = 0; index < this.tangents.length; index += 4) { BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent); BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed); this.tangents[index] = tangentTransformed.x; this.tangents[index + 1] = tangentTransformed.y; this.tangents[index + 2] = tangentTransformed.z; this.tangents[index + 3] = tangentTransformed.w; } } return this; }; /** * Merges the passed VertexData into the current one * @param other the VertexData to be merged into the current one * @returns the modified VertexData */ VertexData.prototype.merge = function (other) { this._validate(); other._validate(); if (!this.normals !== !other.normals || !this.tangents !== !other.tangents || !this.uvs !== !other.uvs || !this.uvs2 !== !other.uvs2 || !this.uvs3 !== !other.uvs3 || !this.uvs4 !== !other.uvs4 || !this.uvs5 !== !other.uvs5 || !this.uvs6 !== !other.uvs6 || !this.colors !== !other.colors || !this.matricesIndices !== !other.matricesIndices || !this.matricesWeights !== !other.matricesWeights || !this.matricesIndicesExtra !== !other.matricesIndicesExtra || !this.matricesWeightsExtra !== !other.matricesWeightsExtra) { throw new Error("Cannot merge vertex data that do not have the same set of attributes"); } if (other.indices) { if (!this.indices) { this.indices = []; } var offset = this.positions ? this.positions.length / 3 : 0; for (var index = 0; index < other.indices.length; index++) { //TODO check type - if Int32Array | Uint32Array | Uint16Array! this.indices.push(other.indices[index] + offset); } } this.positions = this._mergeElement(this.positions, other.positions); this.normals = this._mergeElement(this.normals, other.normals); this.tangents = this._mergeElement(this.tangents, other.tangents); this.uvs = this._mergeElement(this.uvs, other.uvs); this.uvs2 = this._mergeElement(this.uvs2, other.uvs2); this.uvs3 = this._mergeElement(this.uvs3, other.uvs3); this.uvs4 = this._mergeElement(this.uvs4, other.uvs4); this.uvs5 = this._mergeElement(this.uvs5, other.uvs5); this.uvs6 = this._mergeElement(this.uvs6, other.uvs6); this.colors = this._mergeElement(this.colors, other.colors); this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices); this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights); this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra); this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra); return this; }; VertexData.prototype._mergeElement = function (source, other) { if (!source) { return other; } if (!other) { return source; } var len = other.length + source.length; var isSrcTypedArray = source instanceof Float32Array; var isOthTypedArray = other instanceof Float32Array; // use non-loop method when the source is Float32Array if (isSrcTypedArray) { var ret32 = new Float32Array(len); ret32.set(source); ret32.set(other, source.length); return ret32; // source is number[], when other is also use concat } else if (!isOthTypedArray) { return source.concat(other); // source is a number[], but other is a Float32Array, loop required } else { var ret = source.slice(0); // copy source to a separate array for (var i = 0, len = other.length; i < len; i++) { ret.push(other[i]); } return ret; } }; VertexData.prototype._validate = function () { if (!this.positions) { throw new Error("Positions are required"); } var getElementCount = function (kind, values) { var stride = BABYLON.VertexBuffer.DeduceStride(kind); if ((values.length % stride) !== 0) { throw new Error("The " + kind + "s array count must be a multiple of " + stride); } return values.length / stride; }; var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions); var validateElementCount = function (kind, values) { var elementCount = getElementCount(kind, values); if (elementCount !== positionsElementCount) { throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")"); } }; if (this.normals) validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals); if (this.tangents) validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents); if (this.uvs) validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs); if (this.uvs2) validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2); if (this.uvs3) validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3); if (this.uvs4) validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4); if (this.uvs5) validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5); if (this.uvs6) validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6); if (this.colors) validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors); if (this.matricesIndices) validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices); if (this.matricesWeights) validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights); if (this.matricesIndicesExtra) validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra); if (this.matricesWeightsExtra) validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra); }; /** * Serializes the VertexData * @returns a serialized object */ VertexData.prototype.serialize = function () { var serializationObject = this.serialize(); if (this.positions) { serializationObject.positions = this.positions; } if (this.normals) { serializationObject.normals = this.normals; } if (this.tangents) { serializationObject.tangents = this.tangents; } if (this.uvs) { serializationObject.uvs = this.uvs; } if (this.uvs2) { serializationObject.uvs2 = this.uvs2; } if (this.uvs3) { serializationObject.uvs3 = this.uvs3; } if (this.uvs4) { serializationObject.uvs4 = this.uvs4; } if (this.uvs5) { serializationObject.uvs5 = this.uvs5; } if (this.uvs6) { serializationObject.uvs6 = this.uvs6; } if (this.colors) { serializationObject.colors = this.colors; } if (this.matricesIndices) { serializationObject.matricesIndices = this.matricesIndices; serializationObject.matricesIndices._isExpanded = true; } if (this.matricesWeights) { serializationObject.matricesWeights = this.matricesWeights; } if (this.matricesIndicesExtra) { serializationObject.matricesIndicesExtra = this.matricesIndicesExtra; serializationObject.matricesIndicesExtra._isExpanded = true; } if (this.matricesWeightsExtra) { serializationObject.matricesWeightsExtra = this.matricesWeightsExtra; } serializationObject.indices = this.indices; return serializationObject; }; // Statics /** * Extracts the vertexData from a mesh * @param mesh the mesh from which to extract the VertexData * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false * @param forceCopy indicating that the VertexData must be cloned, optional, default false * @returns the object VertexData associated to the passed mesh */ VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) { return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy); }; /** * Extracts the vertexData from the geometry * @param geometry the geometry from which to extract the VertexData * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false * @param forceCopy indicating that the VertexData must be cloned, optional, default false * @returns the object VertexData associated to the passed mesh */ VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) { return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy); }; VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) { var result = new VertexData(); if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) { result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) { result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) { result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) { result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) { result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) { result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) { result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) { result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) { result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) { result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) { result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) { result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) { result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) { result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy); } result.indices = meshOrGeometry.getIndices(copyWhenShared); return result; }; /** * Creates the VertexData for a Ribbon * @param options an object used to set the following optional parameters for the ribbon, required but can be empty * * pathArray array of paths, each of which an array of successive Vector3 * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional * * colors a linear array, of length 4 * number of vertices, of custom color values, optional * @returns the VertexData of the ribbon */ VertexData.CreateRibbon = function (options) { var pathArray = options.pathArray; var closeArray = options.closeArray || false; var closePath = options.closePath || false; var invertUV = options.invertUV || false; var defaultOffset = Math.floor(pathArray[0].length / 2); var offset = options.offset || defaultOffset; offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE; var customUV = options.uvs; var customColors = options.colors; var positions = []; var indices = []; var normals = []; var uvs = []; var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray var uTotalDistance = []; // uTotalDistance[p] : total distance of path p var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray var minlg; // minimal length among all paths from pathArray var lg = []; // array of path lengths : nb of vertex per path var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number var p; // path iterator var i; // point iterator var j; // point iterator // if single path in pathArray if (pathArray.length < 2) { var ar1 = []; var ar2 = []; for (i = 0; i < pathArray[0].length - offset; i++) { ar1.push(pathArray[0][i]); ar2.push(pathArray[0][i + offset]); } pathArray = [ar1, ar2]; } // positions and horizontal distances (u) var idc = 0; var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath var path; var l; minlg = pathArray[0].length; var vectlg; var dist; for (p = 0; p < pathArray.length; p++) { uTotalDistance[p] = 0; us[p] = [0]; path = pathArray[p]; l = path.length; minlg = (minlg < l) ? minlg : l; j = 0; while (j < l) { positions.push(path[j].x, path[j].y, path[j].z); if (j > 0) { vectlg = path[j].subtract(path[j - 1]).length(); dist = vectlg + uTotalDistance[p]; us[p].push(dist); uTotalDistance[p] = dist; } j++; } if (closePath) { // an extra hidden vertex is added in the "positions" array j--; positions.push(path[0].x, path[0].y, path[0].z); vectlg = path[j].subtract(path[0]).length(); dist = vectlg + uTotalDistance[p]; us[p].push(dist); uTotalDistance[p] = dist; } lg[p] = l + closePathCorr; idx[p] = idc; idc += (l + closePathCorr); } // vertical distances (v) var path1; var path2; var vertex1 = null; var vertex2 = null; for (i = 0; i < minlg + closePathCorr; i++) { vTotalDistance[i] = 0; vs[i] = [0]; for (p = 0; p < pathArray.length - 1; p++) { path1 = pathArray[p]; path2 = pathArray[p + 1]; if (i === minlg) { // closePath vertex1 = path1[0]; vertex2 = path2[0]; } else { vertex1 = path1[i]; vertex2 = path2[i]; } vectlg = vertex2.subtract(vertex1).length(); dist = vectlg + vTotalDistance[i]; vs[i].push(dist); vTotalDistance[i] = dist; } if (closeArray && vertex2 && vertex1) { path1 = pathArray[p]; path2 = pathArray[0]; if (i === minlg) { // closePath vertex2 = path2[0]; } vectlg = vertex2.subtract(vertex1).length(); dist = vectlg + vTotalDistance[i]; vTotalDistance[i] = dist; } } // uvs var u; var v; if (customUV) { for (p = 0; p < customUV.length; p++) { uvs.push(customUV[p].x, customUV[p].y); } } else { for (p = 0; p < pathArray.length; p++) { for (i = 0; i < minlg + closePathCorr; i++) { u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0; v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0; if (invertUV) { uvs.push(v, u); } else { uvs.push(u, v); } } } } // indices p = 0; // path index var pi = 0; // positions array index var l1 = lg[p] - 1; // path1 length var l2 = lg[p + 1] - 1; // path2 length var min = (l1 < l2) ? l1 : l2; // current path stop index var shft = idx[1] - idx[0]; // shift var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise indices.push(pi, pi + shft, pi + 1); indices.push(pi + shft + 1, pi + 1, pi + shft); pi += 1; if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path p++; if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true shft = idx[0] - idx[p]; l1 = lg[p] - 1; l2 = lg[0] - 1; } else { shft = idx[p + 1] - idx[p]; l1 = lg[p] - 1; l2 = lg[p + 1] - 1; } pi = idx[p]; min = (l1 < l2) ? l1 + pi : l2 + pi; } } // normals VertexData.ComputeNormals(positions, indices, normals); if (closePath) { // update both the first and last vertex normals to their average value var indexFirst = 0; var indexLast = 0; for (p = 0; p < pathArray.length; p++) { indexFirst = idx[p] * 3; if (p + 1 < pathArray.length) { indexLast = (idx[p + 1] - 1) * 3; } else { indexLast = normals.length - 3; } normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5; normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5; normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5; normals[indexLast] = normals[indexFirst]; normals[indexLast + 1] = normals[indexFirst + 1]; normals[indexLast + 2] = normals[indexFirst + 2]; } } // sides VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); // Colors var colors = null; if (customColors) { colors = new Float32Array(customColors.length * 4); for (var c = 0; c < customColors.length; c++) { colors[c * 4] = customColors[c].r; colors[c * 4 + 1] = customColors[c].g; colors[c * 4 + 2] = customColors[c].b; colors[c * 4 + 3] = customColors[c].a; } } // Result var vertexData = new VertexData(); var positions32 = new Float32Array(positions); var normals32 = new Float32Array(normals); var uvs32 = new Float32Array(uvs); vertexData.indices = indices; vertexData.positions = positions32; vertexData.normals = normals32; vertexData.uvs = uvs32; if (colors) { vertexData.set(colors, BABYLON.VertexBuffer.ColorKind); } if (closePath) { vertexData._idx = idx; } return vertexData; }; /** * Creates the VertexData for a box * @param options an object used to set the following optional parameters for the box, required but can be empty * * size sets the width, height and depth of the box to the value of size, optional default 1 * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size * * faceUV an array of 6 Vector4 elements used to set different images to each box side * * faceColors an array of 6 Color3 elements used to set different colors to each box side * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) * @returns the VertexData of the box */ VertexData.CreateBox = function (options) { var normalsSource = [ new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(0, -1, 0) ]; var indices = []; var positions = []; var normals = []; var uvs = []; var width = options.width || options.size || 1; var height = options.height || options.size || 1; var depth = options.depth || options.size || 1; var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE; var faceUV = options.faceUV || new Array(6); var faceColors = options.faceColors; var colors = []; // default face colors and UV if undefined for (var f = 0; f < 6; f++) { if (faceUV[f] === undefined) { faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1); } if (faceColors && faceColors[f] === undefined) { faceColors[f] = new BABYLON.Color4(1, 1, 1, 1); } } var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2); // Create each face in turn. for (var index = 0; index < normalsSource.length; index++) { var normal = normalsSource[index]; // Get two vectors perpendicular to the face normal and to each other. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x); var side2 = BABYLON.Vector3.Cross(normal, side1); // Six indices (two triangles) per face. var verticesLength = positions.length / 3; indices.push(verticesLength); indices.push(verticesLength + 1); indices.push(verticesLength + 2); indices.push(verticesLength); indices.push(verticesLength + 2); indices.push(verticesLength + 3); // Four vertices per face. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector); positions.push(vertex.x, vertex.y, vertex.z); normals.push(normal.x, normal.y, normal.z); uvs.push(faceUV[index].z, faceUV[index].w); if (faceColors) { colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a); } vertex = normal.subtract(side1).add(side2).multiply(scaleVector); positions.push(vertex.x, vertex.y, vertex.z); normals.push(normal.x, normal.y, normal.z); uvs.push(faceUV[index].x, faceUV[index].w); if (faceColors) { colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a); } vertex = normal.add(side1).add(side2).multiply(scaleVector); positions.push(vertex.x, vertex.y, vertex.z); normals.push(normal.x, normal.y, normal.z); uvs.push(faceUV[index].x, faceUV[index].y); if (faceColors) { colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a); } vertex = normal.add(side1).subtract(side2).multiply(scaleVector); positions.push(vertex.x, vertex.y, vertex.z); normals.push(normal.x, normal.y, normal.z); uvs.push(faceUV[index].z, faceUV[index].y); if (faceColors) { colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a); } } // sides VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); // Result var vertexData = new VertexData(); vertexData.indices = indices; vertexData.positions = positions; vertexData.normals = normals; vertexData.uvs = uvs; if (faceColors) { var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors; vertexData.colors = totalColors; } return vertexData; }; /** * Creates the VertexData for an ellipsoid, defaults to a sphere * @param options an object used to set the following optional parameters for the box, required but can be empty * * segments sets the number of horizontal strips optional, default 32 * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1 * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1 * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1 * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) * @returns the VertexData of the ellipsoid */ VertexData.CreateSphere = function (options) { var segments = options.segments || 32; var diameterX = options.diameterX || options.diameter || 1; var diameterY = options.diameterY || options.diameter || 1; var diameterZ = options.diameterZ || options.diameter || 1; var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0; var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0; var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE; var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2); var totalZRotationSteps = 2 + segments; var totalYRotationSteps = 2 * totalZRotationSteps; var indices = []; var positions = []; var normals = []; var uvs = []; for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) { var normalizedZ = zRotationStep / totalZRotationSteps; var angleZ = normalizedZ * Math.PI * slice; for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) { var normalizedY = yRotationStep / totalYRotationSteps; var angleY = normalizedY * Math.PI * 2 * arc; var rotationZ = BABYLON.Matrix.RotationZ(-angleZ); var rotationY = BABYLON.Matrix.RotationY(angleY); var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ); var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY); var vertex = complete.multiply(radius); var normal = complete.divide(radius).normalize(); positions.push(vertex.x, vertex.y, vertex.z); normals.push(normal.x, normal.y, normal.z); uvs.push(normalizedY, normalizedZ); } if (zRotationStep > 0) { var verticesCount = positions.length / 3; for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) { indices.push((firstIndex)); indices.push((firstIndex + 1)); indices.push(firstIndex + totalYRotationSteps + 1); indices.push((firstIndex + totalYRotationSteps + 1)); indices.push((firstIndex + 1)); indices.push((firstIndex + totalYRotationSteps + 2)); } } } // Sides VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); // Result var vertexData = new VertexData(); vertexData.indices = indices; vertexData.positions = positions; vertexData.normals = normals; vertexData.uvs = uvs; return vertexData; }; /** * Creates the VertexData for a cylinder, cone or prism * @param options an object used to set the following optional parameters for the box, required but can be empty * * height sets the height (y direction) of the cylinder, optional, default 2 * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter * * diameter sets the diameter of the top and bottom of the cone, optional default 1 * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24 * * subdivisions` the number of rings along the cylinder height, optional, default 1 * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1 * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) * @returns the VertexData of the cylinder, cone or prism */ VertexData.CreateCylinder = function (options) { var height = options.height || 2; var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1; var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1; var tessellation = options.tessellation || 24; var subdivisions = options.subdivisions || 1; var hasRings = options.hasRings ? true : false; var enclose = options.enclose ? true : false; var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0; var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE; var faceUV = options.faceUV || new Array(3); var faceColors = options.faceColors; // default face colors and UV if undefined var quadNb = (arc !== 1 && enclose) ? 2 : 0; var ringNb = (hasRings) ? subdivisions : 1; var surfaceNb = 2 + (1 + quadNb) * ringNb; var f; for (f = 0; f < surfaceNb; f++) { if (faceColors && faceColors[f] === undefined) { faceColors[f] = new BABYLON.Color4(1, 1, 1, 1); } } for (f = 0; f < surfaceNb; f++) { if (faceUV && faceUV[f] === undefined) { faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1); } } var indices = new Array(); var positions = new Array(); var normals = new Array(); var uvs = new Array(); var colors = new Array(); var angle_step = Math.PI * 2 * arc / tessellation; var angle; var h; var radius; var tan = (diameterBottom - diameterTop) / 2 / height; var ringVertex = BABYLON.Vector3.Zero(); var ringNormal = BABYLON.Vector3.Zero(); var ringFirstVertex = BABYLON.Vector3.Zero(); var ringFirstNormal = BABYLON.Vector3.Zero(); var quadNormal = BABYLON.Vector3.Zero(); var Y = BABYLON.Axis.Y; // positions, normals, uvs var i; var j; var r; var ringIdx = 1; var s = 1; // surface index var cs = 0; var v = 0; for (i = 0; i <= subdivisions; i++) { h = i / subdivisions; radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2; ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1; for (r = 0; r < ringIdx; r++) { if (hasRings) { s += r; } if (enclose) { s += 2 * r; } for (j = 0; j <= tessellation; j++) { angle = j * angle_step; // position ringVertex.x = Math.cos(-angle) * radius; ringVertex.y = -height / 2 + h * height; ringVertex.z = Math.sin(-angle) * radius; // normal if (diameterTop === 0 && i === subdivisions) { // if no top cap, reuse former normals ringNormal.x = normals[normals.length - (tessellation + 1) * 3]; ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1]; ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2]; } else { ringNormal.x = ringVertex.x; ringNormal.z = ringVertex.z; ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan; ringNormal.normalize(); } // keep first ring vertex values for enclose if (j === 0) { ringFirstVertex.copyFrom(ringVertex); ringFirstNormal.copyFrom(ringNormal); } positions.push(ringVertex.x, ringVertex.y, ringVertex.z); normals.push(ringNormal.x, ringNormal.y, ringNormal.z); if (hasRings) { v = (cs !== s) ? faceUV[s].y : faceUV[s].w; } else { v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h; } uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v); if (faceColors) { colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a); } } // if enclose, add four vertices and their dedicated normals if (arc !== 1 && enclose) { positions.push(ringVertex.x, ringVertex.y, ringVertex.z); positions.push(0, ringVertex.y, 0); positions.push(0, ringVertex.y, 0); positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z); BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal); quadNormal.normalize(); normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z); BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal); quadNormal.normalize(); normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z); if (hasRings) { v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w; } else { v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h; } uvs.push(faceUV[s + 1].x, v); uvs.push(faceUV[s + 1].z, v); if (hasRings) { v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w; } else { v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h; } uvs.push(faceUV[s + 2].x, v); uvs.push(faceUV[s + 2].z, v); if (faceColors) { colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a); colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a); colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a); colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a); } } if (cs !== s) { cs = s; } } } // indices var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose var s; i = 0; for (s = 0; s < subdivisions; s++) { var i0 = 0; var i1 = 0; var i2 = 0; var i3 = 0; for (j = 0; j < tessellation; j++) { i0 = i * (e + 1) + j; i1 = (i + 1) * (e + 1) + j; i2 = i * (e + 1) + (j + 1); i3 = (i + 1) * (e + 1) + (j + 1); indices.push(i0, i1, i2); indices.push(i3, i2, i1); } if (arc !== 1 && enclose) { // if enclose, add two quads indices.push(i0 + 2, i1 + 2, i2 + 2); indices.push(i3 + 2, i2 + 2, i1 + 2); indices.push(i0 + 4, i1 + 4, i2 + 4); indices.push(i3 + 4, i2 + 4, i1 + 4); } i = (hasRings) ? (i + 2) : (i + 1); } // Caps var createCylinderCap = function (isTop) { var radius = isTop ? diameterTop / 2 : diameterBottom / 2; if (radius === 0) { return; } // Cap positions, normals & uvs var angle; var circleVector; var i; var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0]; var c = null; if (faceColors) { c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0]; } // cap center var vbase = positions.length / 3; var offset = isTop ? height / 2 : -height / 2; var center = new BABYLON.Vector3(0, offset, 0); positions.push(center.x, center.y, center.z); normals.push(0, isTop ? 1 : -1, 0); uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5); if (c) { colors.push(c.r, c.g, c.b, c.a); } var textureScale = new BABYLON.Vector2(0.5, 0.5); for (i = 0; i <= tessellation; i++) { angle = Math.PI * 2 * i * arc / tessellation; var cos = Math.cos(-angle); var sin = Math.sin(-angle); circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius); var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5); positions.push(circleVector.x, circleVector.y, circleVector.z); normals.push(0, isTop ? 1 : -1, 0); uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y); if (c) { colors.push(c.r, c.g, c.b, c.a); } } // Cap indices for (i = 0; i < tessellation; i++) { if (!isTop) { indices.push(vbase); indices.push(vbase + (i + 1)); indices.push(vbase + (i + 2)); } else { indices.push(vbase); indices.push(vbase + (i + 2)); indices.push(vbase + (i + 1)); } } }; // add caps to geometry createCylinderCap(false); createCylinderCap(true); // Sides VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); var vertexData = new VertexData(); vertexData.indices = indices; vertexData.positions = positions; vertexData.normals = normals; vertexData.uvs = uvs; if (faceColors) { vertexData.colors = colors; } return vertexData; }; /** * Creates the VertexData for a torus * @param options an object used to set the following optional parameters for the box, required but can be empty * * diameter the diameter of the torus, optional default 1 * * thickness the diameter of the tube forming the torus, optional default 0.5 * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24 * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) * @returns the VertexData of the torus */ VertexData.CreateTorus = function (options) { var indices = []; var positions = []; var normals = []; var uvs = []; var diameter = options.diameter || 1; var thickness = options.thickness || 0.5; var tessellation = options.tessellation || 16; var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE; var stride = tessellation + 1; for (var i = 0; i <= tessellation; i++) { var u = i / tessellation; var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0; var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle)); for (var j = 0; j <= tessellation; j++) { var v = 1 - j / tessellation; var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI; var dx = Math.cos(innerAngle); var dy = Math.sin(innerAngle); // Create a vertex. var normal = new BABYLON.Vector3(dx, dy, 0); var position = normal.scale(thickness / 2); var textureCoordinate = new BABYLON.Vector2(u, v); position = BABYLON.Vector3.TransformCoordinates(position, transform); normal = BABYLON.Vector3.TransformNormal(normal, transform); positions.push(position.x, position.y, position.z); normals.push(normal.x, normal.y, normal.z); uvs.push(textureCoordinate.x, textureCoordinate.y); // And create indices for two triangles. var nextI = (i + 1) % stride; var nextJ = (j + 1) % stride; indices.push(i * stride + j); indices.push(i * stride + nextJ); indices.push(nextI * stride + j); indices.push(i * stride + nextJ); indices.push(nextI * stride + nextJ); indices.push(nextI * stride + j); } } // Sides VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); // Result var vertexData = new VertexData(); vertexData.indices = indices; vertexData.positions = positions; vertexData.normals = normals; vertexData.uvs = uvs; return vertexData; }; /** * Creates the VertexData of the LineSystem * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty * - lines an array of lines, each line being an array of successive Vector3 * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point * @returns the VertexData of the LineSystem */ VertexData.CreateLineSystem = function (options) { var indices = []; var positions = []; var lines = options.lines; var colors = options.colors; var vertexColors = []; var idx = 0; for (var l = 0; l < lines.length; l++) { var points = lines[l]; for (var index = 0; index < points.length; index++) { positions.push(points[index].x, points[index].y, points[index].z); if (colors) { var color = colors[l]; vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a); } if (index > 0) { indices.push(idx - 1); indices.push(idx); } idx++; } } var vertexData = new VertexData(); vertexData.indices = indices; vertexData.positions = positions; if (colors) { vertexData.colors = vertexColors; } return vertexData; }; /** * Create the VertexData for a DashedLines * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty * - points an array successive Vector3 * - dashSize the size of the dashes relative to the dash number, optional, default 3 * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1 * - dashNb the intended total number of dashes, optional, default 200 * @returns the VertexData for the DashedLines */ VertexData.CreateDashedLines = function (options) { var dashSize = options.dashSize || 3; var gapSize = options.gapSize || 1; var dashNb = options.dashNb || 200; var points = options.points; var positions = new Array(); var indices = new Array(); var curvect = BABYLON.Vector3.Zero(); var lg = 0; var nb = 0; var shft = 0; var dashshft = 0; var curshft = 0; var idx = 0; var i = 0; for (i = 0; i < points.length - 1; i++) { points[i + 1].subtractToRef(points[i], curvect); lg += curvect.length(); } shft = lg / dashNb; dashshft = dashSize * shft / (dashSize + gapSize); for (i = 0; i < points.length - 1; i++) { points[i + 1].subtractToRef(points[i], curvect); nb = Math.floor(curvect.length() / shft); curvect.normalize(); for (var j = 0; j < nb; j++) { curshft = shft * j; positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z); positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z); indices.push(idx, idx + 1); idx += 2; } } // Result var vertexData = new VertexData(); vertexData.positions = positions; vertexData.indices = indices; return vertexData; }; /** * Creates the VertexData for a Ground * @param options an object used to set the following optional parameters for the Ground, required but can be empty * - width the width (x direction) of the ground, optional, default 1 * - height the height (z direction) of the ground, optional, default 1 * - subdivisions the number of subdivisions per side, optional, default 1 * @returns the VertexData of the Ground */ VertexData.CreateGround = function (options) { var indices = []; var positions = []; var normals = []; var uvs = []; var row, col; var width = options.width || 1; var height = options.height || 1; var subdivisionsX = options.subdivisionsX || options.subdivisions || 1; var subdivisionsY = options.subdivisionsY || options.subdivisions || 1; for (row = 0; row <= subdivisionsY; row++) { for (col = 0; col <= subdivisionsX; col++) { var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0)); var normal = new BABYLON.Vector3(0, 1.0, 0); positions.push(position.x, position.y, position.z); normals.push(normal.x, normal.y, normal.z); uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY); } } for (row = 0; row < subdivisionsY; row++) { for (col = 0; col < subdivisionsX; col++) { indices.push(col + 1 + (row + 1) * (subdivisionsX + 1)); indices.push(col + 1 + row * (subdivisionsX + 1)); indices.push(col + row * (subdivisionsX + 1)); indices.push(col + (row + 1) * (subdivisionsX + 1)); indices.push(col + 1 + (row + 1) * (subdivisionsX + 1)); indices.push(col + row * (subdivisionsX + 1)); } } // Result var vertexData = new VertexData(); vertexData.indices = indices; vertexData.positions = positions; vertexData.normals = normals; vertexData.uvs = uvs; return vertexData; }; /** * Creates the VertexData for a TiledGround by subdividing the ground into tiles * @param options an object used to set the following optional parameters for the Ground, required but can be empty * * xmin the ground minimum X coordinate, optional, default -1 * * zmin the ground minimum Z coordinate, optional, default -1 * * xmax the ground maximum X coordinate, optional, default 1 * * zmax the ground maximum Z coordinate, optional, default 1 * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6} * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2} * @returns the VertexData of the TiledGround */ VertexData.CreateTiledGround = function (options) { var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0; var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0; var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0; var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0; var subdivisions = options.subdivisions || { w: 1, h: 1 }; var precision = options.precision || { w: 1, h: 1 }; var indices = new Array(); var positions = new Array(); var normals = new Array(); var uvs = new Array(); var row, col, tileRow, tileCol; subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h; subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w; precision.w = (precision.w < 1) ? 1 : precision.w; precision.h = (precision.h < 1) ? 1 : precision.h; var tileSize = { 'w': (xmax - xmin) / subdivisions.w, 'h': (zmax - zmin) / subdivisions.h }; function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) { // Indices var base = positions.length / 3; var rowLength = precision.w + 1; for (row = 0; row < precision.h; row++) { for (col = 0; col < precision.w; col++) { var square = [ base + col + row * rowLength, base + (col + 1) + row * rowLength, base + (col + 1) + (row + 1) * rowLength, base + col + (row + 1) * rowLength ]; indices.push(square[1]); indices.push(square[2]); indices.push(square[3]); indices.push(square[0]); indices.push(square[1]); indices.push(square[3]); } } // Position, normals and uvs var position = BABYLON.Vector3.Zero(); var normal = new BABYLON.Vector3(0, 1.0, 0); for (row = 0; row <= precision.h; row++) { position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin; for (col = 0; col <= precision.w; col++) { position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin; position.y = 0; positions.push(position.x, position.y, position.z); normals.push(normal.x, normal.y, normal.z); uvs.push(col / precision.w, row / precision.h); } } } for (tileRow = 0; tileRow < subdivisions.h; tileRow++) { for (tileCol = 0; tileCol < subdivisions.w; tileCol++) { applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h); } } // Result var vertexData = new VertexData(); vertexData.indices = indices; vertexData.positions = positions; vertexData.normals = normals; vertexData.uvs = uvs; return vertexData; }; /** * Creates the VertexData of the Ground designed from a heightmap * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap * * width the width (x direction) of the ground * * height the height (z direction) of the ground * * subdivisions the number of subdivisions per side * * minHeight the minimum altitude on the ground, optional, default 0 * * maxHeight the maximum altitude on the ground, optional default 1 * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11) * * buffer the array holding the image color data * * bufferWidth the width of image * * bufferHeight the height of image * @returns the VertexData of the Ground designed from a heightmap */ VertexData.CreateGroundFromHeightMap = function (options) { var indices = []; var positions = []; var normals = []; var uvs = []; var row, col; var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11); // Vertices for (row = 0; row <= options.subdivisions; row++) { for (col = 0; col <= options.subdivisions; col++) { var position = new BABYLON.Vector3((col * options.width) / options.subdivisions - (options.width / 2.0), 0, ((options.subdivisions - row) * options.height) / options.subdivisions - (options.height / 2.0)); // Compute height var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0; var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0; var pos = (heightMapX + heightMapY * options.bufferWidth) * 4; var r = options.buffer[pos] / 255.0; var g = options.buffer[pos + 1] / 255.0; var b = options.buffer[pos + 2] / 255.0; var gradient = r * filter.r + g * filter.g + b * filter.b; position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient; // Add vertex positions.push(position.x, position.y, position.z); normals.push(0, 0, 0); uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions); } } // Indices for (row = 0; row < options.subdivisions; row++) { for (col = 0; col < options.subdivisions; col++) { indices.push(col + 1 + (row + 1) * (options.subdivisions + 1)); indices.push(col + 1 + row * (options.subdivisions + 1)); indices.push(col + row * (options.subdivisions + 1)); indices.push(col + (row + 1) * (options.subdivisions + 1)); indices.push(col + 1 + (row + 1) * (options.subdivisions + 1)); indices.push(col + row * (options.subdivisions + 1)); } } // Normals VertexData.ComputeNormals(positions, indices, normals); // Result var vertexData = new VertexData(); vertexData.indices = indices; vertexData.positions = positions; vertexData.normals = normals; vertexData.uvs = uvs; return vertexData; }; /** * Creates the VertexData for a Plane * @param options an object used to set the following optional parameters for the plane, required but can be empty * * size sets the width and height of the plane to the value of size, optional default 1 * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) * @returns the VertexData of the box */ VertexData.CreatePlane = function (options) { var indices = []; var positions = []; var normals = []; var uvs = []; var width = options.width || options.size || 1; var height = options.height || options.size || 1; var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE; // Vertices var halfWidth = width / 2.0; var halfHeight = height / 2.0; positions.push(-halfWidth, -halfHeight, 0); normals.push(0, 0, -1.0); uvs.push(0.0, 0.0); positions.push(halfWidth, -halfHeight, 0); normals.push(0, 0, -1.0); uvs.push(1.0, 0.0); positions.push(halfWidth, halfHeight, 0); normals.push(0, 0, -1.0); uvs.push(1.0, 1.0); positions.push(-halfWidth, halfHeight, 0); normals.push(0, 0, -1.0); uvs.push(0.0, 1.0); // Indices indices.push(0); indices.push(1); indices.push(2); indices.push(0); indices.push(2); indices.push(3); // Sides VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); // Result var vertexData = new VertexData(); vertexData.indices = indices; vertexData.positions = positions; vertexData.normals = normals; vertexData.uvs = uvs; return vertexData; }; /** * Creates the VertexData of the Disc or regular Polygon * @param options an object used to set the following optional parameters for the disc, required but can be empty * * radius the radius of the disc, optional default 0.5 * * tessellation the number of polygon sides, optional, default 64 * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1 * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) * @returns the VertexData of the box */ VertexData.CreateDisc = function (options) { var positions = new Array(); var indices = new Array(); var normals = new Array(); var uvs = new Array(); var radius = options.radius || 0.5; var tessellation = options.tessellation || 64; var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0; var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE; // positions and uvs positions.push(0, 0, 0); // disc center first uvs.push(0.5, 0.5); var theta = Math.PI * 2 * arc; var step = theta / tessellation; for (var a = 0; a < theta; a += step) { var x = Math.cos(a); var y = Math.sin(a); var u = (x + 1) / 2; var v = (1 - y) / 2; positions.push(radius * x, radius * y, 0); uvs.push(u, v); } if (arc === 1) { positions.push(positions[3], positions[4], positions[5]); // close the circle uvs.push(uvs[2], uvs[3]); } //indices var vertexNb = positions.length / 3; for (var i = 1; i < vertexNb - 1; i++) { indices.push(i + 1, 0, i); } // result VertexData.ComputeNormals(positions, indices, normals); VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); var vertexData = new VertexData(); vertexData.indices = indices; vertexData.positions = positions; vertexData.normals = normals; vertexData.uvs = uvs; return vertexData; }; /** * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build() * All parameters are provided by MeshBuilder.CreatePolygon as needed * @param polygon a mesh built from polygonTriangulation.build() * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) * @returns the VertexData of the Polygon */ VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) { var faceUV = fUV || new Array(3); var faceColors = fColors; var colors = []; // default face colors and UV if undefined for (var f = 0; f < 3; f++) { if (faceUV[f] === undefined) { faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1); } if (faceColors && faceColors[f] === undefined) { faceColors[f] = new BABYLON.Color4(1, 1, 1, 1); } } var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind); var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind); var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind); var indices = polygon.getIndices(); // set face colours and textures var idx = 0; var face = 0; for (var index = 0; index < normals.length; index += 3) { //Edge Face no. 1 if (Math.abs(normals[index + 1]) < 0.001) { face = 1; } //Top Face no. 0 if (Math.abs(normals[index + 1] - 1) < 0.001) { face = 0; } //Bottom Face no. 2 if (Math.abs(normals[index + 1] + 1) < 0.001) { face = 2; } idx = index / 3; uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z; uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w; if (faceColors) { colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a); } } // sides VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs); // Result var vertexData = new VertexData(); vertexData.indices = indices; vertexData.positions = positions; vertexData.normals = normals; vertexData.uvs = uvs; if (faceColors) { var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors; vertexData.colors = totalColors; } return vertexData; }; /** * Creates the VertexData of the IcoSphere * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty * * radius the radius of the IcoSphere, optional default 1 * * radiusX allows stretching in the x direction, optional, default radius * * radiusY allows stretching in the y direction, optional, default radius * * radiusZ allows stretching in the z direction, optional, default radius * * flat when true creates a flat shaded mesh, optional, default true * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4 * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) * @returns the VertexData of the IcoSphere */ VertexData.CreateIcoSphere = function (options) { var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE; var radius = options.radius || 1; var flat = (options.flat === undefined) ? true : options.flat; var subdivisions = options.subdivisions || 4; var radiusX = options.radiusX || radius; var radiusY = options.radiusY || radius; var radiusZ = options.radiusZ || radius; var t = (1 + Math.sqrt(5)) / 2; // 12 vertex x,y,z var ico_vertices = [ -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0, 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11 ]; // index of 3 vertex makes a face of icopshere var ico_indices = [ 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23, 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8, 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9, 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1 ]; // vertex for uv have aliased position, not for UV var vertices_unalias_id = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, // vertex alias 0, 2, 3, 3, 3, 4, 7, 8, 9, 9, 10, 11 // 23: B + 12 ]; // uv as integer step (not pixels !) var ico_vertexuv = [ 5, 1, 3, 1, 6, 4, 0, 0, 5, 3, 4, 2, 2, 2, 4, 0, 2, 0, 1, 1, 6, 0, 6, 2, // vertex alias (for same vertex on different faces) 0, 4, 3, 3, 4, 4, 3, 1, 4, 2, 4, 4, 0, 2, 1, 1, 2, 2, 3, 3, 1, 3, 2, 4 // 23: B + 12 ]; // Vertices[0, 1, ...9, A, B] : position on UV plane // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B) // First island of uv mapping // v = 4h 3+ 2 // v = 3h 9+ 4 // v = 2h 9+ 5 B // v = 1h 9 1 0 // v = 0h 3 8 7 A // u = 0 1 2 3 4 5 6 *a // Second island of uv mapping // v = 4h 0+ B+ 4+ // v = 3h A+ 2+ // v = 2h 7+ 6 3+ // v = 1h 8+ 3+ // v = 0h // u = 0 1 2 3 4 5 6 *a // Face layout on texture UV mapping // ============ // \ 4 /\ 16 / ====== // \ / \ / /\ 11 / // \/ 7 \/ / \ / // ======= / 10 \/ // /\ 17 /\ ======= // / \ / \ \ 15 /\ // / 8 \/ 12 \ \ / \ // ============ \/ 6 \ // \ 18 /\ ============ // \ / \ \ 5 /\ 0 / // \/ 13 \ \ / \ / // ======= \/ 1 \/ // ============= // /\ 19 /\ 2 /\ // / \ / \ / \ // / 14 \/ 9 \/ 3 \ // =================== // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97 var ustep = 138 / 1024; var vstep = 239 / 1024; var uoffset = 60 / 1024; var voffset = 26 / 1024; // Second island should have margin, not to touch the first island // avoid any borderline artefact in pixel rounding var island_u_offset = -40 / 1024; var island_v_offset = +20 / 1024; // face is either island 0 or 1 : // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18] var island = [ 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0 // 15 - 19 ]; var indices = new Array(); var positions = new Array(); var normals = new Array(); var uvs = new Array(); var current_indice = 0; // prepare array of 3 vector (empty) (to be worked in place, shared for each face) var face_vertex_pos = new Array(3); var face_vertex_uv = new Array(3); var v012; for (v012 = 0; v012 < 3; v012++) { face_vertex_pos[v012] = BABYLON.Vector3.Zero(); face_vertex_uv[v012] = BABYLON.Vector2.Zero(); } // create all with normals for (var face = 0; face < 20; face++) { // 3 vertex per face for (v012 = 0; v012 < 3; v012++) { // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias) var v_id = ico_indices[3 * face + v012]; // vertex have 3D position (x,y,z) face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * vertices_unalias_id[v_id]], ico_vertices[3 * vertices_unalias_id[v_id] + 1], ico_vertices[3 * vertices_unalias_id[v_id] + 2]); // Normalize to get normal, then scale to radius face_vertex_pos[v012].normalize().scaleInPlace(radius); // uv Coordinates from vertex ID face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset); } // Subdivide the face (interpolate pos, norm, uv) // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere) // - norm is linear interpolation of vertex corner normal // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? ) // - uv is linear interpolation // // Topology is as below for sub-divide by 2 // vertex shown as v0,v1,v2 // interp index is i1 to progress in range [v0,v1[ // interp index is i2 to progress in range [v0,v2[ // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1) // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1) // // // i2 v2 // ^ ^ // / / \ // / / \ // / / \ // / / (0,1) \ // / #---------\ // / / \ (0,0)'/ \ // / / \ / \ // / / \ / \ // / / (0,0) \ / (1,0) \ // / #---------#---------\ // v0 v1 // // --------------------> i1 // // interp of (i1,i2): // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S) // along i1 : lerp(x0,x1, i1/(S-i2)) // // centroid of triangle is needed to get help normal computation // (c1,c2) are used for centroid location var interp_vertex = function (i1, i2, c1, c2) { // vertex is interpolated from // - face_vertex_pos[0..2] // - face_vertex_uv[0..2] var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions); var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions); var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2)); pos_interp.normalize(); var vertex_normal; if (flat) { // in flat mode, recalculate normal as face centroid normal var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions); var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions); vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2)); } else { // in smooth mode, recalculate normal from each single vertex position vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z); } // Vertex normal need correction due to X,Y,Z radius scaling vertex_normal.x /= radiusX; vertex_normal.y /= radiusY; vertex_normal.z /= radiusZ; vertex_normal.normalize(); var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions); var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions); var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2)); positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ); normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z); uvs.push(uv_interp.x, uv_interp.y); // push each vertex has member of a face // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present) indices.push(current_indice); current_indice++; }; for (var i2 = 0; i2 < subdivisions; i2++) { for (var i1 = 0; i1 + i2 < subdivisions; i1++) { // face : (i1,i2) for /\ : // interp for : (i1,i2),(i1+1,i2),(i1,i2+1) interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3); interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3); interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3); if (i1 + i2 + 1 < subdivisions) { // face : (i1,i2)' for \/ : // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1) interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3); interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3); interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3); } } } } // Sides VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); // Result var vertexData = new VertexData(); vertexData.indices = indices; vertexData.positions = positions; vertexData.normals = normals; vertexData.uvs = uvs; return vertexData; }; // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html /** * Creates the VertexData for a Polyhedron * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty * * type provided types are: * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1) * * 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20) * * size the size of the IcoSphere, optional default 1 * * sizeX allows stretching in the x direction, optional, default size * * sizeY allows stretching in the y direction, optional, default size * * sizeZ allows stretching in the z direction, optional, default size * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively * * flat when true creates a flat shaded mesh, optional, default true * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4 * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) * @returns the VertexData of the Polyhedron */ VertexData.CreatePolyhedron = function (options) { // provided polyhedron types : // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1) // 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20) var polyhedra = []; polyhedra[0] = { vertex: [[0, 0, 1.732051], [1.632993, 0, -0.5773503], [-0.8164966, 1.414214, -0.5773503], [-0.8164966, -1.414214, -0.5773503]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]] }; polyhedra[1] = { vertex: [[0, 0, 1.414214], [1.414214, 0, 0], [0, 1.414214, 0], [-1.414214, 0, 0], [0, -1.414214, 0], [0, 0, -1.414214]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [1, 4, 5], [1, 5, 2], [2, 5, 3], [3, 5, 4]] }; polyhedra[2] = { vertex: [[0, 0, 1.070466], [0.7136442, 0, 0.7978784], [-0.3568221, 0.618034, 0.7978784], [-0.3568221, -0.618034, 0.7978784], [0.7978784, 0.618034, 0.3568221], [0.7978784, -0.618034, 0.3568221], [-0.9341724, 0.381966, 0.3568221], [0.1362939, 1, 0.3568221], [0.1362939, -1, 0.3568221], [-0.9341724, -0.381966, 0.3568221], [0.9341724, 0.381966, -0.3568221], [0.9341724, -0.381966, -0.3568221], [-0.7978784, 0.618034, -0.3568221], [-0.1362939, 1, -0.3568221], [-0.1362939, -1, -0.3568221], [-0.7978784, -0.618034, -0.3568221], [0.3568221, 0.618034, -0.7978784], [0.3568221, -0.618034, -0.7978784], [-0.7136442, 0, -0.7978784], [0, 0, -1.070466]], face: [[0, 1, 4, 7, 2], [0, 2, 6, 9, 3], [0, 3, 8, 5, 1], [1, 5, 11, 10, 4], [2, 7, 13, 12, 6], [3, 9, 15, 14, 8], [4, 10, 16, 13, 7], [5, 8, 14, 17, 11], [6, 12, 18, 15, 9], [10, 11, 17, 19, 16], [12, 13, 16, 19, 18], [14, 15, 18, 19, 17]] }; polyhedra[3] = { vertex: [[0, 0, 1.175571], [1.051462, 0, 0.5257311], [0.3249197, 1, 0.5257311], [-0.8506508, 0.618034, 0.5257311], [-0.8506508, -0.618034, 0.5257311], [0.3249197, -1, 0.5257311], [0.8506508, 0.618034, -0.5257311], [0.8506508, -0.618034, -0.5257311], [-0.3249197, 1, -0.5257311], [-1.051462, 0, -0.5257311], [-0.3249197, -1, -0.5257311], [0, 0, -1.175571]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 6], [1, 6, 2], [2, 6, 8], [2, 8, 3], [3, 8, 9], [3, 9, 4], [4, 9, 10], [4, 10, 5], [5, 10, 7], [6, 7, 11], [6, 11, 8], [7, 10, 11], [8, 11, 9], [9, 11, 10]] }; polyhedra[4] = { vertex: [[0, 0, 1.070722], [0.7148135, 0, 0.7971752], [-0.104682, 0.7071068, 0.7971752], [-0.6841528, 0.2071068, 0.7971752], [-0.104682, -0.7071068, 0.7971752], [0.6101315, 0.7071068, 0.5236279], [1.04156, 0.2071068, 0.1367736], [0.6101315, -0.7071068, 0.5236279], [-0.3574067, 1, 0.1367736], [-0.7888348, -0.5, 0.5236279], [-0.9368776, 0.5, 0.1367736], [-0.3574067, -1, 0.1367736], [0.3574067, 1, -0.1367736], [0.9368776, -0.5, -0.1367736], [0.7888348, 0.5, -0.5236279], [0.3574067, -1, -0.1367736], [-0.6101315, 0.7071068, -0.5236279], [-1.04156, -0.2071068, -0.1367736], [-0.6101315, -0.7071068, -0.5236279], [0.104682, 0.7071068, -0.7971752], [0.6841528, -0.2071068, -0.7971752], [0.104682, -0.7071068, -0.7971752], [-0.7148135, 0, -0.7971752], [0, 0, -1.070722]], face: [[0, 2, 3], [1, 6, 5], [4, 9, 11], [7, 15, 13], [8, 16, 10], [12, 14, 19], [17, 22, 18], [20, 21, 23], [0, 1, 5, 2], [0, 3, 9, 4], [0, 4, 7, 1], [1, 7, 13, 6], [2, 5, 12, 8], [2, 8, 10, 3], [3, 10, 17, 9], [4, 11, 15, 7], [5, 6, 14, 12], [6, 13, 20, 14], [8, 12, 19, 16], [9, 17, 18, 11], [10, 16, 22, 17], [11, 18, 21, 15], [13, 15, 21, 20], [14, 20, 23, 19], [16, 19, 23, 22], [18, 22, 23, 21]] }; polyhedra[5] = { vertex: [[0, 0, 1.322876], [1.309307, 0, 0.1889822], [-0.9819805, 0.8660254, 0.1889822], [0.1636634, -1.299038, 0.1889822], [0.3273268, 0.8660254, -0.9449112], [-0.8183171, -0.4330127, -0.9449112]], face: [[0, 3, 1], [2, 4, 5], [0, 1, 4, 2], [0, 2, 5, 3], [1, 3, 5, 4]] }; polyhedra[6] = { vertex: [[0, 0, 1.159953], [1.013464, 0, 0.5642542], [-0.3501431, 0.9510565, 0.5642542], [-0.7715208, -0.6571639, 0.5642542], [0.6633206, 0.9510565, -0.03144481], [0.8682979, -0.6571639, -0.3996071], [-1.121664, 0.2938926, -0.03144481], [-0.2348831, -1.063314, -0.3996071], [0.5181548, 0.2938926, -0.9953061], [-0.5850262, -0.112257, -0.9953061]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 9, 7], [5, 7, 9, 8], [0, 3, 7, 5, 1], [2, 4, 8, 9, 6]] }; polyhedra[7] = { vertex: [[0, 0, 1.118034], [0.8944272, 0, 0.6708204], [-0.2236068, 0.8660254, 0.6708204], [-0.7826238, -0.4330127, 0.6708204], [0.6708204, 0.8660254, 0.2236068], [1.006231, -0.4330127, -0.2236068], [-1.006231, 0.4330127, 0.2236068], [-0.6708204, -0.8660254, -0.2236068], [0.7826238, 0.4330127, -0.6708204], [0.2236068, -0.8660254, -0.6708204], [-0.8944272, 0, -0.6708204], [0, 0, -1.118034]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 10, 7], [5, 9, 11, 8], [7, 10, 11, 9], [0, 3, 7, 9, 5, 1], [2, 4, 8, 11, 10, 6]] }; polyhedra[8] = { vertex: [[-0.729665, 0.670121, 0.319155], [-0.655235, -0.29213, -0.754096], [-0.093922, -0.607123, 0.537818], [0.702196, 0.595691, 0.485187], [0.776626, -0.36656, -0.588064]], face: [[1, 4, 2], [0, 1, 2], [3, 0, 2], [4, 3, 2], [4, 1, 0, 3]] }; polyhedra[9] = { vertex: [[-0.868849, -0.100041, 0.61257], [-0.329458, 0.976099, 0.28078], [-0.26629, -0.013796, -0.477654], [-0.13392, -1.034115, 0.229829], [0.738834, 0.707117, -0.307018], [0.859683, -0.535264, -0.338508]], face: [[3, 0, 2], [5, 3, 2], [4, 5, 2], [1, 4, 2], [0, 1, 2], [0, 3, 5, 4, 1]] }; polyhedra[10] = { vertex: [[-0.610389, 0.243975, 0.531213], [-0.187812, -0.48795, -0.664016], [-0.187812, 0.9759, -0.664016], [0.187812, -0.9759, 0.664016], [0.798201, 0.243975, 0.132803]], face: [[1, 3, 0], [3, 4, 0], [3, 1, 4], [0, 2, 1], [0, 4, 2], [2, 4, 1]] }; polyhedra[11] = { vertex: [[-1.028778, 0.392027, -0.048786], [-0.640503, -0.646161, 0.621837], [-0.125162, -0.395663, -0.540059], [0.004683, 0.888447, -0.651988], [0.125161, 0.395663, 0.540059], [0.632925, -0.791376, 0.433102], [1.031672, 0.157063, -0.354165]], face: [[3, 2, 0], [2, 1, 0], [2, 5, 1], [0, 4, 3], [0, 1, 4], [4, 1, 5], [2, 3, 6], [3, 4, 6], [5, 2, 6], [4, 5, 6]] }; polyhedra[12] = { vertex: [[-0.669867, 0.334933, -0.529576], [-0.669867, 0.334933, 0.529577], [-0.4043, 1.212901, 0], [-0.334933, -0.669867, -0.529576], [-0.334933, -0.669867, 0.529577], [0.334933, 0.669867, -0.529576], [0.334933, 0.669867, 0.529577], [0.4043, -1.212901, 0], [0.669867, -0.334933, -0.529576], [0.669867, -0.334933, 0.529577]], face: [[8, 9, 7], [6, 5, 2], [3, 8, 7], [5, 0, 2], [4, 3, 7], [0, 1, 2], [9, 4, 7], [1, 6, 2], [9, 8, 5, 6], [8, 3, 0, 5], [3, 4, 1, 0], [4, 9, 6, 1]] }; polyhedra[13] = { vertex: [[-0.931836, 0.219976, -0.264632], [-0.636706, 0.318353, 0.692816], [-0.613483, -0.735083, -0.264632], [-0.326545, 0.979634, 0], [-0.318353, -0.636706, 0.692816], [-0.159176, 0.477529, -0.856368], [0.159176, -0.477529, -0.856368], [0.318353, 0.636706, 0.692816], [0.326545, -0.979634, 0], [0.613482, 0.735082, -0.264632], [0.636706, -0.318353, 0.692816], [0.931835, -0.219977, -0.264632]], face: [[11, 10, 8], [7, 9, 3], [6, 11, 8], [9, 5, 3], [2, 6, 8], [5, 0, 3], [4, 2, 8], [0, 1, 3], [10, 4, 8], [1, 7, 3], [10, 11, 9, 7], [11, 6, 5, 9], [6, 2, 0, 5], [2, 4, 1, 0], [4, 10, 7, 1]] }; polyhedra[14] = { vertex: [[-0.93465, 0.300459, -0.271185], [-0.838689, -0.260219, -0.516017], [-0.711319, 0.717591, 0.128359], [-0.710334, -0.156922, 0.080946], [-0.599799, 0.556003, -0.725148], [-0.503838, -0.004675, -0.969981], [-0.487004, 0.26021, 0.48049], [-0.460089, -0.750282, -0.512622], [-0.376468, 0.973135, -0.325605], [-0.331735, -0.646985, 0.084342], [-0.254001, 0.831847, 0.530001], [-0.125239, -0.494738, -0.966586], [0.029622, 0.027949, 0.730817], [0.056536, -0.982543, -0.262295], [0.08085, 1.087391, 0.076037], [0.125583, -0.532729, 0.485984], [0.262625, 0.599586, 0.780328], [0.391387, -0.726999, -0.716259], [0.513854, -0.868287, 0.139347], [0.597475, 0.85513, 0.326364], [0.641224, 0.109523, 0.783723], [0.737185, -0.451155, 0.538891], [0.848705, -0.612742, -0.314616], [0.976075, 0.365067, 0.32976], [1.072036, -0.19561, 0.084927]], face: [[15, 18, 21], [12, 20, 16], [6, 10, 2], [3, 0, 1], [9, 7, 13], [2, 8, 4, 0], [0, 4, 5, 1], [1, 5, 11, 7], [7, 11, 17, 13], [13, 17, 22, 18], [18, 22, 24, 21], [21, 24, 23, 20], [20, 23, 19, 16], [16, 19, 14, 10], [10, 14, 8, 2], [15, 9, 13, 18], [12, 15, 21, 20], [6, 12, 16, 10], [3, 6, 2, 0], [9, 3, 1, 7], [9, 15, 12, 6, 3], [22, 17, 11, 5, 4, 8, 14, 19, 23, 24]] }; var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0; var size = options.size; var sizeX = options.sizeX || size || 1; var sizeY = options.sizeY || size || 1; var sizeZ = options.sizeZ || size || 1; var data = options.custom || polyhedra[type]; var nbfaces = data.face.length; var faceUV = options.faceUV || new Array(nbfaces); var faceColors = options.faceColors; var flat = (options.flat === undefined) ? true : options.flat; var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE; var positions = new Array(); var indices = new Array(); var normals = new Array(); var uvs = new Array(); var colors = new Array(); var index = 0; var faceIdx = 0; // face cursor in the array "indexes" var indexes = new Array(); var i = 0; var f = 0; var u, v, ang, x, y, tmp; // default face colors and UV if undefined if (flat) { for (f = 0; f < nbfaces; f++) { if (faceColors && faceColors[f] === undefined) { faceColors[f] = new BABYLON.Color4(1, 1, 1, 1); } if (faceUV && faceUV[f] === undefined) { faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1); } } } if (!flat) { for (i = 0; i < data.vertex.length; i++) { positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ); uvs.push(0, 0); } for (f = 0; f < nbfaces; f++) { for (i = 0; i < data.face[f].length - 2; i++) { indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]); } } } else { for (f = 0; f < nbfaces; f++) { var fl = data.face[f].length; // number of vertices of the current face ang = 2 * Math.PI / fl; x = 0.5 * Math.tan(ang / 2); y = 0.5; // positions, uvs, colors for (i = 0; i < fl; i++) { // positions positions.push(data.vertex[data.face[f][i]][0] * sizeX, data.vertex[data.face[f][i]][1] * sizeY, data.vertex[data.face[f][i]][2] * sizeZ); indexes.push(index); index++; // uvs u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x); v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5); uvs.push(u, v); tmp = x * Math.cos(ang) - y * Math.sin(ang); y = x * Math.sin(ang) + y * Math.cos(ang); x = tmp; // colors if (faceColors) { colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a); } } // indices from indexes for (i = 0; i < fl - 2; i++) { indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]); } faceIdx += fl; } } VertexData.ComputeNormals(positions, indices, normals); VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); var vertexData = new VertexData(); vertexData.positions = positions; vertexData.indices = indices; vertexData.normals = normals; vertexData.uvs = uvs; if (faceColors && flat) { vertexData.colors = colors; } return vertexData; }; // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473 /** * Creates the VertexData for a TorusKnot * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty * * radius the radius of the torus knot, optional, default 2 * * tube the thickness of the tube, optional, default 0.5 * * radialSegments the number of sides on each tube segments, optional, default 32 * * tubularSegments the number of tubes to decompose the knot into, optional, default 32 * * p the number of windings around the z axis, optional, default 2 * * q the number of windings around the x axis, optional, default 3 * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) * @returns the VertexData of the Torus Knot */ VertexData.CreateTorusKnot = function (options) { var indices = new Array(); var positions = new Array(); var normals = new Array(); var uvs = new Array(); var radius = options.radius || 2; var tube = options.tube || 0.5; var radialSegments = options.radialSegments || 32; var tubularSegments = options.tubularSegments || 32; var p = options.p || 2; var q = options.q || 3; var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE; // Helper var getPos = function (angle) { var cu = Math.cos(angle); var su = Math.sin(angle); var quOverP = q / p * angle; var cs = Math.cos(quOverP); var tx = radius * (2 + cs) * 0.5 * cu; var ty = radius * (2 + cs) * su * 0.5; var tz = radius * Math.sin(quOverP) * 0.5; return new BABYLON.Vector3(tx, ty, tz); }; // Vertices var i; var j; for (i = 0; i <= radialSegments; i++) { var modI = i % radialSegments; var u = modI / radialSegments * 2 * p * Math.PI; var p1 = getPos(u); var p2 = getPos(u + 0.01); var tang = p2.subtract(p1); var n = p2.add(p1); var bitan = BABYLON.Vector3.Cross(tang, n); n = BABYLON.Vector3.Cross(bitan, tang); bitan.normalize(); n.normalize(); for (j = 0; j < tubularSegments; j++) { var modJ = j % tubularSegments; var v = modJ / tubularSegments * 2 * Math.PI; var cx = -tube * Math.cos(v); var cy = tube * Math.sin(v); positions.push(p1.x + cx * n.x + cy * bitan.x); positions.push(p1.y + cx * n.y + cy * bitan.y); positions.push(p1.z + cx * n.z + cy * bitan.z); uvs.push(i / radialSegments); uvs.push(j / tubularSegments); } } for (i = 0; i < radialSegments; i++) { for (j = 0; j < tubularSegments; j++) { var jNext = (j + 1) % tubularSegments; var a = i * tubularSegments + j; var b = (i + 1) * tubularSegments + j; var c = (i + 1) * tubularSegments + jNext; var d = i * tubularSegments + jNext; indices.push(d); indices.push(b); indices.push(a); indices.push(d); indices.push(c); indices.push(b); } } // Normals VertexData.ComputeNormals(positions, indices, normals); // Sides VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); // Result var vertexData = new VertexData(); vertexData.indices = indices; vertexData.positions = positions; vertexData.normals = normals; vertexData.uvs = uvs; return vertexData; }; // Tools /** * Compute normals for given positions and indices * @param positions an array of vertex positions, [...., x, y, z, ......] * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......] * @param normals an array of vertex normals, [...., x, y, z, ......] * @param options an object used to set the following optional parameters for the TorusKnot, optional * * facetNormals : optional array of facet normals (vector3) * * facetPositions : optional array of facet positions (vector3) * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation * * bInfo : optional bounding info, required for facetPartitioning computation * * bbSize : optional bounding box size data, required for facetPartitioning computation * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation * * useRightHandedSystem: optional boolean to for right handed system computation * * depthSort : optional boolean to enable the facet depth sort computation * * distanceTo : optional Vector3 to compute the facet depth from this location * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location */ VertexData.ComputeNormals = function (positions, indices, normals, options) { // temporary scalar variables var index = 0; // facet index var p1p2x = 0.0; // p1p2 vector x coordinate var p1p2y = 0.0; // p1p2 vector y coordinate var p1p2z = 0.0; // p1p2 vector z coordinate var p3p2x = 0.0; // p3p2 vector x coordinate var p3p2y = 0.0; // p3p2 vector y coordinate var p3p2z = 0.0; // p3p2 vector z coordinate var faceNormalx = 0.0; // facet normal x coordinate var faceNormaly = 0.0; // facet normal y coordinate var faceNormalz = 0.0; // facet normal z coordinate var length = 0.0; // facet normal length before normalization var v1x = 0; // vector1 x index in the positions array var v1y = 0; // vector1 y index in the positions array var v1z = 0; // vector1 z index in the positions array var v2x = 0; // vector2 x index in the positions array var v2y = 0; // vector2 y index in the positions array var v2z = 0; // vector2 z index in the positions array var v3x = 0; // vector3 x index in the positions array var v3y = 0; // vector3 y index in the positions array var v3z = 0; // vector3 z index in the positions array var computeFacetNormals = false; var computeFacetPositions = false; var computeFacetPartitioning = false; var computeDepthSort = false; var faceNormalSign = 1; var ratio = 0; var distanceTo = null; if (options) { computeFacetNormals = (options.facetNormals) ? true : false; computeFacetPositions = (options.facetPositions) ? true : false; computeFacetPartitioning = (options.facetPartitioning) ? true : false; faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1; ratio = options.ratio || 0; computeDepthSort = (options.depthSort) ? true : false; distanceTo = (options.distanceTo); if (computeDepthSort) { if (distanceTo === undefined) { distanceTo = BABYLON.Vector3.Zero(); } var depthSortedFacets = options.depthSortedFacets; } } // facetPartitioning reinit if needed var xSubRatio = 0; var ySubRatio = 0; var zSubRatio = 0; var subSq = 0; if (computeFacetPartitioning && options && options.bbSize) { var ox = 0; // X partitioning index for facet position var oy = 0; // Y partinioning index for facet position var oz = 0; // Z partinioning index for facet position var b1x = 0; // X partitioning index for facet v1 vertex var b1y = 0; // Y partitioning index for facet v1 vertex var b1z = 0; // z partitioning index for facet v1 vertex var b2x = 0; // X partitioning index for facet v2 vertex var b2y = 0; // Y partitioning index for facet v2 vertex var b2z = 0; // Z partitioning index for facet v2 vertex var b3x = 0; // X partitioning index for facet v3 vertex var b3y = 0; // Y partitioning index for facet v3 vertex var b3z = 0; // Z partitioning index for facet v3 vertex var block_idx_o = 0; // facet barycenter block index var block_idx_v1 = 0; // v1 vertex block index var block_idx_v2 = 0; // v2 vertex block index var block_idx_v3 = 0; // v3 vertex block index var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y; bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z; xSubRatio = options.subDiv.X * ratio / options.bbSize.x; ySubRatio = options.subDiv.Y * ratio / options.bbSize.y; zSubRatio = options.subDiv.Z * ratio / options.bbSize.z; subSq = options.subDiv.max * options.subDiv.max; options.facetPartitioning.length = 0; } // reset the normals for (index = 0; index < positions.length; index++) { normals[index] = 0.0; } // Loop : 1 indice triplet = 1 facet var nbFaces = (indices.length / 3) | 0; for (index = 0; index < nbFaces; index++) { // get the indexes of the coordinates of each vertex of the facet v1x = indices[index * 3] * 3; v1y = v1x + 1; v1z = v1x + 2; v2x = indices[index * 3 + 1] * 3; v2y = v2x + 1; v2z = v2x + 2; v3x = indices[index * 3 + 2] * 3; v3y = v3x + 1; v3z = v3x + 2; p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2 p1p2y = positions[v1y] - positions[v2y]; p1p2z = positions[v1z] - positions[v2z]; p3p2x = positions[v3x] - positions[v2x]; p3p2y = positions[v3y] - positions[v2y]; p3p2z = positions[v3z] - positions[v2z]; // compute the face normal with the cross product faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y); faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z); faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x); // normalize this normal and store it in the array facetData length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz); length = (length === 0) ? 1.0 : length; faceNormalx /= length; faceNormaly /= length; faceNormalz /= length; if (computeFacetNormals && options) { options.facetNormals[index].x = faceNormalx; options.facetNormals[index].y = faceNormaly; options.facetNormals[index].z = faceNormalz; } if (computeFacetPositions && options) { // compute and the facet barycenter coordinates in the array facetPositions options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0; options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0; options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0; } if (computeFacetPartitioning && options) { // store the facet indexes in arrays in the main facetPartitioning array : // compute each facet vertex (+ facet barycenter) index in the partiniong array ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio); oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio); oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio); b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio); b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio); b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio); b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio); b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio); b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio); b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio); b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio); b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio); block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z; block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z; block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z; block_idx_o = ox + options.subDiv.max * oy + subSq * oz; options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array(); options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array(); options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array(); options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array(); // push each facet index in each block containing the vertex options.facetPartitioning[block_idx_v1].push(index); if (block_idx_v2 != block_idx_v1) { options.facetPartitioning[block_idx_v2].push(index); } if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) { options.facetPartitioning[block_idx_v3].push(index); } if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) { options.facetPartitioning[block_idx_o].push(index); } } if (computeDepthSort && options && options.facetPositions) { var dsf = depthSortedFacets[index]; dsf.ind = index * 3; dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo); } // compute the normals anyway normals[v1x] += faceNormalx; // accumulate all the normals per face normals[v1y] += faceNormaly; normals[v1z] += faceNormalz; normals[v2x] += faceNormalx; normals[v2y] += faceNormaly; normals[v2z] += faceNormalz; normals[v3x] += faceNormalx; normals[v3y] += faceNormaly; normals[v3z] += faceNormalz; } // last normalization of each normal for (index = 0; index < normals.length / 3; index++) { faceNormalx = normals[index * 3]; faceNormaly = normals[index * 3 + 1]; faceNormalz = normals[index * 3 + 2]; length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz); length = (length === 0) ? 1.0 : length; faceNormalx /= length; faceNormaly /= length; faceNormalz /= length; normals[index * 3] = faceNormalx; normals[index * 3 + 1] = faceNormaly; normals[index * 3 + 2] = faceNormalz; } }; VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) { var li = indices.length; var ln = normals.length; var i; var n; sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE; switch (sideOrientation) { case BABYLON.Mesh.FRONTSIDE: // nothing changed break; case BABYLON.Mesh.BACKSIDE: var tmp; // indices for (i = 0; i < li; i += 3) { tmp = indices[i]; indices[i] = indices[i + 2]; indices[i + 2] = tmp; } // normals for (n = 0; n < ln; n++) { normals[n] = -normals[n]; } break; case BABYLON.Mesh.DOUBLESIDE: // positions var lp = positions.length; var l = lp / 3; for (var p = 0; p < lp; p++) { positions[lp + p] = positions[p]; } // indices for (i = 0; i < li; i += 3) { indices[i + li] = indices[i + 2] + l; indices[i + 1 + li] = indices[i + 1] + l; indices[i + 2 + li] = indices[i] + l; } // normals for (n = 0; n < ln; n++) { normals[ln + n] = -normals[n]; } // uvs var lu = uvs.length; var u = 0; for (u = 0; u < lu; u++) { uvs[u + lu] = uvs[u]; } frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); u = 0; for (i = 0; i < lu / 2; i++) { uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u]; uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1]; uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu]; uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1]; u += 2; } break; } }; /** * Applies VertexData created from the imported parameters to the geometry * @param parsedVertexData the parsed data from an imported file * @param geometry the geometry to apply the VertexData to */ VertexData.ImportVertexData = function (parsedVertexData, geometry) { var vertexData = new VertexData(); // positions var positions = parsedVertexData.positions; if (positions) { vertexData.set(positions, BABYLON.VertexBuffer.PositionKind); } // normals var normals = parsedVertexData.normals; if (normals) { vertexData.set(normals, BABYLON.VertexBuffer.NormalKind); } // tangents var tangents = parsedVertexData.tangents; if (tangents) { vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind); } // uvs var uvs = parsedVertexData.uvs; if (uvs) { vertexData.set(uvs, BABYLON.VertexBuffer.UVKind); } // uv2s var uv2s = parsedVertexData.uv2s; if (uv2s) { vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind); } // uv3s var uv3s = parsedVertexData.uv3s; if (uv3s) { vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind); } // uv4s var uv4s = parsedVertexData.uv4s; if (uv4s) { vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind); } // uv5s var uv5s = parsedVertexData.uv5s; if (uv5s) { vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind); } // uv6s var uv6s = parsedVertexData.uv6s; if (uv6s) { vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind); } // colors var colors = parsedVertexData.colors; if (colors) { vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind); } // matricesIndices var matricesIndices = parsedVertexData.matricesIndices; if (matricesIndices) { vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind); } // matricesWeights var matricesWeights = parsedVertexData.matricesWeights; if (matricesWeights) { vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind); } // indices var indices = parsedVertexData.indices; if (indices) { vertexData.indices = indices; } geometry.setAllVerticesData(vertexData, parsedVertexData.updatable); }; return VertexData; }()); BABYLON.VertexData = VertexData; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.mesh.vertexData.js.map var BABYLON; (function (BABYLON) { /** * Class used to store geometry data (vertex buffers + index buffer) */ var Geometry = /** @class */ (function () { /** * Creates a new geometry * @param id defines the unique ID * @param scene defines the hosting scene * @param vertexData defines the {BABYLON.VertexData} used to get geometry data * @param updatable defines if geometry must be updatable (false by default) * @param mesh defines the mesh that will be associated with the geometry */ function Geometry(id, scene, vertexData, updatable, mesh) { if (updatable === void 0) { updatable = false; } if (mesh === void 0) { mesh = null; } /** * Gets the delay loading state of the geometry (none by default which means not delayed) */ this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE; this._totalVertices = 0; this._isDisposed = false; this._indexBufferIsUpdatable = false; this.id = id; this._engine = scene.getEngine(); this._meshes = []; this._scene = scene; //Init vertex buffer cache this._vertexBuffers = {}; this._indices = []; this._updatable = updatable; // vertexData if (vertexData) { this.setAllVerticesData(vertexData, updatable); } else { this._totalVertices = 0; this._indices = []; } if (this._engine.getCaps().vertexArrayObject) { this._vertexArrayObjects = {}; } // applyToMesh if (mesh) { if (mesh.getClassName() === "LinesMesh") { this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold); this._updateExtend(); } this.applyToMesh(mesh); mesh.computeWorldMatrix(true); } } Object.defineProperty(Geometry.prototype, "boundingBias", { /** * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y */ get: function () { return this._boundingBias; }, /** * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y */ set: function (value) { if (this._boundingBias && this._boundingBias.equals(value)) { return; } this._boundingBias = value.clone(); this._updateBoundingInfo(true, null); }, enumerable: true, configurable: true }); /** * Static function used to attach a new empty geometry to a mesh * @param mesh defines the mesh to attach the geometry to * @returns the new {BABYLON.Geometry} */ Geometry.CreateGeometryForMesh = function (mesh) { var geometry = new Geometry(Geometry.RandomId(), mesh.getScene()); geometry.applyToMesh(mesh); return geometry; }; Object.defineProperty(Geometry.prototype, "extend", { /** * Gets the current extend of the geometry */ get: function () { return this._extend; }, enumerable: true, configurable: true }); /** * Gets the hosting scene * @returns the hosting {BABYLON.Scene} */ Geometry.prototype.getScene = function () { return this._scene; }; /** * Gets the hosting engine * @returns the hosting {BABYLON.Engine} */ Geometry.prototype.getEngine = function () { return this._engine; }; /** * Defines if the geometry is ready to use * @returns true if the geometry is ready to be used */ Geometry.prototype.isReady = function () { return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE; }; Object.defineProperty(Geometry.prototype, "doNotSerialize", { /** * Gets a value indicating that the geometry should not be serialized */ get: function () { for (var index = 0; index < this._meshes.length; index++) { if (!this._meshes[index].doNotSerialize) { return false; } } return true; }, enumerable: true, configurable: true }); /** @hidden */ Geometry.prototype._rebuild = function () { if (this._vertexArrayObjects) { this._vertexArrayObjects = {}; } // Index buffer if (this._meshes.length !== 0 && this._indices) { this._indexBuffer = this._engine.createIndexBuffer(this._indices); } // Vertex buffers for (var key in this._vertexBuffers) { var vertexBuffer = this._vertexBuffers[key]; vertexBuffer._rebuild(); } }; /** * Affects all gemetry data in one call * @param vertexData defines the geometry data * @param updatable defines if the geometry must be flagged as updatable (false as default) */ Geometry.prototype.setAllVerticesData = function (vertexData, updatable) { vertexData.applyToGeometry(this, updatable); this.notifyUpdate(); }; /** * Set specific vertex data * @param kind defines the data kind (Position, normal, etc...) * @param data defines the vertex data to use * @param updatable defines if the vertex must be flagged as updatable (false as default) * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified */ Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) { if (updatable === void 0) { updatable = false; } var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride); this.setVerticesBuffer(buffer); }; /** * Removes a specific vertex data * @param kind defines the data kind (Position, normal, etc...) */ Geometry.prototype.removeVerticesData = function (kind) { if (this._vertexBuffers[kind]) { this._vertexBuffers[kind].dispose(); delete this._vertexBuffers[kind]; } }; /** * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data * @param buffer defines the vertex buffer to use * @param totalVertices defines the total number of vertices for position kind (could be null) */ Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) { if (totalVertices === void 0) { totalVertices = null; } var kind = buffer.getKind(); if (this._vertexBuffers[kind]) { this._vertexBuffers[kind].dispose(); } this._vertexBuffers[kind] = buffer; if (kind === BABYLON.VertexBuffer.PositionKind) { var data = buffer.getData(); if (totalVertices != null) { this._totalVertices = totalVertices; } else { if (data != null) { this._totalVertices = data.length / (buffer.byteStride / 4); } } this._updateExtend(data); this._resetPointsArrayCache(); var meshes = this._meshes; var numOfMeshes = meshes.length; for (var index = 0; index < numOfMeshes; index++) { var mesh = meshes[index]; mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum); mesh._createGlobalSubMesh(false); mesh.computeWorldMatrix(true); } } this.notifyUpdate(kind); if (this._vertexArrayObjects) { this._disposeVertexArrayObjects(); this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported } }; /** * Update a specific vertex buffer * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array * It will do nothing if the buffer is not updatable * @param kind defines the data kind (Position, normal, etc...) * @param data defines the data to use * @param offset defines the offset in the target buffer where to store the data * @param useBytes set to true if the offset is in bytes */ Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) { if (useBytes === void 0) { useBytes = false; } var vertexBuffer = this.getVertexBuffer(kind); if (!vertexBuffer) { return; } vertexBuffer.updateDirectly(data, offset, useBytes); this.notifyUpdate(kind); }; /** * Update a specific vertex buffer * This function will create a new buffer if the current one is not updatable * @param kind defines the data kind (Position, normal, etc...) * @param data defines the data to use * @param updateExtends defines if the geometry extends must be recomputed (false by default) */ Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) { if (updateExtends === void 0) { updateExtends = false; } var vertexBuffer = this.getVertexBuffer(kind); if (!vertexBuffer) { return; } vertexBuffer.update(data); if (kind === BABYLON.VertexBuffer.PositionKind) { this._updateBoundingInfo(updateExtends, data); } this.notifyUpdate(kind); }; Geometry.prototype._updateBoundingInfo = function (updateExtends, data) { if (updateExtends) { this._updateExtend(data); } var meshes = this._meshes; var numOfMeshes = meshes.length; this._resetPointsArrayCache(); for (var index = 0; index < numOfMeshes; index++) { var mesh = meshes[index]; if (updateExtends) { mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum); for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) { var subMesh = mesh.subMeshes[subIndex]; subMesh.refreshBoundingInfo(); } } } }; /** @hidden */ Geometry.prototype._bind = function (effect, indexToBind) { if (!effect) { return; } if (indexToBind === undefined) { indexToBind = this._indexBuffer; } var vbs = this.getVertexBuffers(); if (!vbs) { return; } if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) { this._engine.bindBuffers(vbs, indexToBind, effect); return; } // Using VAO if (!this._vertexArrayObjects[effect.key]) { this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect); } this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind); }; /** * Gets total number of vertices * @returns the total number of vertices */ Geometry.prototype.getTotalVertices = function () { if (!this.isReady()) { return 0; } return this._totalVertices; }; /** * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly. * @param kind defines the data kind (Position, normal, etc...) * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it * @returns a float array containing vertex data */ Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) { var vertexBuffer = this.getVertexBuffer(kind); if (!vertexBuffer) { return null; } var data = vertexBuffer.getData(); if (!data) { return null; } var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type); var count = this._totalVertices * vertexBuffer.getSize(); if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) { var copy_1 = new Array(count); vertexBuffer.forEach(count, function (value, index) { copy_1[index] = value; }); return copy_1; } if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) { if (data instanceof Array) { var offset = vertexBuffer.byteOffset / 4; return BABYLON.Tools.Slice(data, offset, offset + count); } else if (data instanceof ArrayBuffer) { return new Float32Array(data, vertexBuffer.byteOffset, count); } else { return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count); } } if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) { return BABYLON.Tools.Slice(data); } return data; }; /** * Returns a boolean defining if the vertex data for the requested `kind` is updatable * @param kind defines the data kind (Position, normal, etc...) * @returns true if the vertex buffer with the specified kind is updatable */ Geometry.prototype.isVertexBufferUpdatable = function (kind) { var vb = this._vertexBuffers[kind]; if (!vb) { return false; } return vb.isUpdatable(); }; /** * Gets a specific vertex buffer * @param kind defines the data kind (Position, normal, etc...) * @returns a {BABYLON.VertexBuffer} */ Geometry.prototype.getVertexBuffer = function (kind) { if (!this.isReady()) { return null; } return this._vertexBuffers[kind]; }; /** * Returns all vertex buffers * @return an object holding all vertex buffers indexed by kind */ Geometry.prototype.getVertexBuffers = function () { if (!this.isReady()) { return null; } return this._vertexBuffers; }; /** * Gets a boolean indicating if specific vertex buffer is present * @param kind defines the data kind (Position, normal, etc...) * @returns true if data is present */ Geometry.prototype.isVerticesDataPresent = function (kind) { if (!this._vertexBuffers) { if (this._delayInfo) { return this._delayInfo.indexOf(kind) !== -1; } return false; } return this._vertexBuffers[kind] !== undefined; }; /** * Gets a list of all attached data kinds (Position, normal, etc...) * @returns a list of string containing all kinds */ Geometry.prototype.getVerticesDataKinds = function () { var result = []; var kind; if (!this._vertexBuffers && this._delayInfo) { for (kind in this._delayInfo) { result.push(kind); } } else { for (kind in this._vertexBuffers) { result.push(kind); } } return result; }; /** * Update index buffer * @param indices defines the indices to store in the index buffer * @param offset defines the offset in the target buffer where to store the data */ Geometry.prototype.updateIndices = function (indices, offset) { if (!this._indexBuffer) { return; } if (!this._indexBufferIsUpdatable) { this.setIndices(indices, null, true); } else { this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset); } }; /** * Creates a new index buffer * @param indices defines the indices to store in the index buffer * @param totalVertices defines the total number of vertices (could be null) * @param updatable defines if the index buffer must be flagged as updatable (false by default) */ Geometry.prototype.setIndices = function (indices, totalVertices, updatable) { if (totalVertices === void 0) { totalVertices = null; } if (updatable === void 0) { updatable = false; } if (this._indexBuffer) { this._engine._releaseBuffer(this._indexBuffer); } this._disposeVertexArrayObjects(); this._indices = indices; this._indexBufferIsUpdatable = updatable; if (this._meshes.length !== 0 && this._indices) { this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable); } if (totalVertices != undefined) { // including null and undefined this._totalVertices = totalVertices; } var meshes = this._meshes; var numOfMeshes = meshes.length; for (var index = 0; index < numOfMeshes; index++) { meshes[index]._createGlobalSubMesh(true); } this.notifyUpdate(); }; /** * Return the total number of indices * @returns the total number of indices */ Geometry.prototype.getTotalIndices = function () { if (!this.isReady()) { return 0; } return this._indices.length; }; /** * Gets the index buffer array * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes * @returns the index buffer array */ Geometry.prototype.getIndices = function (copyWhenShared) { if (!this.isReady()) { return null; } var orig = this._indices; if (!copyWhenShared || this._meshes.length === 1) { return orig; } else { var len = orig.length; var copy = []; for (var i = 0; i < len; i++) { copy.push(orig[i]); } return copy; } }; /** * Gets the index buffer * @return the index buffer */ Geometry.prototype.getIndexBuffer = function () { if (!this.isReady()) { return null; } return this._indexBuffer; }; /** @hidden */ Geometry.prototype._releaseVertexArrayObject = function (effect) { if (effect === void 0) { effect = null; } if (!effect || !this._vertexArrayObjects) { return; } if (this._vertexArrayObjects[effect.key]) { this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]); delete this._vertexArrayObjects[effect.key]; } }; /** * Release the associated resources for a specific mesh * @param mesh defines the source mesh * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it */ Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) { var meshes = this._meshes; var index = meshes.indexOf(mesh); if (index === -1) { return; } meshes.splice(index, 1); mesh._geometry = null; if (meshes.length === 0 && shouldDispose) { this.dispose(); } }; /** * Apply current geometry to a given mesh * @param mesh defines the mesh to apply geometry to */ Geometry.prototype.applyToMesh = function (mesh) { if (mesh._geometry === this) { return; } var previousGeometry = mesh._geometry; if (previousGeometry) { previousGeometry.releaseForMesh(mesh); } var meshes = this._meshes; // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh() mesh._geometry = this; this._scene.pushGeometry(this); meshes.push(mesh); if (this.isReady()) { this._applyToMesh(mesh); } else { mesh._boundingInfo = this._boundingInfo; } }; Geometry.prototype._updateExtend = function (data) { if (data === void 0) { data = null; } if (!data) { data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind); } this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3); }; Geometry.prototype._applyToMesh = function (mesh) { var numOfMeshes = this._meshes.length; // vertexBuffers for (var kind in this._vertexBuffers) { if (numOfMeshes === 1) { this._vertexBuffers[kind].create(); } var buffer = this._vertexBuffers[kind].getBuffer(); if (buffer) buffer.references = numOfMeshes; if (kind === BABYLON.VertexBuffer.PositionKind) { if (!this._extend) { this._updateExtend(); } mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum); mesh._createGlobalSubMesh(false); //bounding info was just created again, world matrix should be applied again. mesh._updateBoundingInfo(); } } // indexBuffer if (numOfMeshes === 1 && this._indices && this._indices.length > 0) { this._indexBuffer = this._engine.createIndexBuffer(this._indices); } if (this._indexBuffer) { this._indexBuffer.references = numOfMeshes; } }; Geometry.prototype.notifyUpdate = function (kind) { if (this.onGeometryUpdated) { this.onGeometryUpdated(this, kind); } for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) { var mesh = _a[_i]; mesh._markSubMeshesAsAttributesDirty(); } }; /** * Load the geometry if it was flagged as delay loaded * @param scene defines the hosting scene * @param onLoaded defines a callback called when the geometry is loaded */ Geometry.prototype.load = function (scene, onLoaded) { if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) { return; } if (this.isReady()) { if (onLoaded) { onLoaded(); } return; } this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING; this._queueLoad(scene, onLoaded); }; Geometry.prototype._queueLoad = function (scene, onLoaded) { var _this = this; if (!this.delayLoadingFile) { return; } scene._addPendingData(this); scene._loadFile(this.delayLoadingFile, function (data) { if (!_this._delayLoadingFunction) { return; } _this._delayLoadingFunction(JSON.parse(data), _this); _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED; _this._delayInfo = []; scene._removePendingData(_this); var meshes = _this._meshes; var numOfMeshes = meshes.length; for (var index = 0; index < numOfMeshes; index++) { _this._applyToMesh(meshes[index]); } if (onLoaded) { onLoaded(); } }, undefined, true); }; /** * Invert the geometry to move from a right handed system to a left handed one. */ Geometry.prototype.toLeftHanded = function () { // Flip faces var tIndices = this.getIndices(false); if (tIndices != null && tIndices.length > 0) { for (var i = 0; i < tIndices.length; i += 3) { var tTemp = tIndices[i + 0]; tIndices[i + 0] = tIndices[i + 2]; tIndices[i + 2] = tTemp; } this.setIndices(tIndices); } // Negate position.z var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false); if (tPositions != null && tPositions.length > 0) { for (var i = 0; i < tPositions.length; i += 3) { tPositions[i + 2] = -tPositions[i + 2]; } this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false); } // Negate normal.z var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false); if (tNormals != null && tNormals.length > 0) { for (var i = 0; i < tNormals.length; i += 3) { tNormals[i + 2] = -tNormals[i + 2]; } this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false); } }; // Cache /** @hidden */ Geometry.prototype._resetPointsArrayCache = function () { this._positions = null; }; /** @hidden */ Geometry.prototype._generatePointsArray = function () { if (this._positions) return true; var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind); if (!data || data.length === 0) { return false; } this._positions = []; for (var index = 0; index < data.length; index += 3) { this._positions.push(BABYLON.Vector3.FromArray(data, index)); } return true; }; /** * Gets a value indicating if the geometry is disposed * @returns true if the geometry was disposed */ Geometry.prototype.isDisposed = function () { return this._isDisposed; }; Geometry.prototype._disposeVertexArrayObjects = function () { if (this._vertexArrayObjects) { for (var kind in this._vertexArrayObjects) { this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]); } this._vertexArrayObjects = {}; } }; /** * Free all associated resources */ Geometry.prototype.dispose = function () { var meshes = this._meshes; var numOfMeshes = meshes.length; var index; for (index = 0; index < numOfMeshes; index++) { this.releaseForMesh(meshes[index]); } this._meshes = []; this._disposeVertexArrayObjects(); for (var kind in this._vertexBuffers) { this._vertexBuffers[kind].dispose(); } this._vertexBuffers = {}; this._totalVertices = 0; if (this._indexBuffer) { this._engine._releaseBuffer(this._indexBuffer); } this._indexBuffer = null; this._indices = []; this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE; this.delayLoadingFile = null; this._delayLoadingFunction = null; this._delayInfo = []; this._boundingInfo = null; this._scene.removeGeometry(this); this._isDisposed = true; }; /** * Clone the current geometry into a new geometry * @param id defines the unique ID of the new geometry * @returns a new geometry object */ Geometry.prototype.copy = function (id) { var vertexData = new BABYLON.VertexData(); vertexData.indices = []; var indices = this.getIndices(); if (indices) { for (var index = 0; index < indices.length; index++) { vertexData.indices.push(indices[index]); } } var updatable = false; var stopChecking = false; var kind; for (kind in this._vertexBuffers) { // using slice() to make a copy of the array and not just reference it var data = this.getVerticesData(kind); if (data instanceof Float32Array) { vertexData.set(new Float32Array(data), kind); } else { vertexData.set(data.slice(0), kind); } if (!stopChecking) { var vb = this.getVertexBuffer(kind); if (vb) { updatable = vb.isUpdatable(); stopChecking = !updatable; } } } var geometry = new Geometry(id, this._scene, vertexData, updatable); geometry.delayLoadState = this.delayLoadState; geometry.delayLoadingFile = this.delayLoadingFile; geometry._delayLoadingFunction = this._delayLoadingFunction; for (kind in this._delayInfo) { geometry._delayInfo = geometry._delayInfo || []; geometry._delayInfo.push(kind); } // Bounding info geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum); return geometry; }; /** * Serialize the current geometry info (and not the vertices data) into a JSON object * @return a JSON representation of the current geometry data (without the vertices data) */ Geometry.prototype.serialize = function () { var serializationObject = {}; serializationObject.id = this.id; serializationObject.updatable = this._updatable; if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) { serializationObject.tags = BABYLON.Tags.GetTags(this); } return serializationObject; }; Geometry.prototype.toNumberArray = function (origin) { if (Array.isArray(origin)) { return origin; } else { return Array.prototype.slice.call(origin); } }; /** * Serialize all vertices data into a JSON oject * @returns a JSON representation of the current geometry data */ Geometry.prototype.serializeVerticeData = function () { var serializationObject = this.serialize(); if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) { serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind)); if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) { serializationObject.positions._updatable = true; } } if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) { serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind)); if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) { serializationObject.normals._updatable = true; } } if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) { serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind)); if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) { serializationObject.tangets._updatable = true; } } if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) { serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind)); if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) { serializationObject.uvs._updatable = true; } } if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) { serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind)); if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) { serializationObject.uv2s._updatable = true; } } if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) { serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind)); if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) { serializationObject.uv3s._updatable = true; } } if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) { serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind)); if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) { serializationObject.uv4s._updatable = true; } } if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) { serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind)); if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) { serializationObject.uv5s._updatable = true; } } if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) { serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind)); if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) { serializationObject.uv6s._updatable = true; } } if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) { serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind)); if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) { serializationObject.colors._updatable = true; } } if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) { serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind)); serializationObject.matricesIndices._isExpanded = true; if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) { serializationObject.matricesIndices._updatable = true; } } if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) { serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind)); if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) { serializationObject.matricesWeights._updatable = true; } } serializationObject.indices = this.toNumberArray(this.getIndices()); return serializationObject; }; // Statics /** * Extracts a clone of a mesh geometry * @param mesh defines the source mesh * @param id defines the unique ID of the new geometry object * @returns the new geometry object */ Geometry.ExtractFromMesh = function (mesh, id) { var geometry = mesh._geometry; if (!geometry) { return null; } return geometry.copy(id); }; /** * You should now use Tools.RandomId(), this method is still here for legacy reasons. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523 * Be aware Math.random() could cause collisions, but: * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide" * @returns a string containing a new GUID */ Geometry.RandomId = function () { return BABYLON.Tools.RandomId(); }; /** @hidden */ Geometry._ImportGeometry = function (parsedGeometry, mesh) { var scene = mesh.getScene(); // Geometry var geometryId = parsedGeometry.geometryId; if (geometryId) { var geometry = scene.getGeometryByID(geometryId); if (geometry) { geometry.applyToMesh(mesh); } } else if (parsedGeometry instanceof ArrayBuffer) { var binaryInfo = mesh._binaryInfo; if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) { var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count); mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false); } if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) { var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count); mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false); } if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) { var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count); mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false); } if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) { var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count); mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false); } if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) { var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count); mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false); } if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) { var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count); mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false); } if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) { var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count); mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false); } if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) { var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count); mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false); } if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) { var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count); mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false); } if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) { var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count); mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride); } if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) { var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count); mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false); } if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) { var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count); mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false); } if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) { var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count); mesh.setIndices(indicesData, null); } if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) { var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5); mesh.subMeshes = []; for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) { var materialIndex = subMeshesData[(i * 5) + 0]; var verticesStart = subMeshesData[(i * 5) + 1]; var verticesCount = subMeshesData[(i * 5) + 2]; var indexStart = subMeshesData[(i * 5) + 3]; var indexCount = subMeshesData[(i * 5) + 4]; BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh); } } } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) { mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable); mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable); if (parsedGeometry.tangents) { mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable); } if (parsedGeometry.uvs) { mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable); } if (parsedGeometry.uvs2) { mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable); } if (parsedGeometry.uvs3) { mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable); } if (parsedGeometry.uvs4) { mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable); } if (parsedGeometry.uvs5) { mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable); } if (parsedGeometry.uvs6) { mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable); } if (parsedGeometry.colors) { mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable); } if (parsedGeometry.matricesIndices) { if (!parsedGeometry.matricesIndices._isExpanded) { var floatIndices = []; for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) { var matricesIndex = parsedGeometry.matricesIndices[i]; floatIndices.push(matricesIndex & 0x000000FF); floatIndices.push((matricesIndex & 0x0000FF00) >> 8); floatIndices.push((matricesIndex & 0x00FF0000) >> 16); floatIndices.push(matricesIndex >> 24); } mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable); } else { delete parsedGeometry.matricesIndices._isExpanded; mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable); } } if (parsedGeometry.matricesIndicesExtra) { if (!parsedGeometry.matricesIndicesExtra._isExpanded) { var floatIndices = []; for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) { var matricesIndex = parsedGeometry.matricesIndicesExtra[i]; floatIndices.push(matricesIndex & 0x000000FF); floatIndices.push((matricesIndex & 0x0000FF00) >> 8); floatIndices.push((matricesIndex & 0x00FF0000) >> 16); floatIndices.push(matricesIndex >> 24); } mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable); } else { delete parsedGeometry.matricesIndices._isExpanded; mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable); } } if (parsedGeometry.matricesWeights) { Geometry._CleanMatricesWeights(parsedGeometry, mesh); mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable); } if (parsedGeometry.matricesWeightsExtra) { mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable); } mesh.setIndices(parsedGeometry.indices, null); } // SubMeshes if (parsedGeometry.subMeshes) { mesh.subMeshes = []; for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) { var parsedSubMesh = parsedGeometry.subMeshes[subIndex]; BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh); } } // Flat shading if (mesh._shouldGenerateFlatShading) { mesh.convertToFlatShadedMesh(); delete mesh._shouldGenerateFlatShading; } // Update mesh.computeWorldMatrix(true); // Octree var sceneOctree = scene.selectionOctree; if (sceneOctree !== undefined && sceneOctree !== null) { sceneOctree.addMesh(mesh); } }; Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) { var epsilon = 1e-3; if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) { return; } var noInfluenceBoneIndex = 0.0; if (parsedGeometry.skeletonId > -1) { var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId); if (!skeleton) { return; } noInfluenceBoneIndex = skeleton.bones.length; } else { return; } var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind); var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind); var matricesWeights = parsedGeometry.matricesWeights; var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra; var influencers = parsedGeometry.numBoneInfluencer; var size = matricesWeights.length; for (var i = 0; i < size; i += 4) { var weight = 0.0; var firstZeroWeight = -1; for (var j = 0; j < 4; j++) { var w = matricesWeights[i + j]; weight += w; if (w < epsilon && firstZeroWeight < 0) { firstZeroWeight = j; } } if (matricesWeightsExtra) { for (var j = 0; j < 4; j++) { var w = matricesWeightsExtra[i + j]; weight += w; if (w < epsilon && firstZeroWeight < 0) { firstZeroWeight = j + 4; } } } if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) { firstZeroWeight = influencers - 1; } if (weight > epsilon) { var mweight = 1.0 / weight; for (var j = 0; j < 4; j++) { matricesWeights[i + j] *= mweight; } if (matricesWeightsExtra) { for (var j = 0; j < 4; j++) { matricesWeightsExtra[i + j] *= mweight; } } } else { if (firstZeroWeight >= 4) { matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight; matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex; } else { matricesWeights[i + firstZeroWeight] = 1.0 - weight; matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex; } } } mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices); if (parsedGeometry.matricesWeightsExtra) { mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra); } }; /** * Create a new geometry from persisted data (Using .babylon file format) * @param parsedVertexData defines the persisted data * @param scene defines the hosting scene * @param rootUrl defines the root url to use to load assets (like delayed data) * @returns the new geometry object */ Geometry.Parse = function (parsedVertexData, scene, rootUrl) { if (scene.getGeometryByID(parsedVertexData.id)) { return null; // null since geometry could be something else than a box... } var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable); if (BABYLON.Tags) { BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags); } if (parsedVertexData.delayLoadingFile) { geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED; geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile; geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum)); geometry._delayInfo = []; if (parsedVertexData.hasUVs) { geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind); } if (parsedVertexData.hasUVs2) { geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind); } if (parsedVertexData.hasUVs3) { geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind); } if (parsedVertexData.hasUVs4) { geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind); } if (parsedVertexData.hasUVs5) { geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind); } if (parsedVertexData.hasUVs6) { geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind); } if (parsedVertexData.hasColors) { geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind); } if (parsedVertexData.hasMatricesIndices) { geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind); } if (parsedVertexData.hasMatricesWeights) { geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind); } geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData; } else { BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry); } scene.pushGeometry(geometry, true); return geometry; }; return Geometry; }()); BABYLON.Geometry = Geometry; // Primitives /// Abstract class /** * Abstract class used to provide common services for all typed geometries * @hidden */ var _PrimitiveGeometry = /** @class */ (function (_super) { __extends(_PrimitiveGeometry, _super); /** * Creates a new typed geometry * @param id defines the unique ID of the geometry * @param scene defines the hosting scene * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) * @param mesh defines the hosting mesh (can be null) */ function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) { if (_canBeRegenerated === void 0) { _canBeRegenerated = false; } if (mesh === void 0) { mesh = null; } var _this = _super.call(this, id, scene, undefined, false, mesh) || this; _this._canBeRegenerated = _canBeRegenerated; _this._beingRegenerated = true; _this.regenerate(); _this._beingRegenerated = false; return _this; } /** * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default) * @returns true if the geometry can be regenerated */ _PrimitiveGeometry.prototype.canBeRegenerated = function () { return this._canBeRegenerated; }; /** * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values */ _PrimitiveGeometry.prototype.regenerate = function () { if (!this._canBeRegenerated) { return; } this._beingRegenerated = true; this.setAllVerticesData(this._regenerateVertexData(), false); this._beingRegenerated = false; }; /** * Clone the geometry * @param id defines the unique ID of the new geometry * @returns the new geometry */ _PrimitiveGeometry.prototype.asNewGeometry = function (id) { return _super.prototype.copy.call(this, id); }; // overrides _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) { if (!this._beingRegenerated) { return; } _super.prototype.setAllVerticesData.call(this, vertexData, false); }; _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) { if (!this._beingRegenerated) { return; } _super.prototype.setVerticesData.call(this, kind, data, false); }; // to override /** @hidden */ _PrimitiveGeometry.prototype._regenerateVertexData = function () { throw new Error("Abstract method"); }; _PrimitiveGeometry.prototype.copy = function (id) { throw new Error("Must be overriden in sub-classes."); }; _PrimitiveGeometry.prototype.serialize = function () { var serializationObject = _super.prototype.serialize.call(this); serializationObject.canBeRegenerated = this.canBeRegenerated(); return serializationObject; }; return _PrimitiveGeometry; }(Geometry)); BABYLON._PrimitiveGeometry = _PrimitiveGeometry; /** * Creates a ribbon geometry * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons */ var RibbonGeometry = /** @class */ (function (_super) { __extends(RibbonGeometry, _super); /** * Creates a ribbon geometry * @param id defines the unique ID of the geometry * @param scene defines the hosting scene * @param pathArray defines the array of paths to use * @param closeArray defines if the last path and the first path must be joined * @param closePath defines if the last and first points of each path in your pathArray must be joined * @param offset defines the offset between points * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) * @param mesh defines the hosting mesh (can be null) * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ function RibbonGeometry(id, scene, /** * Defines the array of paths to use */ pathArray, /** * Defines if the last and first points of each path in your pathArray must be joined */ closeArray, /** * Defines if the last and first points of each path in your pathArray must be joined */ closePath, /** * Defines the offset between points */ offset, canBeRegenerated, mesh, /** * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ side) { if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; } var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this; _this.pathArray = pathArray; _this.closeArray = closeArray; _this.closePath = closePath; _this.offset = offset; _this.side = side; return _this; } /** @hidden */ RibbonGeometry.prototype._regenerateVertexData = function () { return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side }); }; RibbonGeometry.prototype.copy = function (id) { return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side); }; return RibbonGeometry; }(_PrimitiveGeometry)); BABYLON.RibbonGeometry = RibbonGeometry; /** * Creates a box geometry * @description see http://doc.babylonjs.com/how_to/set_shapes#box */ var BoxGeometry = /** @class */ (function (_super) { __extends(BoxGeometry, _super); /** * Creates a box geometry * @param id defines the unique ID of the geometry * @param scene defines the hosting scene * @param size defines the zise of the box (width, height and depth are the same) * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) * @param mesh defines the hosting mesh (can be null) * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ function BoxGeometry(id, scene, /** * Defines the zise of the box (width, height and depth are the same) */ size, canBeRegenerated, mesh, /** * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ side) { if (mesh === void 0) { mesh = null; } if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; } var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this; _this.size = size; _this.side = side; return _this; } BoxGeometry.prototype._regenerateVertexData = function () { return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side }); }; BoxGeometry.prototype.copy = function (id) { return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side); }; BoxGeometry.prototype.serialize = function () { var serializationObject = _super.prototype.serialize.call(this); serializationObject.size = this.size; return serializationObject; }; BoxGeometry.Parse = function (parsedBox, scene) { if (scene.getGeometryByID(parsedBox.id)) { return null; // null since geometry could be something else than a box... } var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null); if (BABYLON.Tags) { BABYLON.Tags.AddTagsTo(box, parsedBox.tags); } scene.pushGeometry(box, true); return box; }; return BoxGeometry; }(_PrimitiveGeometry)); BABYLON.BoxGeometry = BoxGeometry; /** * Creates a sphere geometry * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere */ var SphereGeometry = /** @class */ (function (_super) { __extends(SphereGeometry, _super); /** * Create a new sphere geometry * @param id defines the unique ID of the geometry * @param scene defines the hosting scene * @param segments defines the number of segments to use to create the sphere * @param diameter defines the diameter of the sphere * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) * @param mesh defines the hosting mesh (can be null) * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ function SphereGeometry(id, scene, /** * Defines the number of segments to use to create the sphere */ segments, /** * Defines the diameter of the sphere */ diameter, canBeRegenerated, mesh, /** * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ side) { if (mesh === void 0) { mesh = null; } if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; } var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this; _this.segments = segments; _this.diameter = diameter; _this.side = side; return _this; } SphereGeometry.prototype._regenerateVertexData = function () { return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side }); }; SphereGeometry.prototype.copy = function (id) { return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side); }; SphereGeometry.prototype.serialize = function () { var serializationObject = _super.prototype.serialize.call(this); serializationObject.segments = this.segments; serializationObject.diameter = this.diameter; return serializationObject; }; SphereGeometry.Parse = function (parsedSphere, scene) { if (scene.getGeometryByID(parsedSphere.id)) { return null; // null since geometry could be something else than a sphere... } var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null); if (BABYLON.Tags) { BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags); } scene.pushGeometry(sphere, true); return sphere; }; return SphereGeometry; }(_PrimitiveGeometry)); BABYLON.SphereGeometry = SphereGeometry; /** * Creates a disc geometry * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon */ var DiscGeometry = /** @class */ (function (_super) { __extends(DiscGeometry, _super); /** * Creates a new disc geometry * @param id defines the unique ID of the geometry * @param scene defines the hosting scene * @param radius defines the radius of the disc * @param tessellation defines the tesselation factor to apply to the disc * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) * @param mesh defines the hosting mesh (can be null) * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ function DiscGeometry(id, scene, /** * Defines the radius of the disc */ radius, /** * Defines the tesselation factor to apply to the disc */ tessellation, canBeRegenerated, mesh, /** * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ side) { if (mesh === void 0) { mesh = null; } if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; } var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this; _this.radius = radius; _this.tessellation = tessellation; _this.side = side; return _this; } DiscGeometry.prototype._regenerateVertexData = function () { return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side }); }; DiscGeometry.prototype.copy = function (id) { return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side); }; return DiscGeometry; }(_PrimitiveGeometry)); BABYLON.DiscGeometry = DiscGeometry; /** * Creates a new cylinder geometry * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone */ var CylinderGeometry = /** @class */ (function (_super) { __extends(CylinderGeometry, _super); /** * Creates a new cylinder geometry * @param id defines the unique ID of the geometry * @param scene defines the hosting scene * @param height defines the height of the cylinder * @param diameterTop defines the diameter of the cylinder's top cap * @param diameterBottom defines the diameter of the cylinder's bottom cap * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides) * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default) * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) * @param mesh defines the hosting mesh (can be null) * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ function CylinderGeometry(id, scene, /** * Defines the height of the cylinder */ height, /** * Defines the diameter of the cylinder's top cap */ diameterTop, /** * Defines the diameter of the cylinder's bottom cap */ diameterBottom, /** * Defines the tessellation factor to apply to the cylinder */ tessellation, /** * Defines the number of subdivisions to apply to the cylinder (1 by default) */ subdivisions, canBeRegenerated, mesh, /** * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ side) { if (subdivisions === void 0) { subdivisions = 1; } if (mesh === void 0) { mesh = null; } if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; } var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this; _this.height = height; _this.diameterTop = diameterTop; _this.diameterBottom = diameterBottom; _this.tessellation = tessellation; _this.subdivisions = subdivisions; _this.side = side; return _this; } CylinderGeometry.prototype._regenerateVertexData = function () { return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side }); }; CylinderGeometry.prototype.copy = function (id) { return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side); }; CylinderGeometry.prototype.serialize = function () { var serializationObject = _super.prototype.serialize.call(this); serializationObject.height = this.height; serializationObject.diameterTop = this.diameterTop; serializationObject.diameterBottom = this.diameterBottom; serializationObject.tessellation = this.tessellation; return serializationObject; }; CylinderGeometry.Parse = function (parsedCylinder, scene) { if (scene.getGeometryByID(parsedCylinder.id)) { return null; // null since geometry could be something else than a cylinder... } var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null); if (BABYLON.Tags) { BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags); } scene.pushGeometry(cylinder, true); return cylinder; }; return CylinderGeometry; }(_PrimitiveGeometry)); BABYLON.CylinderGeometry = CylinderGeometry; /** * Creates a new torus geometry * @description see http://doc.babylonjs.com/how_to/set_shapes#torus */ var TorusGeometry = /** @class */ (function (_super) { __extends(TorusGeometry, _super); /** * Creates a new torus geometry * @param id defines the unique ID of the geometry * @param scene defines the hosting scene * @param diameter defines the diameter of the torus * @param thickness defines the thickness of the torus (ie. internal diameter) * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle) * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) * @param mesh defines the hosting mesh (can be null) * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ function TorusGeometry(id, scene, /** * Defines the diameter of the torus */ diameter, /** * Defines the thickness of the torus (ie. internal diameter) */ thickness, /** * Defines the tesselation factor to apply to the torus */ tessellation, canBeRegenerated, mesh, /** * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ side) { if (mesh === void 0) { mesh = null; } if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; } var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this; _this.diameter = diameter; _this.thickness = thickness; _this.tessellation = tessellation; _this.side = side; return _this; } TorusGeometry.prototype._regenerateVertexData = function () { return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side }); }; TorusGeometry.prototype.copy = function (id) { return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side); }; TorusGeometry.prototype.serialize = function () { var serializationObject = _super.prototype.serialize.call(this); serializationObject.diameter = this.diameter; serializationObject.thickness = this.thickness; serializationObject.tessellation = this.tessellation; return serializationObject; }; TorusGeometry.Parse = function (parsedTorus, scene) { if (scene.getGeometryByID(parsedTorus.id)) { return null; // null since geometry could be something else than a torus... } var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null); if (BABYLON.Tags) { BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags); } scene.pushGeometry(torus, true); return torus; }; return TorusGeometry; }(_PrimitiveGeometry)); BABYLON.TorusGeometry = TorusGeometry; /** * Creates a new ground geometry * @description see http://doc.babylonjs.com/how_to/set_shapes#ground */ var GroundGeometry = /** @class */ (function (_super) { __extends(GroundGeometry, _super); /** * Creates a new ground geometry * @param id defines the unique ID of the geometry * @param scene defines the hosting scene * @param width defines the width of the ground * @param height defines the height of the ground * @param subdivisions defines the subdivisions to apply to the ground * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) * @param mesh defines the hosting mesh (can be null) */ function GroundGeometry(id, scene, /** * Defines the width of the ground */ width, /** * Defines the height of the ground */ height, /** * Defines the subdivisions to apply to the ground */ subdivisions, canBeRegenerated, mesh) { if (mesh === void 0) { mesh = null; } var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this; _this.width = width; _this.height = height; _this.subdivisions = subdivisions; return _this; } GroundGeometry.prototype._regenerateVertexData = function () { return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions }); }; GroundGeometry.prototype.copy = function (id) { return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null); }; GroundGeometry.prototype.serialize = function () { var serializationObject = _super.prototype.serialize.call(this); serializationObject.width = this.width; serializationObject.height = this.height; serializationObject.subdivisions = this.subdivisions; return serializationObject; }; GroundGeometry.Parse = function (parsedGround, scene) { if (scene.getGeometryByID(parsedGround.id)) { return null; // null since geometry could be something else than a ground... } var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null); if (BABYLON.Tags) { BABYLON.Tags.AddTagsTo(ground, parsedGround.tags); } scene.pushGeometry(ground, true); return ground; }; return GroundGeometry; }(_PrimitiveGeometry)); BABYLON.GroundGeometry = GroundGeometry; /** * Creates a tiled ground geometry * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground */ var TiledGroundGeometry = /** @class */ (function (_super) { __extends(TiledGroundGeometry, _super); /** * Creates a tiled ground geometry * @param id defines the unique ID of the geometry * @param scene defines the hosting scene * @param xmin defines the minimum value on X axis * @param zmin defines the minimum value on Z axis * @param xmax defines the maximum value on X axis * @param zmax defines the maximum value on Z axis * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map) * @param precision defines the precision to use when computing the tiles * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) * @param mesh defines the hosting mesh (can be null) */ function TiledGroundGeometry(id, scene, /** * Defines the minimum value on X axis */ xmin, /** * Defines the minimum value on Z axis */ zmin, /** * Defines the maximum value on X axis */ xmax, /** * Defines the maximum value on Z axis */ zmax, /** * Defines the subdivisions to apply to the ground */ subdivisions, /** * Defines the precision to use when computing the tiles */ precision, canBeRegenerated, mesh) { if (mesh === void 0) { mesh = null; } var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this; _this.xmin = xmin; _this.zmin = zmin; _this.xmax = xmax; _this.zmax = zmax; _this.subdivisions = subdivisions; _this.precision = precision; return _this; } TiledGroundGeometry.prototype._regenerateVertexData = function () { return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision }); }; TiledGroundGeometry.prototype.copy = function (id) { return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null); }; return TiledGroundGeometry; }(_PrimitiveGeometry)); BABYLON.TiledGroundGeometry = TiledGroundGeometry; /** * Creates a plane geometry * @description see http://doc.babylonjs.com/how_to/set_shapes#plane */ var PlaneGeometry = /** @class */ (function (_super) { __extends(PlaneGeometry, _super); /** * Creates a plane geometry * @param id defines the unique ID of the geometry * @param scene defines the hosting scene * @param size defines the size of the plane (width === height) * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) * @param mesh defines the hosting mesh (can be null) * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ function PlaneGeometry(id, scene, /** * Defines the size of the plane (width === height) */ size, canBeRegenerated, mesh, /** * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ side) { if (mesh === void 0) { mesh = null; } if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; } var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this; _this.size = size; _this.side = side; return _this; } PlaneGeometry.prototype._regenerateVertexData = function () { return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side }); }; PlaneGeometry.prototype.copy = function (id) { return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side); }; PlaneGeometry.prototype.serialize = function () { var serializationObject = _super.prototype.serialize.call(this); serializationObject.size = this.size; return serializationObject; }; PlaneGeometry.Parse = function (parsedPlane, scene) { if (scene.getGeometryByID(parsedPlane.id)) { return null; // null since geometry could be something else than a ground... } var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null); if (BABYLON.Tags) { BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags); } scene.pushGeometry(plane, true); return plane; }; return PlaneGeometry; }(_PrimitiveGeometry)); BABYLON.PlaneGeometry = PlaneGeometry; /** * Creates a torus knot geometry * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot */ var TorusKnotGeometry = /** @class */ (function (_super) { __extends(TorusKnotGeometry, _super); /** * Creates a torus knot geometry * @param id defines the unique ID of the geometry * @param scene defines the hosting scene * @param radius defines the radius of the torus knot * @param tube defines the thickness of the torus knot tube * @param radialSegments defines the number of radial segments * @param tubularSegments defines the number of tubular segments * @param p defines the first number of windings * @param q defines the second number of windings * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default) * @param mesh defines the hosting mesh (can be null) * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ function TorusKnotGeometry(id, scene, /** * Defines the radius of the torus knot */ radius, /** * Defines the thickness of the torus knot tube */ tube, /** * Defines the number of radial segments */ radialSegments, /** * Defines the number of tubular segments */ tubularSegments, /** * Defines the first number of windings */ p, /** * Defines the second number of windings */ q, canBeRegenerated, mesh, /** * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE) */ side) { if (mesh === void 0) { mesh = null; } if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; } var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this; _this.radius = radius; _this.tube = tube; _this.radialSegments = radialSegments; _this.tubularSegments = tubularSegments; _this.p = p; _this.q = q; _this.side = side; return _this; } TorusKnotGeometry.prototype._regenerateVertexData = function () { return BABYLON.VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side }); }; TorusKnotGeometry.prototype.copy = function (id) { return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side); }; TorusKnotGeometry.prototype.serialize = function () { var serializationObject = _super.prototype.serialize.call(this); serializationObject.radius = this.radius; serializationObject.tube = this.tube; serializationObject.radialSegments = this.radialSegments; serializationObject.tubularSegments = this.tubularSegments; serializationObject.p = this.p; serializationObject.q = this.q; return serializationObject; }; ; TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) { if (scene.getGeometryByID(parsedTorusKnot.id)) { return null; // null since geometry could be something else than a ground... } var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null); if (BABYLON.Tags) { BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags); } scene.pushGeometry(torusKnot, true); return torusKnot; }; return TorusKnotGeometry; }(_PrimitiveGeometry)); BABYLON.TorusKnotGeometry = TorusKnotGeometry; //} })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.geometry.js.map var BABYLON; (function (BABYLON) { /** * PostProcessManager is used to manage one or more post processes or post process pipelines * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses */ var PostProcessManager = /** @class */ (function () { /** * Creates a new instance PostProcess * @param scene The scene that the post process is associated with. */ function PostProcessManager(scene) { this._vertexBuffers = {}; this._scene = scene; } PostProcessManager.prototype._prepareBuffers = function () { if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) { return; } // VBO var vertices = []; vertices.push(1, 1); vertices.push(-1, 1); vertices.push(-1, -1); vertices.push(1, -1); this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2); this._buildIndexBuffer(); }; PostProcessManager.prototype._buildIndexBuffer = 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._scene.getEngine().createIndexBuffer(indices); }; /** * Rebuilds the vertex buffers of the manager. */ PostProcessManager.prototype._rebuild = function () { var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]; if (!vb) { return; } vb._rebuild(); this._buildIndexBuffer(); }; // Methods /** * Prepares a frame to be run through a post process. * @param sourceTexture The input texture to the post procesess. (default: null) * @param postProcesses An array of post processes to be run. (default: null) * @returns True if the post processes were able to be run. */ PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) { if (sourceTexture === void 0) { sourceTexture = null; } if (postProcesses === void 0) { postProcesses = null; } var camera = this._scene.activeCamera; if (!camera) { return false; } var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; }); if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) { return false; } postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined); return true; }; /** * Manually render a set of post processes to a texture. * @param postProcesses An array of post processes to be run. * @param targetTexture The target texture to render to. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight * @param faceIndex defines the face to render to if a cubemap is defined as the target * @param lodLevel defines which lod of the texture to render to */ PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) { if (targetTexture === void 0) { targetTexture = null; } if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; } if (faceIndex === void 0) { faceIndex = 0; } if (lodLevel === void 0) { lodLevel = 0; } var engine = this._scene.getEngine(); for (var index = 0; index < postProcesses.length; index++) { if (index < postProcesses.length - 1) { postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture); } else { if (targetTexture) { engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel); } else { engine.restoreDefaultFramebuffer(); } } var pp = postProcesses[index]; var effect = pp.apply(); if (effect) { pp.onBeforeRenderObservable.notifyObservers(effect); // VBOs this._prepareBuffers(); engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect); // Draw order engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6); pp.onAfterRenderObservable.notifyObservers(effect); } } // Restore depth buffer engine.setDepthBuffer(true); engine.setDepthWrite(true); }; /** * Finalize the result of the output of the postprocesses. * @param doNotPresent If true the result will not be displayed to the screen. * @param targetTexture The target texture to render to. * @param faceIndex The index of the face to bind the target texture to. * @param postProcesses The array of post processes to render. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false) */ PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) { if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; } var camera = this._scene.activeCamera; if (!camera) { return; } postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; }); if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) { return; } var engine = this._scene.getEngine(); for (var index = 0, len = postProcesses.length; index < len; index++) { var pp = postProcesses[index]; if (index < len - 1) { pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture); } else { if (targetTexture) { engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport); pp._outputTexture = targetTexture; } else { engine.restoreDefaultFramebuffer(); pp._outputTexture = null; } } if (doNotPresent) { break; } var effect = pp.apply(); if (effect) { pp.onBeforeRenderObservable.notifyObservers(effect); // VBOs this._prepareBuffers(); engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect); // Draw order engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6); pp.onAfterRenderObservable.notifyObservers(effect); } } // Restore states engine.setDepthBuffer(true); engine.setDepthWrite(true); engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE); }; /** * Disposes of the post process manager. */ PostProcessManager.prototype.dispose = function () { var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]; if (buffer) { buffer.dispose(); this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null; } if (this._indexBuffer) { this._scene.getEngine()._releaseBuffer(this._indexBuffer); this._indexBuffer = null; } }; return PostProcessManager; }()); BABYLON.PostProcessManager = PostProcessManager; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.postProcessManager.js.map var BABYLON; (function (BABYLON) { /** * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window */ var PerformanceMonitor = /** @class */ (function () { /** * constructor * @param frameSampleSize The number of samples required to saturate the sliding window */ function PerformanceMonitor(frameSampleSize) { if (frameSampleSize === void 0) { frameSampleSize = 30; } this._enabled = true; this._rollingFrameTime = new RollingAverage(frameSampleSize); } /** * Samples current frame * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames */ PerformanceMonitor.prototype.sampleFrame = function (timeMs) { if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; } if (!this._enabled) return; if (this._lastFrameTimeMs != null) { var dt = timeMs - this._lastFrameTimeMs; this._rollingFrameTime.add(dt); } this._lastFrameTimeMs = timeMs; }; Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", { /** * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far) * @return Average frame time in milliseconds */ get: function () { return this._rollingFrameTime.average; }, enumerable: true, configurable: true }); Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", { /** * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far) * @return Frame time variance in milliseconds squared */ get: function () { return this._rollingFrameTime.variance; }, enumerable: true, configurable: true }); Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", { /** * Returns the frame time of the most recent frame * @return Frame time in milliseconds */ get: function () { return this._rollingFrameTime.history(0); }, enumerable: true, configurable: true }); Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", { /** * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far) * @return Framerate in frames per second */ get: function () { return 1000.0 / this._rollingFrameTime.average; }, enumerable: true, configurable: true }); Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", { /** * Returns the average framerate in frames per second using the most recent frame time * @return Framerate in frames per second */ get: function () { var history = this._rollingFrameTime.history(0); if (history === 0) { return 0; } return 1000.0 / history; }, enumerable: true, configurable: true }); Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", { /** * Returns true if enough samples have been taken to completely fill the sliding window * @return true if saturated */ get: function () { return this._rollingFrameTime.isSaturated(); }, enumerable: true, configurable: true }); /** * Enables contributions to the sliding window sample set */ PerformanceMonitor.prototype.enable = function () { this._enabled = true; }; /** * Disables contributions to the sliding window sample set * Samples will not be interpolated over the disabled period */ PerformanceMonitor.prototype.disable = function () { this._enabled = false; //clear last sample to avoid interpolating over the disabled period when next enabled this._lastFrameTimeMs = null; }; Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", { /** * Returns true if sampling is enabled * @return true if enabled */ get: function () { return this._enabled; }, enumerable: true, configurable: true }); /** * Resets performance monitor */ PerformanceMonitor.prototype.reset = function () { //clear last sample to avoid interpolating over the disabled period when next enabled this._lastFrameTimeMs = null; //wipe record this._rollingFrameTime.reset(); }; return PerformanceMonitor; }()); BABYLON.PerformanceMonitor = PerformanceMonitor; /** * RollingAverage * * Utility to efficiently compute the rolling average and variance over a sliding window of samples */ var RollingAverage = /** @class */ (function () { /** * constructor * @param length The number of samples required to saturate the sliding window */ function RollingAverage(length) { this._samples = new Array(length); this.reset(); } /** * Adds a sample to the sample set * @param v The sample value */ RollingAverage.prototype.add = function (v) { //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance var delta; //we need to check if we've already wrapped round if (this.isSaturated()) { //remove bottom of stack from mean var bottomValue = this._samples[this._pos]; delta = bottomValue - this.average; this.average -= delta / (this._sampleCount - 1); this._m2 -= delta * (bottomValue - this.average); } else { this._sampleCount++; } //add new value to mean delta = v - this.average; this.average += delta / (this._sampleCount); this._m2 += delta * (v - this.average); //set the new variance this.variance = this._m2 / (this._sampleCount - 1); this._samples[this._pos] = v; this._pos++; this._pos %= this._samples.length; //positive wrap around }; /** * Returns previously added values or null if outside of history or outside the sliding window domain * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that * @return Value previously recorded with add() or null if outside of range */ RollingAverage.prototype.history = function (i) { if ((i >= this._sampleCount) || (i >= this._samples.length)) { return 0; } var i0 = this._wrapPosition(this._pos - 1.0); return this._samples[this._wrapPosition(i0 - i)]; }; /** * Returns true if enough samples have been taken to completely fill the sliding window * @return true if sample-set saturated */ RollingAverage.prototype.isSaturated = function () { return this._sampleCount >= this._samples.length; }; /** * Resets the rolling average (equivalent to 0 samples taken so far) */ RollingAverage.prototype.reset = function () { this.average = 0; this.variance = 0; this._sampleCount = 0; this._pos = 0; this._m2 = 0; }; /** * Wraps a value around the sample range boundaries * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned. * @return Wrapped position in sample range */ RollingAverage.prototype._wrapPosition = function (i) { var max = this._samples.length; return ((i % max) + max) % max; }; return RollingAverage; }()); BABYLON.RollingAverage = RollingAverage; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.performanceMonitor.js.map var BABYLON; (function (BABYLON) { /** * 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 BABYLON.ColorCurves(); this._colorCurvesEnabled = false; this._colorGradingEnabled = false; this._colorGradingWithGreenDepth = true; this._colorGradingBGR = true; this._exposure = 1.0; this._toneMappingEnabled = false; 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 BABYLON.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 BABYLON.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, "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, "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); }; ImageProcessingConfiguration.prototype.getClassName = function () { return "ImageProcessingConfiguration"; }; /** * Prepare the list of uniforms associated with the Image Processing effects. * @param uniformsList 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) { BABYLON.ColorCurves.PrepareUniforms(uniforms); } }; /** * Prepare the list of samplers associated with the Image Processing effects. * @param uniformsList 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 */ 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.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; 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. */ 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 */ ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) { if (aspectRatio === void 0) { aspectRatio = 1; } // Color Curves if (this._colorCurvesEnabled && this.colorCurves) { BABYLON.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 = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch); vignetteScaleY = BABYLON.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 BABYLON.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 BABYLON.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 BABYLON.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 }); // Static constants associated to the image processing. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0; ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1; __decorate([ BABYLON.serializeAsColorCurves() ], ImageProcessingConfiguration.prototype, "colorCurves", void 0); __decorate([ BABYLON.serialize() ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0); __decorate([ BABYLON.serializeAsTexture() ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0); __decorate([ BABYLON.serialize() ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0); __decorate([ BABYLON.serialize() ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0); __decorate([ BABYLON.serialize() ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0); __decorate([ BABYLON.serialize() ], ImageProcessingConfiguration.prototype, "_exposure", void 0); __decorate([ BABYLON.serialize() ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0); __decorate([ BABYLON.serialize() ], ImageProcessingConfiguration.prototype, "_contrast", void 0); __decorate([ BABYLON.serialize() ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0); __decorate([ BABYLON.serialize() ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0); __decorate([ BABYLON.serialize() ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0); __decorate([ BABYLON.serialize() ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0); __decorate([ BABYLON.serializeAsColor4() ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0); __decorate([ BABYLON.serialize() ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0); __decorate([ BABYLON.serialize() ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0); __decorate([ BABYLON.serialize() ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0); __decorate([ BABYLON.serialize() ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0); __decorate([ BABYLON.serialize() ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0); return ImageProcessingConfiguration; }()); BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map var BABYLON; (function (BABYLON) { /** * 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) { __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 = BABYLON.Matrix.Identity(); _this.name = url; _this.url = url; _this.hasAlpha = false; _this.isCube = false; _this.is3D = _this._engine.webGLVersion > 1; _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE; _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE; _this.anisotropicFilteringLevel = 1; _this._texture = _this._getFromCache(url, true); if (!_this._texture) { if (!scene.useDelayedTextureLoading) { _this.loadTexture(); } else { _this.delayLoadState = BABYLON.Engine.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, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE); } else { texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.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; } pixelIndexSlice++; if (pixelIndexSlice % size == 0) { pixelIndexH++; pixelIndexSlice = 0; if (pixelIndexH % size == 0) { pixelIndexW++; pixelIndexH = 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, BABYLON.Engine.TEXTUREFORMAT_RGBA, false); } else { texture.updateSize(size * size, size); engine.updateRawTexture(texture, data, BABYLON.Engine.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 !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) { return; } this.delayLoadState = BABYLON.Engine.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, rootUrl) { 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; }(BABYLON.BaseTexture)); BABYLON.ColorGradingTexture = ColorGradingTexture; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.colorGradingTexture.js.map var BABYLON; (function (BABYLON) { /** * 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 BABYLON.Color4(0, 0, 0, 0); this._globalCurve = new BABYLON.Color4(0, 0, 0, 0); this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0); this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0); this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0); this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0); this._negativeCurve = new BABYLON.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 }); 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 */ 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 BABYLON.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 BABYLON.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 BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null); }; __decorate([ BABYLON.serialize() ], ColorCurves.prototype, "_globalHue", void 0); __decorate([ BABYLON.serialize() ], ColorCurves.prototype, "_globalDensity", void 0); __decorate([ BABYLON.serialize() ], ColorCurves.prototype, "_globalSaturation", void 0); __decorate([ BABYLON.serialize() ], ColorCurves.prototype, "_globalExposure", void 0); __decorate([ BABYLON.serialize() ], ColorCurves.prototype, "_highlightsHue", void 0); __decorate([ BABYLON.serialize() ], ColorCurves.prototype, "_highlightsDensity", void 0); __decorate([ BABYLON.serialize() ], ColorCurves.prototype, "_highlightsSaturation", void 0); __decorate([ BABYLON.serialize() ], ColorCurves.prototype, "_highlightsExposure", void 0); __decorate([ BABYLON.serialize() ], ColorCurves.prototype, "_midtonesHue", void 0); __decorate([ BABYLON.serialize() ], ColorCurves.prototype, "_midtonesDensity", void 0); __decorate([ BABYLON.serialize() ], ColorCurves.prototype, "_midtonesSaturation", void 0); __decorate([ BABYLON.serialize() ], ColorCurves.prototype, "_midtonesExposure", void 0); return ColorCurves; }()); BABYLON.ColorCurves = ColorCurves; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.colorCurves.js.map //# sourceMappingURL=babylon.behavior.js.map var BABYLON; (function (BABYLON) { /** * "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; } effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition); }; /** * Helps preparing the defines values about the UVs in used in the effect. * UVs are shared as much as we can accross chanels in the shaders. * @param texture The texture we are preparing the UVs for * @param defines The defines to update * @param key The chanel key "diffuse", "specular"... used in the shader */ MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) { defines._needUVs = true; defines[key] = true; if (texture.getTextureMatrix().isIdentity(true)) { 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 chanel key "diffuse", "specular"... used in the shader */ MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) { var matrix = texture.getTextureMatrix(); if (!matrix.isIdentity(true)) { 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 !== BABYLON.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; if (useClipPlane == null) { useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null); } if (defines["CLIPPLANE"] !== useClipPlane) { defines["CLIPPLANE"] = useClipPlane; 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(BABYLON.VertexBuffer.NormalKind)); if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) { defines["TANGENT"] = true; } if (defines._needUVs) { defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind); defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind); } else { defines["UV1"] = false; defines["UV2"] = false; } if (useVertexColor) { var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.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; defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1); } 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 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; var type; if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) { type = "SPOTLIGHT" + lightIndex; var spotLight = light; defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false; } else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) { type = "HEMILIGHT" + lightIndex; } else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) { type = "POINTLIGHT" + lightIndex; } else { type = "DIRLIGHT" + lightIndex; } defines[type] = true; // 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) { shadowEnabled = true; shadowGenerator.prepareDefines(defines, lightIndex); } } if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) { lightmapMode = true; defines["LIGHTMAPEXCLUDED" + lightIndex] = true; defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.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" + lightIndex] = false; defines["POINTLIGHT" + lightIndex] = false; defines["DIRLIGHT" + lightIndex] = false; defines["SPOTLIGHT" + lightIndex] = false; defines["SHADOW" + lightIndex] = 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, "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 && BABYLON.Engine.LastCreatedEngine) { var maxAttributesCount = BABYLON.Engine.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(BABYLON.VertexBuffer.PositionKind + index); if (normal) { attribs.push(BABYLON.VertexBuffer.NormalKind + index); } if (tangent) { attribs.push(BABYLON.VertexBuffer.TangentKind + index); } if (attribs.length > maxAttributesCount) { BABYLON.Tools.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(BABYLON.VertexBuffer.MatricesIndicesKind); attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind); if (defines["NUM_BONE_INFLUENCERS"] > 4) { attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind); attribs.push(BABYLON.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, scene, 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, BABYLON.Tmp.Color3[0]); light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString); if (defines["SPECULARTERM"]) { light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]); light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString); } // Shadows if (scene.shadowsEnabled) { this.BindLightShadow(light, scene, 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 */ MaterialHelper.BindFogParameters = function (scene, mesh, effect) { if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) { effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity); 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 matrices = mesh.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); } }; return MaterialHelper; }()); BABYLON.MaterialHelper = MaterialHelper; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.materialHelper.js.map var BABYLON; (function (BABYLON) { var PushMaterial = /** @class */ (function (_super) { __extends(PushMaterial, _super); function PushMaterial(name, scene) { var _this = _super.call(this, name, scene) || this; _this._normalMatrix = new BABYLON.Matrix(); _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; }(BABYLON.Material)); BABYLON.PushMaterial = PushMaterial; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.pushMaterial.js.map var BABYLON; (function (BABYLON) { /** @hidden */ var StandardMaterialDefines = /** @class */ (function (_super) { __extends(StandardMaterialDefines, _super); function StandardMaterialDefines() { var _this = _super.call(this) || this; _this.MAINUV1 = false; _this.MAINUV2 = false; _this.DIFFUSE = false; _this.DIFFUSEDIRECTUV = 0; _this.AMBIENT = false; _this.AMBIENTDIRECTUV = 0; _this.OPACITY = false; _this.OPACITYDIRECTUV = 0; _this.OPACITYRGB = false; _this.REFLECTION = false; _this.EMISSIVE = false; _this.EMISSIVEDIRECTUV = 0; _this.SPECULAR = false; _this.SPECULARDIRECTUV = 0; _this.BUMP = false; _this.BUMPDIRECTUV = 0; _this.PARALLAX = false; _this.PARALLAXOCCLUSION = false; _this.SPECULAROVERALPHA = false; _this.CLIPPLANE = false; _this.ALPHATEST = false; _this.DEPTHPREPASS = false; _this.ALPHAFROMDIFFUSE = false; _this.POINTSIZE = false; _this.FOG = false; _this.SPECULARTERM = false; _this.DIFFUSEFRESNEL = false; _this.OPACITYFRESNEL = false; _this.REFLECTIONFRESNEL = false; _this.REFRACTIONFRESNEL = false; _this.EMISSIVEFRESNEL = false; _this.FRESNEL = false; _this.NORMAL = false; _this.UV1 = false; _this.UV2 = false; _this.VERTEXCOLOR = false; _this.VERTEXALPHA = false; _this.NUM_BONE_INFLUENCERS = 0; _this.BonesPerMesh = 0; _this.INSTANCES = false; _this.GLOSSINESS = false; _this.ROUGHNESS = false; _this.EMISSIVEASILLUMINATION = false; _this.LINKEMISSIVEWITHDIFFUSE = false; _this.REFLECTIONFRESNELFROMSPECULAR = false; _this.LIGHTMAP = false; _this.LIGHTMAPDIRECTUV = 0; _this.OBJECTSPACE_NORMALMAP = false; _this.USELIGHTMAPASSHADOWMAP = false; _this.REFLECTIONMAP_3D = false; _this.REFLECTIONMAP_SPHERICAL = false; _this.REFLECTIONMAP_PLANAR = false; _this.REFLECTIONMAP_CUBIC = false; _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false; _this.REFLECTIONMAP_PROJECTION = false; _this.REFLECTIONMAP_SKYBOX = false; _this.REFLECTIONMAP_EXPLICIT = false; _this.REFLECTIONMAP_EQUIRECTANGULAR = false; _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false; _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false; _this.INVERTCUBICMAP = false; _this.LOGARITHMICDEPTH = false; _this.REFRACTION = false; _this.REFRACTIONMAP_3D = false; _this.REFLECTIONOVERALPHA = false; _this.TWOSIDEDLIGHTING = false; _this.SHADOWFLOAT = false; _this.MORPHTARGETS = false; _this.MORPHTARGETS_NORMAL = false; _this.MORPHTARGETS_TANGENT = false; _this.NUM_MORPH_INFLUENCERS = 0; _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7 _this.IMAGEPROCESSING = false; _this.VIGNETTE = false; _this.VIGNETTEBLENDMODEMULTIPLY = false; _this.VIGNETTEBLENDMODEOPAQUE = false; _this.TONEMAPPING = false; _this.CONTRAST = false; _this.COLORCURVES = false; _this.COLORGRADING = false; _this.COLORGRADING3D = false; _this.SAMPLER3DGREENDEPTH = false; _this.SAMPLER3DBGRMAP = false; _this.IMAGEPROCESSINGPOSTPROCESS = false; /** * If the reflection texture on this material is in linear color space * @hidden */ _this.IS_REFLECTION_LINEAR = false; /** * If the refraction texture on this material is in linear color space * @hidden */ _this.IS_REFRACTION_LINEAR = false; _this.EXPOSURE = false; _this.rebuild(); return _this; } StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) { var modes = [ "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX", "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED", "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED" ]; for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) { var mode = modes_1[_i]; this[mode] = (mode === modeToEnable); } }; return StandardMaterialDefines; }(BABYLON.MaterialDefines)); BABYLON.StandardMaterialDefines = StandardMaterialDefines; var StandardMaterial = /** @class */ (function (_super) { __extends(StandardMaterial, _super); function StandardMaterial(name, scene) { var _this = _super.call(this, name, scene) || this; _this.ambientColor = new BABYLON.Color3(0, 0, 0); _this.diffuseColor = new BABYLON.Color3(1, 1, 1); _this.specularColor = new BABYLON.Color3(1, 1, 1); _this.emissiveColor = new BABYLON.Color3(0, 0, 0); _this.specularPower = 64; _this._useAlphaFromDiffuseTexture = false; _this._useEmissiveAsIllumination = false; _this._linkEmissiveWithDiffuse = false; _this._useSpecularOverAlpha = false; _this._useReflectionOverAlpha = false; _this._disableLighting = false; _this._useObjectSpaceNormalMap = false; _this._useParallax = false; _this._useParallaxOcclusion = false; _this.parallaxScaleBias = 0.05; _this._roughness = 0; _this.indexOfRefraction = 0.98; _this.invertRefractionY = true; /** * Defines the alpha limits in alpha test mode */ _this.alphaCutOff = 0.4; _this._useLightmapAsShadowmap = false; _this._useReflectionFresnelFromSpecular = false; _this._useGlossinessFromSpecularMapAlpha = false; _this._maxSimultaneousLights = 4; /** * 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; _this._renderTargets = new BABYLON.SmartArray(16); _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero(); _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0); // Setup the default processing configuration to the scene. _this._attachImageProcessingConfiguration(null); _this.getRenderTargetTextures = function () { _this._renderTargets.reset(); if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) { _this._renderTargets.push(_this._reflectionTexture); } if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) { _this._renderTargets.push(_this._refractionTexture); } return _this._renderTargets; }; return _this; } Object.defineProperty(StandardMaterial.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 }); /** * Attaches a new image processing configuration to the Standard Material. * @param configuration */ StandardMaterial.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. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) { _this._markAllSubMeshesAsImageProcessingDirty(); }); }; Object.defineProperty(StandardMaterial.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(StandardMaterial.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(StandardMaterial.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(StandardMaterial.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(StandardMaterial.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(StandardMaterial.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(StandardMaterial.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 }); StandardMaterial.prototype.getClassName = function () { return "StandardMaterial"; }; Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", { get: function () { return this._useLogarithmicDepth; }, set: function (value) { this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported; this._markAllSubMeshesAsMiscDirty(); }, enumerable: true, configurable: true }); StandardMaterial.prototype.needAlphaBlending = function () { return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled; }; StandardMaterial.prototype.needAlphaTesting = function () { return this._diffuseTexture != null && this._diffuseTexture.hasAlpha; }; StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () { return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture; }; StandardMaterial.prototype.getAlphaTestTexture = function () { return this._diffuseTexture; }; /** * Child classes can use it to update shaders */ StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) { if (useInstances === void 0) { useInstances = false; } if (subMesh.effect && this.isFrozen) { if (this._wasPreviouslyReady && subMesh.effect) { return true; } } if (!subMesh._materialDefines) { subMesh._materialDefines = new StandardMaterialDefines(); } 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 defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting); // Textures if (defines._areTexturesDirty) { defines._needUVs = false; defines.MAINUV1 = false; defines.MAINUV2 = false; if (scene.texturesEnabled) { if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) { if (!this._diffuseTexture.isReadyOrNotBlocking()) { return false; } else { BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE"); } } else { defines.DIFFUSE = false; } if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) { if (!this._ambientTexture.isReadyOrNotBlocking()) { return false; } else { BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT"); } } else { defines.AMBIENT = false; } if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) { if (!this._opacityTexture.isReadyOrNotBlocking()) { return false; } else { BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY"); defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB; } } else { defines.OPACITY = false; } if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) { if (!this._reflectionTexture.isReadyOrNotBlocking()) { return false; } else { defines._needNormals = true; defines.REFLECTION = true; defines.ROUGHNESS = (this._roughness > 0); defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha; defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE); defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube; switch (this._reflectionTexture.coordinatesMode) { case BABYLON.Texture.EXPLICIT_MODE: defines.setReflectionMode("REFLECTIONMAP_EXPLICIT"); break; case BABYLON.Texture.PLANAR_MODE: defines.setReflectionMode("REFLECTIONMAP_PLANAR"); break; case BABYLON.Texture.PROJECTION_MODE: defines.setReflectionMode("REFLECTIONMAP_PROJECTION"); break; case BABYLON.Texture.SKYBOX_MODE: defines.setReflectionMode("REFLECTIONMAP_SKYBOX"); break; case BABYLON.Texture.SPHERICAL_MODE: defines.setReflectionMode("REFLECTIONMAP_SPHERICAL"); break; case BABYLON.Texture.EQUIRECTANGULAR_MODE: defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR"); break; case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE: defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"); break; case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE: defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"); break; case BABYLON.Texture.CUBIC_MODE: case BABYLON.Texture.INVCUBIC_MODE: default: defines.setReflectionMode("REFLECTIONMAP_CUBIC"); break; } defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false; } } else { defines.REFLECTION = false; } if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) { if (!this._emissiveTexture.isReadyOrNotBlocking()) { return false; } else { BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE"); } } else { defines.EMISSIVE = false; } if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) { if (!this._lightmapTexture.isReadyOrNotBlocking()) { return false; } else { BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP"); defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap; } } else { defines.LIGHTMAP = false; } if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) { if (!this._specularTexture.isReadyOrNotBlocking()) { return false; } else { BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR"); defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha; } } else { defines.SPECULAR = false; } if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) { // Bump texure can not be not blocking. if (!this._bumpTexture.isReady()) { return false; } else { BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP"); defines.PARALLAX = this._useParallax; defines.PARALLAXOCCLUSION = this._useParallaxOcclusion; } defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap; } else { defines.BUMP = false; } if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) { if (!this._refractionTexture.isReadyOrNotBlocking()) { return false; } else { defines._needUVs = true; defines.REFRACTION = true; defines.REFRACTIONMAP_3D = this._refractionTexture.isCube; } } else { defines.REFRACTION = false; } defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting; } else { defines.DIFFUSE = false; defines.AMBIENT = false; defines.OPACITY = false; defines.REFLECTION = false; defines.EMISSIVE = false; defines.LIGHTMAP = false; defines.BUMP = false; defines.REFRACTION = false; } defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture(); defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination; defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse; defines.SPECULAROVERALPHA = this._useSpecularOverAlpha; defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF); } if (defines._areImageProcessingDirty) { if (!this._imageProcessingConfiguration.isReady()) { return false; } this._imageProcessingConfiguration.prepareDefines(defines); defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace); defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace); } if (defines._areFresnelDirty) { if (StandardMaterial.FresnelEnabled) { // Fresnel if (this._diffuseFresnelParameters || this._opacityFresnelParameters || this._emissiveFresnelParameters || this._refractionFresnelParameters || this._reflectionFresnelParameters) { defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled); defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled); defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled); defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular; defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled); defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled); defines._needNormals = true; defines.FRESNEL = true; } } else { defines.FRESNEL = false; } } // Misc. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines); // Attribs BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true); // Values that need to be evaluated on every frame BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances); // Get correct effect if (defines.isDirty) { defines.markAsProcessed(); scene.resetCachedMaterial(); // Fallbacks var fallbacks = new BABYLON.EffectFallbacks(); if (defines.REFLECTION) { fallbacks.addFallback(0, "REFLECTION"); } if (defines.SPECULAR) { fallbacks.addFallback(0, "SPECULAR"); } if (defines.BUMP) { fallbacks.addFallback(0, "BUMP"); } if (defines.PARALLAX) { fallbacks.addFallback(1, "PARALLAX"); } if (defines.PARALLAXOCCLUSION) { fallbacks.addFallback(0, "PARALLAXOCCLUSION"); } if (defines.SPECULAROVERALPHA) { fallbacks.addFallback(0, "SPECULAROVERALPHA"); } if (defines.FOG) { fallbacks.addFallback(1, "FOG"); } if (defines.POINTSIZE) { fallbacks.addFallback(0, "POINTSIZE"); } if (defines.LOGARITHMICDEPTH) { fallbacks.addFallback(0, "LOGARITHMICDEPTH"); } BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights); if (defines.SPECULARTERM) { fallbacks.addFallback(0, "SPECULARTERM"); } if (defines.DIFFUSEFRESNEL) { fallbacks.addFallback(1, "DIFFUSEFRESNEL"); } if (defines.OPACITYFRESNEL) { fallbacks.addFallback(2, "OPACITYFRESNEL"); } if (defines.REFLECTIONFRESNEL) { fallbacks.addFallback(3, "REFLECTIONFRESNEL"); } if (defines.EMISSIVEFRESNEL) { fallbacks.addFallback(4, "EMISSIVEFRESNEL"); } if (defines.FRESNEL) { fallbacks.addFallback(4, "FRESNEL"); } //Attributes var attribs = [BABYLON.VertexBuffer.PositionKind]; if (defines.NORMAL) { attribs.push(BABYLON.VertexBuffer.NormalKind); } if (defines.UV1) { attribs.push(BABYLON.VertexBuffer.UVKind); } if (defines.UV2) { attribs.push(BABYLON.VertexBuffer.UV2Kind); } if (defines.VERTEXCOLOR) { attribs.push(BABYLON.VertexBuffer.ColorKind); } BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks); BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines); BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines); var shaderName = "default"; var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor", "vFogInfos", "vFogColor", "pointSize", "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos", "mBones", "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix", "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor", "vReflectionPosition", "vReflectionSize", "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff" ]; var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"]; var uniformBuffers = ["Material", "Scene"]; BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines); BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines); BABYLON.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(); subMesh.setEffect(scene.getEngine().createEffect(shaderName, { attributes: attribs, uniformsNames: uniforms, uniformBuffersNames: uniformBuffers, samplers: samplers, defines: join, fallbacks: fallbacks, onCompiled: this.onCompiled, onError: this.onError, indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS } }, engine), defines); this.buildUniformLayout(); } if (!subMesh.effect || !subMesh.effect.isReady()) { return false; } defines._renderId = scene.getRenderId(); this._wasPreviouslyReady = true; return true; }; StandardMaterial.prototype.buildUniformLayout = function () { // Order is important ! this._uniformBuffer.addUniform("diffuseLeftColor", 4); this._uniformBuffer.addUniform("diffuseRightColor", 4); this._uniformBuffer.addUniform("opacityParts", 4); this._uniformBuffer.addUniform("reflectionLeftColor", 4); this._uniformBuffer.addUniform("reflectionRightColor", 4); this._uniformBuffer.addUniform("refractionLeftColor", 4); this._uniformBuffer.addUniform("refractionRightColor", 4); this._uniformBuffer.addUniform("emissiveLeftColor", 4); this._uniformBuffer.addUniform("emissiveRightColor", 4); this._uniformBuffer.addUniform("vDiffuseInfos", 2); this._uniformBuffer.addUniform("vAmbientInfos", 2); this._uniformBuffer.addUniform("vOpacityInfos", 2); this._uniformBuffer.addUniform("vReflectionInfos", 2); this._uniformBuffer.addUniform("vReflectionPosition", 3); this._uniformBuffer.addUniform("vReflectionSize", 3); this._uniformBuffer.addUniform("vEmissiveInfos", 2); this._uniformBuffer.addUniform("vLightmapInfos", 2); this._uniformBuffer.addUniform("vSpecularInfos", 2); this._uniformBuffer.addUniform("vBumpInfos", 3); this._uniformBuffer.addUniform("diffuseMatrix", 16); this._uniformBuffer.addUniform("ambientMatrix", 16); this._uniformBuffer.addUniform("opacityMatrix", 16); this._uniformBuffer.addUniform("reflectionMatrix", 16); this._uniformBuffer.addUniform("emissiveMatrix", 16); this._uniformBuffer.addUniform("lightmapMatrix", 16); this._uniformBuffer.addUniform("specularMatrix", 16); this._uniformBuffer.addUniform("bumpMatrix", 16); this._uniformBuffer.addUniform("vTangentSpaceParams", 2); this._uniformBuffer.addUniform("refractionMatrix", 16); this._uniformBuffer.addUniform("vRefractionInfos", 4); this._uniformBuffer.addUniform("vSpecularColor", 4); this._uniformBuffer.addUniform("vEmissiveColor", 3); this._uniformBuffer.addUniform("vDiffuseColor", 4); this._uniformBuffer.addUniform("pointSize", 1); this._uniformBuffer.create(); }; StandardMaterial.prototype.unbind = function () { if (this._activeEffect) { var needFlag = false; if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) { this._activeEffect.setTexture("reflection2DSampler", null); needFlag = true; } if (this._refractionTexture && this._refractionTexture.isRenderTarget) { this._activeEffect.setTexture("refraction2DSampler", null); needFlag = true; } if (needFlag) { this._markAllSubMeshesAsTexturesDirty(); } } _super.prototype.unbind.call(this); }; StandardMaterial.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 BABYLON.MaterialHelper.BindBonesParameters(mesh, effect); if (mustRebind) { this._uniformBuffer.bindToEffect(effect, "Material"); this.bindViewProjection(effect); if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) { if (StandardMaterial.FresnelEnabled && defines.FRESNEL) { // Fresnel if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) { this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power); this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias); } if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) { this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power); } if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) { this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power); this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias); } if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) { this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power); this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias); } if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) { this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power); this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias); } } // Textures if (scene.texturesEnabled) { if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) { this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level); BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse"); if (this._diffuseTexture.hasAlpha) { effect.setFloat("alphaCutOff", this.alphaCutOff); } } if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) { this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level); BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient"); } if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) { this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level); BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity"); } if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) { this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness); this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix()); if (this._reflectionTexture.boundingBoxSize) { var cubeTexture = this._reflectionTexture; this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition); this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize); } } if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) { this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level); BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive"); } if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) { this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level); BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap"); } if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) { this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level); BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular"); } if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) { this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias); BABYLON.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); } } if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) { var depth = 1.0; if (!this._refractionTexture.isCube) { this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix()); if (this._refractionTexture.depth) { depth = this._refractionTexture.depth; } } this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1); } } // Point size if (this.pointsCloud) { this._uniformBuffer.updateFloat("pointSize", this.pointSize); } if (defines.SPECULARTERM) { this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower); } this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor); // Diffuse this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility); } // Textures if (scene.texturesEnabled) { if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) { effect.setTexture("diffuseSampler", this._diffuseTexture); } if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) { effect.setTexture("ambientSampler", this._ambientTexture); } if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) { effect.setTexture("opacitySampler", this._opacityTexture); } if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) { if (this._reflectionTexture.isCube) { effect.setTexture("reflectionCubeSampler", this._reflectionTexture); } else { effect.setTexture("reflection2DSampler", this._reflectionTexture); } } if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) { effect.setTexture("emissiveSampler", this._emissiveTexture); } if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) { effect.setTexture("lightmapSampler", this._lightmapTexture); } if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) { effect.setTexture("specularSampler", this._specularTexture); } if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) { effect.setTexture("bumpSampler", this._bumpTexture); } if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) { var depth = 1.0; if (this._refractionTexture.isCube) { effect.setTexture("refractionCubeSampler", this._refractionTexture); } else { effect.setTexture("refraction2DSampler", this._refractionTexture); } } } // Clip plane BABYLON.MaterialHelper.BindClipPlane(effect, scene); // Colors scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor); BABYLON.MaterialHelper.BindEyePosition(effect, scene); effect.setColor3("vAmbientColor", this._globalAmbientColor); } if (mustRebind || !this.isFrozen) { // Lights if (scene.lightsEnabled && !this._disableLighting) { BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights); } // View if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) { this.bindView(effect); } // Fog BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect); // Morph targets if (defines.NUM_MORPH_INFLUENCERS) { BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect); } // Log. depth BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene); // image processing if (!this._imageProcessingConfiguration.applyByPostProcess) { this._imageProcessingConfiguration.bind(this._activeEffect); } } this._uniformBuffer.update(); this._afterBind(mesh, this._activeEffect); }; StandardMaterial.prototype.getAnimatables = function () { var results = []; if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) { results.push(this._diffuseTexture); } if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) { results.push(this._ambientTexture); } if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) { results.push(this._opacityTexture); } if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) { results.push(this._reflectionTexture); } if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) { results.push(this._emissiveTexture); } if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) { results.push(this._specularTexture); } if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) { results.push(this._bumpTexture); } if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) { results.push(this._lightmapTexture); } if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) { results.push(this._refractionTexture); } return results; }; StandardMaterial.prototype.getActiveTextures = function () { var activeTextures = _super.prototype.getActiveTextures.call(this); if (this._diffuseTexture) { activeTextures.push(this._diffuseTexture); } if (this._ambientTexture) { activeTextures.push(this._ambientTexture); } if (this._opacityTexture) { activeTextures.push(this._opacityTexture); } if (this._reflectionTexture) { activeTextures.push(this._reflectionTexture); } if (this._emissiveTexture) { activeTextures.push(this._emissiveTexture); } if (this._specularTexture) { activeTextures.push(this._specularTexture); } if (this._bumpTexture) { activeTextures.push(this._bumpTexture); } if (this._lightmapTexture) { activeTextures.push(this._lightmapTexture); } if (this._refractionTexture) { activeTextures.push(this._refractionTexture); } return activeTextures; }; StandardMaterial.prototype.hasTexture = function (texture) { if (_super.prototype.hasTexture.call(this, texture)) { return true; } if (this._diffuseTexture === texture) { return true; } if (this._ambientTexture === texture) { return true; } if (this._opacityTexture === texture) { return true; } if (this._reflectionTexture === texture) { return true; } if (this._emissiveTexture === texture) { return true; } if (this._specularTexture === texture) { return true; } if (this._bumpTexture === texture) { return true; } if (this._lightmapTexture === texture) { return true; } if (this._refractionTexture === texture) { return true; } return false; }; StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) { if (forceDisposeTextures) { if (this._diffuseTexture) { this._diffuseTexture.dispose(); } if (this._ambientTexture) { this._ambientTexture.dispose(); } if (this._opacityTexture) { this._opacityTexture.dispose(); } if (this._reflectionTexture) { this._reflectionTexture.dispose(); } if (this._emissiveTexture) { this._emissiveTexture.dispose(); } if (this._specularTexture) { this._specularTexture.dispose(); } if (this._bumpTexture) { this._bumpTexture.dispose(); } if (this._lightmapTexture) { this._lightmapTexture.dispose(); } if (this._refractionTexture) { this._refractionTexture.dispose(); } } if (this._imageProcessingConfiguration && this._imageProcessingObserver) { this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); } _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures); }; StandardMaterial.prototype.clone = function (name) { var _this = this; var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this); result.name = name; result.id = name; return result; }; StandardMaterial.prototype.serialize = function () { return BABYLON.SerializationHelper.Serialize(this); }; // Statics StandardMaterial.Parse = function (source, scene, rootUrl) { return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl); }; Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", { get: function () { return StandardMaterial._DiffuseTextureEnabled; }, set: function (value) { if (StandardMaterial._DiffuseTextureEnabled === value) { return; } StandardMaterial._DiffuseTextureEnabled = value; BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", { get: function () { return StandardMaterial._AmbientTextureEnabled; }, set: function (value) { if (StandardMaterial._AmbientTextureEnabled === value) { return; } StandardMaterial._AmbientTextureEnabled = value; BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", { get: function () { return StandardMaterial._OpacityTextureEnabled; }, set: function (value) { if (StandardMaterial._OpacityTextureEnabled === value) { return; } StandardMaterial._OpacityTextureEnabled = value; BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", { get: function () { return StandardMaterial._ReflectionTextureEnabled; }, set: function (value) { if (StandardMaterial._ReflectionTextureEnabled === value) { return; } StandardMaterial._ReflectionTextureEnabled = value; BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", { get: function () { return StandardMaterial._EmissiveTextureEnabled; }, set: function (value) { if (StandardMaterial._EmissiveTextureEnabled === value) { return; } StandardMaterial._EmissiveTextureEnabled = value; BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", { get: function () { return StandardMaterial._SpecularTextureEnabled; }, set: function (value) { if (StandardMaterial._SpecularTextureEnabled === value) { return; } StandardMaterial._SpecularTextureEnabled = value; BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(StandardMaterial, "BumpTextureEnabled", { get: function () { return StandardMaterial._BumpTextureEnabled; }, set: function (value) { if (StandardMaterial._BumpTextureEnabled === value) { return; } StandardMaterial._BumpTextureEnabled = value; BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", { get: function () { return StandardMaterial._LightmapTextureEnabled; }, set: function (value) { if (StandardMaterial._LightmapTextureEnabled === value) { return; } StandardMaterial._LightmapTextureEnabled = value; BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", { get: function () { return StandardMaterial._RefractionTextureEnabled; }, set: function (value) { if (StandardMaterial._RefractionTextureEnabled === value) { return; } StandardMaterial._RefractionTextureEnabled = value; BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", { get: function () { return StandardMaterial._ColorGradingTextureEnabled; }, set: function (value) { if (StandardMaterial._ColorGradingTextureEnabled === value) { return; } StandardMaterial._ColorGradingTextureEnabled = value; BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag); }, enumerable: true, configurable: true }); Object.defineProperty(StandardMaterial, "FresnelEnabled", { get: function () { return StandardMaterial._FresnelEnabled; }, set: function (value) { if (StandardMaterial._FresnelEnabled === value) { return; } StandardMaterial._FresnelEnabled = value; BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag); }, enumerable: true, configurable: true }); // Flags used to enable or disable a type of texture for all Standard Materials StandardMaterial._DiffuseTextureEnabled = true; StandardMaterial._AmbientTextureEnabled = true; StandardMaterial._OpacityTextureEnabled = true; StandardMaterial._ReflectionTextureEnabled = true; StandardMaterial._EmissiveTextureEnabled = true; StandardMaterial._SpecularTextureEnabled = true; StandardMaterial._BumpTextureEnabled = true; StandardMaterial._LightmapTextureEnabled = true; StandardMaterial._RefractionTextureEnabled = true; StandardMaterial._ColorGradingTextureEnabled = true; StandardMaterial._FresnelEnabled = true; __decorate([ BABYLON.serializeAsTexture("diffuseTexture") ], StandardMaterial.prototype, "_diffuseTexture", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty") ], StandardMaterial.prototype, "diffuseTexture", void 0); __decorate([ BABYLON.serializeAsTexture("ambientTexture") ], StandardMaterial.prototype, "_ambientTexture", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "ambientTexture", void 0); __decorate([ BABYLON.serializeAsTexture("opacityTexture") ], StandardMaterial.prototype, "_opacityTexture", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty") ], StandardMaterial.prototype, "opacityTexture", void 0); __decorate([ BABYLON.serializeAsTexture("reflectionTexture") ], StandardMaterial.prototype, "_reflectionTexture", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "reflectionTexture", void 0); __decorate([ BABYLON.serializeAsTexture("emissiveTexture") ], StandardMaterial.prototype, "_emissiveTexture", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "emissiveTexture", void 0); __decorate([ BABYLON.serializeAsTexture("specularTexture") ], StandardMaterial.prototype, "_specularTexture", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "specularTexture", void 0); __decorate([ BABYLON.serializeAsTexture("bumpTexture") ], StandardMaterial.prototype, "_bumpTexture", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "bumpTexture", void 0); __decorate([ BABYLON.serializeAsTexture("lightmapTexture") ], StandardMaterial.prototype, "_lightmapTexture", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "lightmapTexture", void 0); __decorate([ BABYLON.serializeAsTexture("refractionTexture") ], StandardMaterial.prototype, "_refractionTexture", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "refractionTexture", void 0); __decorate([ BABYLON.serializeAsColor3("ambient") ], StandardMaterial.prototype, "ambientColor", void 0); __decorate([ BABYLON.serializeAsColor3("diffuse") ], StandardMaterial.prototype, "diffuseColor", void 0); __decorate([ BABYLON.serializeAsColor3("specular") ], StandardMaterial.prototype, "specularColor", void 0); __decorate([ BABYLON.serializeAsColor3("emissive") ], StandardMaterial.prototype, "emissiveColor", void 0); __decorate([ BABYLON.serialize() ], StandardMaterial.prototype, "specularPower", void 0); __decorate([ BABYLON.serialize("useAlphaFromDiffuseTexture") ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0); __decorate([ BABYLON.serialize("useEmissiveAsIllumination") ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0); __decorate([ BABYLON.serialize("linkEmissiveWithDiffuse") ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0); __decorate([ BABYLON.serialize("useSpecularOverAlpha") ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0); __decorate([ BABYLON.serialize("useReflectionOverAlpha") ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0); __decorate([ BABYLON.serialize("disableLighting") ], StandardMaterial.prototype, "_disableLighting", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty") ], StandardMaterial.prototype, "disableLighting", void 0); __decorate([ BABYLON.serialize("useObjectSpaceNormalMap") ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0); __decorate([ BABYLON.serialize("useParallax") ], StandardMaterial.prototype, "_useParallax", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "useParallax", void 0); __decorate([ BABYLON.serialize("useParallaxOcclusion") ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "useParallaxOcclusion", void 0); __decorate([ BABYLON.serialize() ], StandardMaterial.prototype, "parallaxScaleBias", void 0); __decorate([ BABYLON.serialize("roughness") ], StandardMaterial.prototype, "_roughness", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "roughness", void 0); __decorate([ BABYLON.serialize() ], StandardMaterial.prototype, "indexOfRefraction", void 0); __decorate([ BABYLON.serialize() ], StandardMaterial.prototype, "invertRefractionY", void 0); __decorate([ BABYLON.serialize() ], StandardMaterial.prototype, "alphaCutOff", void 0); __decorate([ BABYLON.serialize("useLightmapAsShadowmap") ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0); __decorate([ BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters") ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty") ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0); __decorate([ BABYLON.serializeAsFresnelParameters("opacityFresnelParameters") ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty") ], StandardMaterial.prototype, "opacityFresnelParameters", void 0); __decorate([ BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters") ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty") ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0); __decorate([ BABYLON.serializeAsFresnelParameters("refractionFresnelParameters") ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty") ], StandardMaterial.prototype, "refractionFresnelParameters", void 0); __decorate([ BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters") ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty") ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0); __decorate([ BABYLON.serialize("useReflectionFresnelFromSpecular") ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty") ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0); __decorate([ BABYLON.serialize("useGlossinessFromSpecularMapAlpha") ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0); __decorate([ BABYLON.serialize("maxSimultaneousLights") ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty") ], StandardMaterial.prototype, "maxSimultaneousLights", void 0); __decorate([ BABYLON.serialize("invertNormalMapX") ], StandardMaterial.prototype, "_invertNormalMapX", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "invertNormalMapX", void 0); __decorate([ BABYLON.serialize("invertNormalMapY") ], StandardMaterial.prototype, "_invertNormalMapY", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "invertNormalMapY", void 0); __decorate([ BABYLON.serialize("twoSidedLighting") ], StandardMaterial.prototype, "_twoSidedLighting", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "twoSidedLighting", void 0); __decorate([ BABYLON.serialize() ], StandardMaterial.prototype, "useLogarithmicDepth", null); return StandardMaterial; }(BABYLON.PushMaterial)); BABYLON.StandardMaterial = StandardMaterial; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.standardMaterial.js.map var BABYLON; (function (BABYLON) { BABYLON.CameraInputTypes = {}; var CameraInputsManager = /** @class */ (function () { function CameraInputsManager(camera) { this.attached = {}; this.camera = camera; this.checkInputs = function () { }; } /** * Add an input method to a camera. * builtin inputs example: camera.inputs.addGamepad(); * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput()); * @param input camera input method */ CameraInputsManager.prototype.add = function (input) { var type = input.getSimpleName(); if (this.attached[type]) { BABYLON.Tools.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(); } } }; 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(); }; }; CameraInputsManager.prototype.attachInput = function (input) { if (this.attachedElement) { input.attachControl(this.attachedElement, this.noPreventDefault); } }; CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) { if (noPreventDefault === void 0) { noPreventDefault = false; } if (this.attachedElement) { return; } noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault; this.attachedElement = element; this.noPreventDefault = noPreventDefault; for (var cam in this.attached) { this.attached[cam].attachControl(element, noPreventDefault); } }; 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; }; 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 () { }; }; CameraInputsManager.prototype.serialize = function (serializedCamera) { var inputs = {}; for (var cam in this.attached) { var input = this.attached[cam]; var res = BABYLON.SerializationHelper.Serialize(input); inputs[input.getClassName()] = res; } serializedCamera.inputsmgr = inputs; }; CameraInputsManager.prototype.parse = function (parsedCamera) { var parsedInputs = parsedCamera.inputsmgr; if (parsedInputs) { this.clear(); for (var n in parsedInputs) { var construct = BABYLON.CameraInputTypes[n]; if (construct) { var parsedinput = parsedInputs[n]; var input = BABYLON.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 = BABYLON.CameraInputTypes[this.attached[n].getClassName()]; if (construct) { var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null); this.remove(this.attached[n]); this.add(input); } } } }; return CameraInputsManager; }()); BABYLON.CameraInputsManager = CameraInputsManager; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.cameraInputsManager.js.map var BABYLON; (function (BABYLON) { var TargetCamera = /** @class */ (function (_super) { __extends(TargetCamera, _super); function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) { if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; } var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this; _this.cameraDirection = new BABYLON.Vector3(0, 0, 0); _this.cameraRotation = new BABYLON.Vector2(0, 0); _this.rotation = new BABYLON.Vector3(0, 0, 0); _this.speed = 2.0; _this.noRotationConstraint = false; _this.lockedTarget = null; _this._currentTarget = BABYLON.Vector3.Zero(); _this._viewMatrix = BABYLON.Matrix.Zero(); _this._camMatrix = BABYLON.Matrix.Zero(); _this._cameraTransformMatrix = BABYLON.Matrix.Zero(); _this._cameraRotationMatrix = BABYLON.Matrix.Zero(); _this._referencePoint = new BABYLON.Vector3(0, 0, 1); _this._currentUpVector = new BABYLON.Vector3(0, 1, 0); _this._transformedReferencePoint = BABYLON.Vector3.Zero(); _this._globalCurrentTarget = BABYLON.Vector3.Zero(); _this._globalCurrentUpVector = BABYLON.Vector3.Zero(); return _this; } TargetCamera.prototype.getFrontPosition = function (distance) { this.getWorldMatrix(); var direction = this.getTarget().subtract(this.position); direction.normalize(); direction.scaleInPlace(distance); return this.globalPosition.add(direction); }; TargetCamera.prototype._getLockedTargetPosition = function () { if (!this.lockedTarget) { return null; } if (this.lockedTarget.absolutePosition) { this.lockedTarget.computeWorldMatrix(); } return this.lockedTarget.absolutePosition || this.lockedTarget; }; 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 */ 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; }; // Cache TargetCamera.prototype._initCache = function () { _super.prototype._initCache.call(this); this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); }; 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 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 TargetCamera.prototype._computeLocalCameraSpeed = function () { var engine = this.getEngine(); return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0))); }; // Target TargetCamera.prototype.setTarget = function (target) { this.upVector.normalize(); BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, 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) { BABYLON.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. */ TargetCamera.prototype.getTarget = function () { return this._currentTarget; }; TargetCamera.prototype._decideIfNeedsToMove = function () { return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0; }; TargetCamera.prototype._updatePosition = function () { if (this.parent) { this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]); BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]); this.position.addInPlace(BABYLON.Tmp.Vector3[0]); return; } this.position.addInPlace(this.cameraDirection); }; 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) { BABYLON.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 * BABYLON.Epsilon) { this.cameraDirection.x = 0; } if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) { this.cameraDirection.y = 0; } if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) { this.cameraDirection.z = 0; } this.cameraDirection.scaleInPlace(this.inertia); } if (needToRotate) { if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) { this.cameraRotation.x = 0; } if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.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 { BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix); } //update the up vector! BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector); }; TargetCamera.prototype._getViewMatrix = function () { if (this.lockedTarget) { this.setTarget(this._getLockedTargetPosition()); } // Compute this._updateCameraRotationMatrix(); BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint); // Computing target and final matrix this.position.addToRef(this._transformedReferencePoint, this._currentTarget); this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector); return this._viewMatrix; }; TargetCamera.prototype._computeViewMatrix = function (position, target, up) { if (this.parent) { var parentWorldMatrix = this.parent.getWorldMatrix(); BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition); BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget); BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector); this._markSyncedWithParent(); } else { this._globalPosition.copyFrom(this.position); this._globalCurrentTarget.copyFrom(target); this._globalCurrentUpVector.copyFrom(up); } if (this.getScene().useRightHandedSystem) { BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix); } else { BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix); } }; /** * @override * Override Camera.createRigCamera */ TargetCamera.prototype.createRigCamera = function (name, cameraIndex) { if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) { var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene()); if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) { if (!this.rotationQuaternion) { this.rotationQuaternion = new BABYLON.Quaternion(); } rigCamera._cameraRigParams = {}; rigCamera.rotationQuaternion = new BABYLON.Quaternion(); } return rigCamera; } return null; }; /** * @override * Override Camera._updateRigCameras */ TargetCamera.prototype._updateRigCameras = function () { var camLeft = this._rigCameras[0]; var camRight = this._rigCameras[1]; switch (this.cameraRigMode) { case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH: case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL: case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED: case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER: //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance: var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1; var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1; this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position); this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position); camLeft.setTarget(this.getTarget()); camRight.setTarget(this.getTarget()); break; case BABYLON.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._getRigCamPosition = function (halfSpace, result) { if (!this._rigCamTransformMatrix) { this._rigCamTransformMatrix = new BABYLON.Matrix(); } var target = this.getTarget(); BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix); this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z)); BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result); }; TargetCamera.prototype.getClassName = function () { return "TargetCamera"; }; __decorate([ BABYLON.serializeAsVector3() ], TargetCamera.prototype, "rotation", void 0); __decorate([ BABYLON.serialize() ], TargetCamera.prototype, "speed", void 0); __decorate([ BABYLON.serializeAsMeshReference("lockedTargetId") ], TargetCamera.prototype, "lockedTarget", void 0); return TargetCamera; }(BABYLON.Camera)); BABYLON.TargetCamera = TargetCamera; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.targetCamera.js.map var BABYLON; (function (BABYLON) { var FreeCameraMouseInput = /** @class */ (function () { function FreeCameraMouseInput(touchEnabled) { if (touchEnabled === void 0) { touchEnabled = true; } this.touchEnabled = touchEnabled; this.buttons = [0, 1, 2]; this.angularSensibility = 2000.0; this.previousPosition = null; } FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; var engine = this.camera.getEngine(); if (!this._pointerInput) { this._pointerInput = function (p, s) { var evt = p.event; if (engine.isInVRExclusivePointerMode) { return; } if (!_this.touchEnabled && evt.pointerType === "touch") { return; } if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) { return; } var srcElement = (evt.srcElement || evt.target); if (p.type === BABYLON.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 === BABYLON.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 === BABYLON.PointerEventTypes.POINTERMOVE) { if (!_this.previousPosition || engine.isPointerLock) { return; } var offsetX = evt.clientX - _this.previousPosition.x; 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.clientY - _this.previousPosition.y; _this.camera.cameraRotation.x += offsetY / _this.angularSensibility; _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, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE); element.addEventListener("mousemove", this._onMouseMove, false); }; FreeCameraMouseInput.prototype.detachControl = function (element) { if (this._observer && element) { this.camera.getScene().onPointerObservable.remove(this._observer); if (this._onMouseMove) { element.removeEventListener("mousemove", this._onMouseMove); } this._observer = null; this._onMouseMove = null; this.previousPosition = null; } }; FreeCameraMouseInput.prototype.getClassName = function () { return "FreeCameraMouseInput"; }; FreeCameraMouseInput.prototype.getSimpleName = function () { return "mouse"; }; __decorate([ BABYLON.serialize() ], FreeCameraMouseInput.prototype, "buttons", void 0); __decorate([ BABYLON.serialize() ], FreeCameraMouseInput.prototype, "angularSensibility", void 0); return FreeCameraMouseInput; }()); BABYLON.FreeCameraMouseInput = FreeCameraMouseInput; BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.freeCameraMouseInput.js.map var BABYLON; (function (BABYLON) { var FreeCameraKeyboardMoveInput = /** @class */ (function () { function FreeCameraKeyboardMoveInput() { this._keys = new Array(); this.keysUp = [38]; this.keysDown = [40]; this.keysLeft = [37]; this.keysRight = [39]; } 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 (info.type === BABYLON.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(); } } } }); }; 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 = []; }; 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); BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection); camera.cameraDirection.addInPlace(camera._transformedDirection); } } }; FreeCameraKeyboardMoveInput.prototype.getClassName = function () { return "FreeCameraKeyboardMoveInput"; }; FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) { this._keys = []; }; FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () { return "keyboard"; }; __decorate([ BABYLON.serialize() ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0); __decorate([ BABYLON.serialize() ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0); __decorate([ BABYLON.serialize() ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0); __decorate([ BABYLON.serialize() ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0); return FreeCameraKeyboardMoveInput; }()); BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput; BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map var BABYLON; (function (BABYLON) { var FreeCameraInputsManager = /** @class */ (function (_super) { __extends(FreeCameraInputsManager, _super); function FreeCameraInputsManager(camera) { return _super.call(this, camera) || this; } FreeCameraInputsManager.prototype.addKeyboard = function () { this.add(new BABYLON.FreeCameraKeyboardMoveInput()); return this; }; FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) { if (touchEnabled === void 0) { touchEnabled = true; } this.add(new BABYLON.FreeCameraMouseInput(touchEnabled)); return this; }; FreeCameraInputsManager.prototype.addGamepad = function () { this.add(new BABYLON.FreeCameraGamepadInput()); return this; }; FreeCameraInputsManager.prototype.addDeviceOrientation = function () { this.add(new BABYLON.FreeCameraDeviceOrientationInput()); return this; }; FreeCameraInputsManager.prototype.addTouch = function () { this.add(new BABYLON.FreeCameraTouchInput()); return this; }; FreeCameraInputsManager.prototype.addVirtualJoystick = function () { this.add(new BABYLON.FreeCameraVirtualJoystickInput()); return this; }; return FreeCameraInputsManager; }(BABYLON.CameraInputsManager)); BABYLON.FreeCameraInputsManager = FreeCameraInputsManager; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.freeCameraInputsManager.js.map var BABYLON; (function (BABYLON) { var FreeCamera = /** @class */ (function (_super) { __extends(FreeCamera, _super); function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) { if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; } var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this; _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5); _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0); _this.checkCollisions = false; _this.applyGravity = false; _this._needMoveForGravity = false; _this._oldPosition = BABYLON.Vector3.Zero(); _this._diffPosition = BABYLON.Vector3.Zero(); _this._newPosition = BABYLON.Vector3.Zero(); // Collisions _this._collisionMask = -1; _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) { if (collidedMesh === void 0) { collidedMesh = null; } //TODO move this to the collision coordinator! if (_this.getScene().workerCollisions) newPosition.multiplyInPlace(_this._collider._radius); var updatePosition = function (newPos) { _this._newPosition.copyFrom(newPos); _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition); if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) { _this.position.addInPlace(_this._diffPosition); if (_this.onCollide && collidedMesh) { _this.onCollide(collidedMesh); } } }; updatePosition(newPosition); }; _this.inputs = new BABYLON.FreeCameraInputsManager(_this); _this.inputs.addKeyboard().addMouse(); return _this; } Object.defineProperty(FreeCamera.prototype, "angularSensibility", { //-- begin properties for backward compatibility for inputs /** * 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", { 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", { 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", { 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", { 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 }); // Controls FreeCamera.prototype.attachControl = function (element, noPreventDefault) { this.inputs.attachElement(element, noPreventDefault); }; FreeCamera.prototype.detachControl = function (element) { this.inputs.detachElement(element); this.cameraDirection = new BABYLON.Vector3(0, 0, 0); this.cameraRotation = new BABYLON.Vector2(0, 0); }; Object.defineProperty(FreeCamera.prototype, "collisionMask", { get: function () { return this._collisionMask; }, set: function (mask) { this._collisionMask = !isNaN(mask) ? mask : -1; }, enumerable: true, configurable: true }); FreeCamera.prototype._collideWithWorld = function (displacement) { var globalPosition; if (this.parent) { globalPosition = BABYLON.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); if (!this._collider) { this._collider = new BABYLON.Collider(); } 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); } this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId); }; FreeCamera.prototype._checkInputs = function () { if (!this._localDirection) { this._localDirection = BABYLON.Vector3.Zero(); this._transformedDirection = BABYLON.Vector3.Zero(); } this.inputs.checkInputs(); _super.prototype._checkInputs.call(this); }; 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; }; FreeCamera.prototype._updatePosition = function () { if (this.checkCollisions && this.getScene().collisionsEnabled) { this._collideWithWorld(this.cameraDirection); } else { _super.prototype._updatePosition.call(this); } }; FreeCamera.prototype.dispose = function () { this.inputs.clear(); _super.prototype.dispose.call(this); }; FreeCamera.prototype.getClassName = function () { return "FreeCamera"; }; __decorate([ BABYLON.serializeAsVector3() ], FreeCamera.prototype, "ellipsoid", void 0); __decorate([ BABYLON.serializeAsVector3() ], FreeCamera.prototype, "ellipsoidOffset", void 0); __decorate([ BABYLON.serialize() ], FreeCamera.prototype, "checkCollisions", void 0); __decorate([ BABYLON.serialize() ], FreeCamera.prototype, "applyGravity", void 0); return FreeCamera; }(BABYLON.TargetCamera)); BABYLON.FreeCamera = FreeCamera; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.freeCamera.js.map var BABYLON; (function (BABYLON) { /** * 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) { __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 : http://doc.babylonjs.com/tutorials/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 BABYLON.Color3(0.0, 0.0, 0.0); _this.direction = direction || BABYLON.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 = BABYLON.Vector3.Normalize(target.subtract(BABYLON.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 = BABYLON.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; }; /** * @hidden internal use only. */ HemisphericLight.prototype._getWorldMatrix = function () { if (!this._worldMatrix) { this._worldMatrix = BABYLON.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 BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT; }; __decorate([ BABYLON.serializeAsColor3() ], HemisphericLight.prototype, "groundColor", void 0); __decorate([ BABYLON.serializeAsVector3() ], HemisphericLight.prototype, "direction", void 0); return HemisphericLight; }(BABYLON.Light)); BABYLON.HemisphericLight = HemisphericLight; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.hemisphericLight.js.map var BABYLON; (function (BABYLON) { var ShaderMaterial = /** @class */ (function (_super) { __extends(ShaderMaterial, _super); function ShaderMaterial(name, scene, shaderPath, options) { var _this = _super.call(this, name, scene) || this; _this._textures = {}; _this._textureArrays = {}; _this._floats = {}; _this._ints = {}; _this._floatsArrays = {}; _this._colors3 = {}; _this._colors3Arrays = {}; _this._colors4 = {}; _this._vectors2 = {}; _this._vectors3 = {}; _this._vectors4 = {}; _this._matrices = {}; _this._matrices3x3 = {}; _this._matrices2x2 = {}; _this._vectors2Arrays = {}; _this._vectors3Arrays = {}; _this._cachedWorldViewMatrix = new BABYLON.Matrix(); _this._shaderPath = shaderPath; options.needAlphaBlending = options.needAlphaBlending || false; options.needAlphaTesting = options.needAlphaTesting || false; options.attributes = options.attributes || ["position", "normal", "uv"]; options.uniforms = options.uniforms || ["worldViewProjection"]; options.uniformBuffers = options.uniformBuffers || []; options.samplers = options.samplers || []; options.defines = options.defines || []; _this._options = options; return _this; } ShaderMaterial.prototype.getClassName = function () { return "ShaderMaterial"; }; ShaderMaterial.prototype.needAlphaBlending = function () { return this._options.needAlphaBlending; }; ShaderMaterial.prototype.needAlphaTesting = function () { return this._options.needAlphaTesting; }; ShaderMaterial.prototype._checkUniform = function (uniformName) { if (this._options.uniforms.indexOf(uniformName) === -1) { this._options.uniforms.push(uniformName); } }; ShaderMaterial.prototype.setTexture = function (name, texture) { if (this._options.samplers.indexOf(name) === -1) { this._options.samplers.push(name); } this._textures[name] = texture; return this; }; ShaderMaterial.prototype.setTextureArray = function (name, textures) { if (this._options.samplers.indexOf(name) === -1) { this._options.samplers.push(name); } this._checkUniform(name); this._textureArrays[name] = textures; return this; }; ShaderMaterial.prototype.setFloat = function (name, value) { this._checkUniform(name); this._floats[name] = value; return this; }; ShaderMaterial.prototype.setInt = function (name, value) { this._checkUniform(name); this._ints[name] = value; return this; }; ShaderMaterial.prototype.setFloats = function (name, value) { this._checkUniform(name); this._floatsArrays[name] = value; return this; }; ShaderMaterial.prototype.setColor3 = function (name, value) { this._checkUniform(name); this._colors3[name] = value; return this; }; ShaderMaterial.prototype.setColor3Array = function (name, value) { this._checkUniform(name); this._colors3Arrays[name] = value.reduce(function (arr, color) { color.toArray(arr, arr.length); return arr; }, []); return this; }; ShaderMaterial.prototype.setColor4 = function (name, value) { this._checkUniform(name); this._colors4[name] = value; return this; }; ShaderMaterial.prototype.setVector2 = function (name, value) { this._checkUniform(name); this._vectors2[name] = value; return this; }; ShaderMaterial.prototype.setVector3 = function (name, value) { this._checkUniform(name); this._vectors3[name] = value; return this; }; ShaderMaterial.prototype.setVector4 = function (name, value) { this._checkUniform(name); this._vectors4[name] = value; return this; }; ShaderMaterial.prototype.setMatrix = function (name, value) { this._checkUniform(name); this._matrices[name] = value; return this; }; ShaderMaterial.prototype.setMatrix3x3 = function (name, value) { this._checkUniform(name); this._matrices3x3[name] = value; return this; }; ShaderMaterial.prototype.setMatrix2x2 = function (name, value) { this._checkUniform(name); this._matrices2x2[name] = value; return this; }; ShaderMaterial.prototype.setArray2 = function (name, value) { this._checkUniform(name); this._vectors2Arrays[name] = value; return this; }; ShaderMaterial.prototype.setArray3 = function (name, value) { this._checkUniform(name); this._vectors3Arrays[name] = value; return this; }; ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) { if (!mesh) { return true; } if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) { return false; } return false; }; ShaderMaterial.prototype.isReady = function (mesh, useInstances) { var scene = this.getScene(); var engine = scene.getEngine(); if (!this.checkReadyOnEveryCall) { if (this._renderId === scene.getRenderId()) { if (this._checkCache(scene, mesh, useInstances)) { return true; } } } // Instances var defines = []; var attribs = []; var fallbacks = new BABYLON.EffectFallbacks(); if (useInstances) { defines.push("#define INSTANCES"); } for (var index = 0; index < this._options.defines.length; index++) { defines.push(this._options.defines[index]); } for (var index = 0; index < this._options.attributes.length; index++) { attribs.push(this._options.attributes[index]); } if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) { attribs.push(BABYLON.VertexBuffer.ColorKind); defines.push("#define VERTEXCOLOR"); } // Bones if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind); attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind); if (mesh.numBoneInfluencers > 4) { attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind); attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind); } defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1)); fallbacks.addCPUSkinningFallback(0, mesh); if (this._options.uniforms.indexOf("mBones") === -1) { this._options.uniforms.push("mBones"); } } else { defines.push("#define NUM_BONE_INFLUENCERS 0"); } // Textures for (var name in this._textures) { if (!this._textures[name].isReady()) { return false; } } // Alpha test if (mesh && this._shouldTurnAlphaTestOn(mesh)) { defines.push("#define ALPHATEST"); } var previousEffect = this._effect; var join = defines.join("\n"); this._effect = engine.createEffect(this._shaderPath, { attributes: attribs, uniformsNames: this._options.uniforms, uniformBuffersNames: this._options.uniformBuffers, samplers: this._options.samplers, defines: join, fallbacks: fallbacks, onCompiled: this.onCompiled, onError: this.onError }, engine); if (!this._effect.isReady()) { return false; } if (previousEffect !== this._effect) { scene.resetCachedMaterial(); } this._renderId = scene.getRenderId(); return true; }; ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) { var scene = this.getScene(); if (!this._effect) { return; } if (this._options.uniforms.indexOf("world") !== -1) { this._effect.setMatrix("world", world); } if (this._options.uniforms.indexOf("worldView") !== -1) { world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix); this._effect.setMatrix("worldView", this._cachedWorldViewMatrix); } if (this._options.uniforms.indexOf("worldViewProjection") !== -1) { this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix())); } }; ShaderMaterial.prototype.bind = function (world, mesh) { // Std values this.bindOnlyWorldMatrix(world); if (this._effect && this.getScene().getCachedMaterial() !== this) { if (this._options.uniforms.indexOf("view") !== -1) { this._effect.setMatrix("view", this.getScene().getViewMatrix()); } if (this._options.uniforms.indexOf("projection") !== -1) { this._effect.setMatrix("projection", this.getScene().getProjectionMatrix()); } if (this._options.uniforms.indexOf("viewProjection") !== -1) { this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix()); } // Bones BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect); var name; // Texture for (name in this._textures) { this._effect.setTexture(name, this._textures[name]); } // Texture arrays for (name in this._textureArrays) { this._effect.setTextureArray(name, this._textureArrays[name]); } // Int 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]); } for (name in this._colors3Arrays) { this._effect.setArray3(name, this._colors3Arrays[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]); } // Vector4 for (name in this._vectors4) { this._effect.setVector4(name, this._vectors4[name]); } // Matrix for (name in this._matrices) { this._effect.setMatrix(name, this._matrices[name]); } // Matrix 3x3 for (name in this._matrices3x3) { this._effect.setMatrix3x3(name, this._matrices3x3[name]); } // Matrix 2x2 for (name in this._matrices2x2) { this._effect.setMatrix2x2(name, this._matrices2x2[name]); } // Vector2Array for (name in this._vectors2Arrays) { this._effect.setArray2(name, this._vectors2Arrays[name]); } // Vector3Array for (name in this._vectors3Arrays) { this._effect.setArray3(name, this._vectors3Arrays[name]); } } this._afterBind(mesh); }; ShaderMaterial.prototype.getActiveTextures = function () { var activeTextures = _super.prototype.getActiveTextures.call(this); for (var name in this._textures) { activeTextures.push(this._textures[name]); } for (var name in this._textureArrays) { var array = this._textureArrays[name]; for (var index = 0; index < array.length; index++) { activeTextures.push(array[index]); } } return activeTextures; }; ShaderMaterial.prototype.hasTexture = function (texture) { if (_super.prototype.hasTexture.call(this, texture)) { return true; } for (var name in this._textures) { if (this._textures[name] === texture) { return true; } } for (var name in this._textureArrays) { var array = this._textureArrays[name]; for (var index = 0; index < array.length; index++) { if (array[index] === texture) { return true; } } } return false; }; ShaderMaterial.prototype.clone = function (name) { var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options); return newShaderMaterial; }; ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) { if (forceDisposeTextures) { var name; for (name in this._textures) { this._textures[name].dispose(); } for (name in this._textureArrays) { var array = this._textureArrays[name]; for (var index = 0; index < array.length; index++) { array[index].dispose(); } } } this._textures = {}; _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures); }; ShaderMaterial.prototype.serialize = function () { var serializationObject = BABYLON.SerializationHelper.Serialize(this); serializationObject.customType = "BABYLON.ShaderMaterial"; serializationObject.options = this._options; serializationObject.shaderPath = this._shaderPath; var name; // Texture serializationObject.textures = {}; for (name in this._textures) { serializationObject.textures[name] = this._textures[name].serialize(); } // Texture arrays serializationObject.textureArrays = {}; for (name in this._textureArrays) { serializationObject.textureArrays[name] = []; var array = this._textureArrays[name]; for (var index = 0; index < array.length; index++) { serializationObject.textureArrays[name].push(array[index].serialize()); } } // Float serializationObject.floats = {}; for (name in this._floats) { serializationObject.floats[name] = this._floats[name]; } // Float s serializationObject.FloatArrays = {}; for (name in this._floatsArrays) { serializationObject.FloatArrays[name] = this._floatsArrays[name]; } // Color3 serializationObject.colors3 = {}; for (name in this._colors3) { serializationObject.colors3[name] = this._colors3[name].asArray(); } // Color3 array serializationObject.colors3Arrays = {}; for (name in this._colors3Arrays) { serializationObject.colors3Arrays[name] = this._colors3Arrays[name]; } // Color4 serializationObject.colors4 = {}; for (name in this._colors4) { serializationObject.colors4[name] = this._colors4[name].asArray(); } // Vector2 serializationObject.vectors2 = {}; for (name in this._vectors2) { serializationObject.vectors2[name] = this._vectors2[name].asArray(); } // Vector3 serializationObject.vectors3 = {}; for (name in this._vectors3) { serializationObject.vectors3[name] = this._vectors3[name].asArray(); } // Vector4 serializationObject.vectors4 = {}; for (name in this._vectors4) { serializationObject.vectors4[name] = this._vectors4[name].asArray(); } // Matrix serializationObject.matrices = {}; for (name in this._matrices) { serializationObject.matrices[name] = this._matrices[name].asArray(); } // Matrix 3x3 serializationObject.matrices3x3 = {}; for (name in this._matrices3x3) { serializationObject.matrices3x3[name] = this._matrices3x3[name]; } // Matrix 2x2 serializationObject.matrices2x2 = {}; for (name in this._matrices2x2) { serializationObject.matrices2x2[name] = this._matrices2x2[name]; } // Vector2Array serializationObject.vectors2Arrays = {}; for (name in this._vectors2Arrays) { serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name]; } // Vector3Array serializationObject.vectors3Arrays = {}; for (name in this._vectors3Arrays) { serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name]; } return serializationObject; }; ShaderMaterial.Parse = function (source, scene, rootUrl) { var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl); var name; // Texture for (name in source.textures) { material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl)); } // Texture arrays for (name in source.textureArrays) { var array = source.textureArrays[name]; var textureArray = new Array(); for (var index = 0; index < array.length; index++) { textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl)); } material.setTextureArray(name, textureArray); } // Float for (name in source.floats) { material.setFloat(name, source.floats[name]); } // Float s for (name in source.floatsArrays) { material.setFloats(name, source.floatsArrays[name]); } // Color3 for (name in source.colors3) { material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name])); } // Color3 arrays for (name in source.colors3Arrays) { var colors = source.colors3Arrays[name].reduce(function (arr, num, i) { if (i % 3 === 0) { arr.push([num]); } else { arr[arr.length - 1].push(num); } return arr; }, []).map(function (color) { return BABYLON.Color3.FromArray(color); }); material.setColor3Array(name, colors); } // Color4 for (name in source.colors4) { material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name])); } // Vector2 for (name in source.vectors2) { material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name])); } // Vector3 for (name in source.vectors3) { material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name])); } // Vector4 for (name in source.vectors4) { material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name])); } // Matrix for (name in source.matrices) { material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name])); } // Matrix 3x3 for (name in source.matrices3x3) { material.setMatrix3x3(name, source.matrices3x3[name]); } // Matrix 2x2 for (name in source.matrices2x2) { material.setMatrix2x2(name, source.matrices2x2[name]); } // Vector2Array for (name in source.vectors2Arrays) { material.setArray2(name, source.vectors2Arrays[name]); } // Vector3Array for (name in source.vectors3Arrays) { material.setArray3(name, source.vectors3Arrays[name]); } return material; }; return ShaderMaterial; }(BABYLON.Material)); BABYLON.ShaderMaterial = ShaderMaterial; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.shaderMaterial.js.map var BABYLON; (function (BABYLON) { var GroundMesh = /** @class */ (function (_super) { __extends(GroundMesh, _super); function GroundMesh(name, scene) { var _this = _super.call(this, name, scene) || this; _this.generateOctree = false; return _this; } GroundMesh.prototype.getClassName = function () { return "GroundMesh"; }; Object.defineProperty(GroundMesh.prototype, "subdivisions", { get: function () { return Math.min(this._subdivisionsX, this._subdivisionsY); }, enumerable: true, configurable: true }); Object.defineProperty(GroundMesh.prototype, "subdivisionsX", { get: function () { return this._subdivisionsX; }, enumerable: true, configurable: true }); Object.defineProperty(GroundMesh.prototype, "subdivisionsY", { get: function () { return this._subdivisionsY; }, enumerable: true, configurable: true }); GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) { if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; } this._subdivisionsX = chunksCount; this._subdivisionsY = chunksCount; this.subdivide(chunksCount); this.createOrUpdateSubmeshesOctree(octreeBlocksSize); }; /** * Returns a height (y) value in the Worl system : * the ground altitude at the coordinates (x, z) expressed in the World system. * Returns the ground y position if (x, z) are outside the ground surface. */ GroundMesh.prototype.getHeightAtCoordinates = function (x, z) { var world = this.getWorldMatrix(); var invMat = BABYLON.Tmp.Matrix[5]; world.invertToRef(invMat); var tmpVect = BABYLON.Tmp.Vector3[8]; BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space x = tmpVect.x; z = tmpVect.z; if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) { return this.position.y; } if (!this._heightQuads || this._heightQuads.length == 0) { this._initHeightQuads(); this._computeHeightQuads(); } var facet = this._getFacetAt(x, z); var y = -(facet.x * x + facet.z * z + facet.w) / facet.y; // return y in the World system BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect); return tmpVect.y; }; /** * Returns a normalized vector (Vector3) orthogonal to the ground * at the ground coordinates (x, z) expressed in the World system. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface. */ GroundMesh.prototype.getNormalAtCoordinates = function (x, z) { var normal = new BABYLON.Vector3(0.0, 1.0, 0.0); this.getNormalAtCoordinatesToRef(x, z, normal); return normal; }; /** * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground * at the ground coordinates (x, z) expressed in the World system. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface. * Returns the GroundMesh. */ GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) { var world = this.getWorldMatrix(); var tmpMat = BABYLON.Tmp.Matrix[5]; world.invertToRef(tmpMat); var tmpVect = BABYLON.Tmp.Vector3[8]; BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space x = tmpVect.x; z = tmpVect.z; if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) { return this; } if (!this._heightQuads || this._heightQuads.length == 0) { this._initHeightQuads(); this._computeHeightQuads(); } var facet = this._getFacetAt(x, z); BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref); return this; }; /** * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates() * if the ground has been updated. * This can be used in the render loop. * Returns the GroundMesh. */ GroundMesh.prototype.updateCoordinateHeights = function () { if (!this._heightQuads || this._heightQuads.length == 0) { this._initHeightQuads(); } this._computeHeightQuads(); return this; }; // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates GroundMesh.prototype._getFacetAt = function (x, z) { // retrieve col and row from x, z coordinates in the ground local system var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width); var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY); var quad = this._heightQuads[row * this._subdivisionsX + col]; var facet; if (z < quad.slope.x * x + quad.slope.y) { facet = quad.facet1; } else { facet = quad.facet2; } return facet; }; // Creates and populates the heightMap array with "facet" elements : // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0 // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0 // Returns the GroundMesh. GroundMesh.prototype._initHeightQuads = function () { var subdivisionsX = this._subdivisionsX; var subdivisionsY = this._subdivisionsY; this._heightQuads = new Array(); for (var row = 0; row < subdivisionsY; row++) { for (var col = 0; col < subdivisionsX; col++) { var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0), facet2: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0) }; this._heightQuads[row * subdivisionsX + col] = quad; } } return this; }; // Compute each quad element values and update the the heightMap array : // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0 // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0 // Returns the GroundMesh. GroundMesh.prototype._computeHeightQuads = function () { var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind); if (!positions) { return this; } var v1 = BABYLON.Tmp.Vector3[3]; var v2 = BABYLON.Tmp.Vector3[2]; var v3 = BABYLON.Tmp.Vector3[1]; var v4 = BABYLON.Tmp.Vector3[0]; var v1v2 = BABYLON.Tmp.Vector3[4]; var v1v3 = BABYLON.Tmp.Vector3[5]; var v1v4 = BABYLON.Tmp.Vector3[6]; var norm1 = BABYLON.Tmp.Vector3[7]; var norm2 = BABYLON.Tmp.Vector3[8]; var i = 0; var j = 0; var k = 0; var cd = 0; // 2D slope coefficient : z = cd * x + h var h = 0; var d1 = 0; // facet plane equation : ax + by + cz + d = 0 var d2 = 0; var subdivisionsX = this._subdivisionsX; var subdivisionsY = this._subdivisionsY; for (var row = 0; row < subdivisionsY; row++) { for (var col = 0; col < subdivisionsX; col++) { i = col * 3; j = row * (subdivisionsX + 1) * 3; k = (row + 1) * (subdivisionsX + 1) * 3; v1.x = positions[j + i]; v1.y = positions[j + i + 1]; v1.z = positions[j + i + 2]; v2.x = positions[j + i + 3]; v2.y = positions[j + i + 4]; v2.z = positions[j + i + 5]; v3.x = positions[k + i]; v3.y = positions[k + i + 1]; v3.z = positions[k + i + 2]; v4.x = positions[k + i + 3]; v4.y = positions[k + i + 4]; v4.z = positions[k + i + 5]; // 2D slope V1V4 cd = (v4.z - v1.z) / (v4.x - v1.x); h = v1.z - cd * v1.x; // v1 belongs to the slope // facet equations : // we compute each facet normal vector // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0 // we compute the value d by applying the equation to v1 which belongs to the plane // then we store the facet equation in a Vector4 v2.subtractToRef(v1, v1v2); v3.subtractToRef(v1, v1v3); v4.subtractToRef(v1, v1v4); BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2); norm1.normalize(); norm2.normalize(); d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z); d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z); var quad = this._heightQuads[row * subdivisionsX + col]; quad.slope.copyFromFloats(cd, h); quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1); quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2); } } return this; }; GroundMesh.prototype.serialize = function (serializationObject) { _super.prototype.serialize.call(this, serializationObject); serializationObject.subdivisionsX = this._subdivisionsX; serializationObject.subdivisionsY = this._subdivisionsY; serializationObject.minX = this._minX; serializationObject.maxX = this._maxX; serializationObject.minZ = this._minZ; serializationObject.maxZ = this._maxZ; serializationObject.width = this._width; serializationObject.height = this._height; }; GroundMesh.Parse = function (parsedMesh, scene) { var result = new GroundMesh(parsedMesh.name, scene); result._subdivisionsX = parsedMesh.subdivisionsX || 1; result._subdivisionsY = parsedMesh.subdivisionsY || 1; result._minX = parsedMesh.minX; result._maxX = parsedMesh.maxX; result._minZ = parsedMesh.minZ; result._maxZ = parsedMesh.maxZ; result._width = parsedMesh.width; result._height = parsedMesh.height; return result; }; return GroundMesh; }(BABYLON.Mesh)); BABYLON.GroundMesh = GroundMesh; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.groundMesh.js.map var BABYLON; (function (BABYLON) { /** * Creates an instance based on a source mesh. */ var InstancedMesh = /** @class */ (function (_super) { __extends(InstancedMesh, _super); function InstancedMesh(name, source) { var _this = _super.call(this, name, source.getScene()) || this; source.instances.push(_this); _this._sourceMesh = source; _this.position.copyFrom(source.position); _this.rotation.copyFrom(source.rotation); _this.scaling.copyFrom(source.scaling); if (source.rotationQuaternion) { _this.rotationQuaternion = source.rotationQuaternion.clone(); } _this.infiniteDistance = source.infiniteDistance; _this.setPivotMatrix(source.getPivotMatrix()); _this.refreshBoundingInfo(); _this._syncSubMeshes(); return _this; } /** * Returns the string "InstancedMesh". */ InstancedMesh.prototype.getClassName = function () { return "InstancedMesh"; }; Object.defineProperty(InstancedMesh.prototype, "receiveShadows", { // Methods get: function () { return this._sourceMesh.receiveShadows; }, enumerable: true, configurable: true }); Object.defineProperty(InstancedMesh.prototype, "material", { get: function () { return this._sourceMesh.material; }, enumerable: true, configurable: true }); Object.defineProperty(InstancedMesh.prototype, "visibility", { get: function () { return this._sourceMesh.visibility; }, enumerable: true, configurable: true }); Object.defineProperty(InstancedMesh.prototype, "skeleton", { get: function () { return this._sourceMesh.skeleton; }, enumerable: true, configurable: true }); Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", { get: function () { return this._sourceMesh.renderingGroupId; }, set: function (value) { if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) { return; } //no-op with warning BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene"); }, enumerable: true, configurable: true }); /** * Returns the total number of vertices (integer). */ InstancedMesh.prototype.getTotalVertices = function () { return this._sourceMesh.getTotalVertices(); }; Object.defineProperty(InstancedMesh.prototype, "sourceMesh", { get: function () { return this._sourceMesh; }, enumerable: true, configurable: true }); /** * Is this node ready to be used/rendered * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default) * @return {boolean} is it ready */ InstancedMesh.prototype.isReady = function (completeCheck) { if (completeCheck === void 0) { completeCheck = false; } return this._sourceMesh.isReady(completeCheck, true); }; /** * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc. */ InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) { return this._sourceMesh.getVerticesData(kind, copyWhenShared); }; /** * Sets the vertex data of the mesh geometry for the requested `kind`. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data. * The `data` are either a numeric array either a Float32Array. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc). * Note that a new underlying VertexBuffer object is created each call. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed. * * Possible `kind` values : * - BABYLON.VertexBuffer.PositionKind * - BABYLON.VertexBuffer.UVKind * - BABYLON.VertexBuffer.UV2Kind * - BABYLON.VertexBuffer.UV3Kind * - BABYLON.VertexBuffer.UV4Kind * - BABYLON.VertexBuffer.UV5Kind * - BABYLON.VertexBuffer.UV6Kind * - BABYLON.VertexBuffer.ColorKind * - BABYLON.VertexBuffer.MatricesIndicesKind * - BABYLON.VertexBuffer.MatricesIndicesExtraKind * - BABYLON.VertexBuffer.MatricesWeightsKind * - BABYLON.VertexBuffer.MatricesWeightsExtraKind * * Returns the Mesh. */ InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) { if (this.sourceMesh) { this.sourceMesh.setVerticesData(kind, data, updatable, stride); } return this.sourceMesh; }; /** * Updates the existing vertex data of the mesh geometry for the requested `kind`. * If the mesh has no geometry, it is simply returned as it is. * The `data` are either a numeric array either a Float32Array. * No new underlying VertexBuffer object is created. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh. * * Possible `kind` values : * - BABYLON.VertexBuffer.PositionKind * - BABYLON.VertexBuffer.UVKind * - BABYLON.VertexBuffer.UV2Kind * - BABYLON.VertexBuffer.UV3Kind * - BABYLON.VertexBuffer.UV4Kind * - BABYLON.VertexBuffer.UV5Kind * - BABYLON.VertexBuffer.UV6Kind * - BABYLON.VertexBuffer.ColorKind * - BABYLON.VertexBuffer.MatricesIndicesKind * - BABYLON.VertexBuffer.MatricesIndicesExtraKind * - BABYLON.VertexBuffer.MatricesWeightsKind * - BABYLON.VertexBuffer.MatricesWeightsExtraKind * * Returns the Mesh. */ InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) { if (this.sourceMesh) { this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique); } return this.sourceMesh; }; /** * Sets the mesh indices. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array). * If the mesh has no geometry, a new Geometry object is created and set to the mesh. * This method creates a new index buffer each call. * Returns the Mesh. */ InstancedMesh.prototype.setIndices = function (indices, totalVertices) { if (totalVertices === void 0) { totalVertices = null; } if (this.sourceMesh) { this.sourceMesh.setIndices(indices, totalVertices); } return this.sourceMesh; }; /** * Boolean : True if the mesh owns the requested kind of data. */ InstancedMesh.prototype.isVerticesDataPresent = function (kind) { return this._sourceMesh.isVerticesDataPresent(kind); }; /** * Returns an array of indices (IndicesArray). */ InstancedMesh.prototype.getIndices = function () { return this._sourceMesh.getIndices(); }; Object.defineProperty(InstancedMesh.prototype, "_positions", { get: function () { return this._sourceMesh._positions; }, enumerable: true, configurable: true }); /** * Sets a new updated BoundingInfo to the mesh. * Returns the mesh. */ InstancedMesh.prototype.refreshBoundingInfo = function () { var meshBB = this._sourceMesh.getBoundingInfo(); this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone()); this._updateBoundingInfo(); return this; }; InstancedMesh.prototype._preActivate = function () { if (this._currentLOD) { this._currentLOD._preActivate(); } return this; }; InstancedMesh.prototype._activate = function (renderId) { if (this._currentLOD) { this._currentLOD._registerInstanceForRenderId(this, renderId); } return this; }; /** * Returns the current associated LOD AbstractMesh. */ InstancedMesh.prototype.getLOD = function (camera) { if (!camera) { return this; } var boundingInfo = this.getBoundingInfo(); this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere); if (this._currentLOD === this.sourceMesh) { return this; } return this._currentLOD; }; InstancedMesh.prototype._syncSubMeshes = function () { this.releaseSubMeshes(); if (this._sourceMesh.subMeshes) { for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) { this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh); } } return this; }; InstancedMesh.prototype._generatePointsArray = function () { return this._sourceMesh._generatePointsArray(); }; /** * Creates a new InstancedMesh from the current mesh. * - name (string) : the cloned mesh name * - newParent (optional Node) : the optional Node to parent the clone to. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned. * * Returns the clone. */ InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) { var result = this._sourceMesh.createInstance(name); // Deep copy BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []); // Bounding info this.refreshBoundingInfo(); // Parent if (newParent) { result.parent = newParent; } if (!doNotCloneChildren) { // Children for (var index = 0; index < this.getScene().meshes.length; index++) { var mesh = this.getScene().meshes[index]; if (mesh.parent === this) { mesh.clone(mesh.name, result); } } } result.computeWorldMatrix(true); return result; }; /** * Disposes the InstancedMesh. * Returns nothing. */ InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) { if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; } // Remove from mesh var index = this._sourceMesh.instances.indexOf(this); this._sourceMesh.instances.splice(index, 1); _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures); }; return InstancedMesh; }(BABYLON.AbstractMesh)); BABYLON.InstancedMesh = InstancedMesh; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.instancedMesh.js.map var BABYLON; (function (BABYLON) { var LinesMesh = /** @class */ (function (_super) { __extends(LinesMesh, _super); function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) { if (scene === void 0) { scene = null; } if (parent === void 0) { parent = null; } var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this; _this.useVertexColor = useVertexColor; _this.useVertexAlpha = useVertexAlpha; _this.color = new BABYLON.Color3(1, 1, 1); _this.alpha = 1; if (source) { _this.color = source.color.clone(); _this.alpha = source.alpha; _this.useVertexColor = source.useVertexColor; _this.useVertexAlpha = source.useVertexAlpha; } _this._intersectionThreshold = 0.1; var defines = []; var options = { attributes: [BABYLON.VertexBuffer.PositionKind], uniforms: ["world", "viewProjection"], needAlphaBlending: true, defines: defines }; if (useVertexAlpha === false) { options.needAlphaBlending = false; } if (!useVertexColor) { options.uniforms.push("color"); } else { options.defines.push("#define VERTEXCOLOR"); options.attributes.push(BABYLON.VertexBuffer.ColorKind); } _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options); return _this; } Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", { /** * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray. * This margin is expressed in world space coordinates, so its value may vary. * Default value is 0.1 * @returns the intersection Threshold value. */ get: function () { return this._intersectionThreshold; }, /** * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray. * This margin is expressed in world space coordinates, so its value may vary. * @param value the new threshold to apply */ set: function (value) { if (this._intersectionThreshold === value) { return; } this._intersectionThreshold = value; if (this.geometry) { this.geometry.boundingBias = new BABYLON.Vector2(0, value); } }, enumerable: true, configurable: true }); /** * Returns the string "LineMesh" */ LinesMesh.prototype.getClassName = function () { return "LinesMesh"; }; Object.defineProperty(LinesMesh.prototype, "material", { get: function () { return this._colorShader; }, set: function (value) { // Do nothing }, enumerable: true, configurable: true }); Object.defineProperty(LinesMesh.prototype, "checkCollisions", { get: function () { return false; }, enumerable: true, configurable: true }); LinesMesh.prototype.createInstance = function (name) { throw new Error("LinesMeshes do not support createInstance."); }; LinesMesh.prototype._bind = function (subMesh, effect, fillMode) { if (!this._geometry) { return this; } // VBOs this._geometry._bind(this._colorShader.getEffect()); // Color if (!this.useVertexColor) { this._colorShader.setColor4("color", this.color.toColor4(this.alpha)); } return this; }; LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) { if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) { return this; } var engine = this.getScene().getEngine(); // Draw order engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount); return this; }; LinesMesh.prototype.dispose = function (doNotRecurse) { this._colorShader.dispose(); _super.prototype.dispose.call(this, doNotRecurse); }; /** * Returns a new LineMesh object cloned from the current one. */ LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) { return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren); }; return LinesMesh; }(BABYLON.Mesh)); BABYLON.LinesMesh = LinesMesh; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.linesMesh.js.map var BABYLON; (function (BABYLON) { /** * Class containing static functions to help procedurally build meshes */ var MeshBuilder = /** @class */ (function () { function MeshBuilder() { } MeshBuilder.updateSideOrientation = function (orientation) { if (orientation == BABYLON.Mesh.DOUBLESIDE) { return BABYLON.Mesh.DOUBLESIDE; } if (orientation === undefined || orientation === null) { return BABYLON.Mesh.FRONTSIDE; } return orientation; }; /** * Creates a box mesh * * The parameter `size` sets the size (float) of each box side (default 1) * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`) * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 Color3 elements) and `faceUV` (an array of 6 Vector4 elements) * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box * @param name defines the name of the mesh * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns the box mesh */ MeshBuilder.CreateBox = function (name, options, scene) { if (scene === void 0) { scene = null; } var box = new BABYLON.Mesh(name, scene); options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); box._originalBuilderSideOrientation = options.sideOrientation; var vertexData = BABYLON.VertexData.CreateBox(options); vertexData.applyToMesh(box, options.updatable); return box; }; /** * Creates a sphere mesh * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1) * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`) * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32) * * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio * * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude) * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created * @param name defines the name of the mesh * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns the sphere mesh * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere */ MeshBuilder.CreateSphere = function (name, options, scene) { var sphere = new BABYLON.Mesh(name, scene); options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); sphere._originalBuilderSideOrientation = options.sideOrientation; var vertexData = BABYLON.VertexData.CreateSphere(options); vertexData.applyToMesh(sphere, options.updatable); return sphere; }; /** * Creates a plane polygonal mesh. By default, this is a disc * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5) * * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc * * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created * @param name defines the name of the mesh * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns the plane polygonal mesh * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon */ MeshBuilder.CreateDisc = function (name, options, scene) { if (scene === void 0) { scene = null; } var disc = new BABYLON.Mesh(name, scene); options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); disc._originalBuilderSideOrientation = options.sideOrientation; var vertexData = BABYLON.VertexData.CreateDisc(options); vertexData.applyToMesh(disc, options.updatable); return disc; }; /** * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided * * The parameter `radius` sets the radius size (float) of the icosphere (default 1) * * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`) * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size * * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created * @param name defines the name of the mesh * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns the icosahedron mesh * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere */ MeshBuilder.CreateIcoSphere = function (name, options, scene) { var sphere = new BABYLON.Mesh(name, scene); options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); sphere._originalBuilderSideOrientation = options.sideOrientation; var vertexData = BABYLON.VertexData.CreateIcoSphere(options); vertexData.applyToMesh(sphere, options.updatable); return sphere; }; ; /** * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array * * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path * * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11 * * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture * * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created * @param name defines the name of the mesh * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns the ribbon mesh * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes */ MeshBuilder.CreateRibbon = function (name, options, scene) { if (scene === void 0) { scene = null; } var pathArray = options.pathArray; var closeArray = options.closeArray; var closePath = options.closePath; var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); var instance = options.instance; var updatable = options.updatable; if (instance) { // existing ribbon instance update // positionFunction : ribbon case // only pathArray and sideOrientation parameters are taken into account for positions update BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]); var positionFunction = function (positions) { var minlg = pathArray[0].length; var i = 0; var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1; for (var si = 1; si <= ns; si++) { for (var p = 0; p < pathArray.length; p++) { var path = pathArray[p]; var l = path.length; minlg = (minlg < l) ? minlg : l; var j = 0; while (j < minlg) { positions[i] = path[j].x; positions[i + 1] = path[j].y; positions[i + 2] = path[j].z; if (path[j].x < BABYLON.Tmp.Vector3[0].x) { BABYLON.Tmp.Vector3[0].x = path[j].x; } if (path[j].x > BABYLON.Tmp.Vector3[1].x) { BABYLON.Tmp.Vector3[1].x = path[j].x; } if (path[j].y < BABYLON.Tmp.Vector3[0].y) { BABYLON.Tmp.Vector3[0].y = path[j].y; } if (path[j].y > BABYLON.Tmp.Vector3[1].y) { BABYLON.Tmp.Vector3[1].y = path[j].y; } if (path[j].z < BABYLON.Tmp.Vector3[0].z) { BABYLON.Tmp.Vector3[0].z = path[j].z; } if (path[j].z > BABYLON.Tmp.Vector3[1].z) { BABYLON.Tmp.Vector3[1].z = path[j].z; } j++; i += 3; } if (instance._closePath) { positions[i] = path[0].x; positions[i + 1] = path[0].y; positions[i + 2] = path[0].z; i += 3; } } } }; var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind); positionFunction(positions); instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]); instance._boundingInfo.update(instance._worldMatrix); instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false); if (options.colors) { var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind); for (var c = 0; c < options.colors.length; c++) { colors[c * 4] = options.colors[c].r; colors[c * 4 + 1] = options.colors[c].g; colors[c * 4 + 2] = options.colors[c].b; colors[c * 4 + 3] = options.colors[c].a; } instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false); } if (options.uvs) { var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind); for (var i = 0; i < options.uvs.length; i++) { uvs[i * 2] = options.uvs[i].x; uvs[i * 2 + 1] = options.uvs[i].y; } instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false); } if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) { var indices = instance.getIndices(); var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind); var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null; BABYLON.VertexData.ComputeNormals(positions, indices, normals, params); if (instance._closePath) { var indexFirst = 0; var indexLast = 0; for (var p = 0; p < pathArray.length; p++) { indexFirst = instance._idx[p] * 3; if (p + 1 < pathArray.length) { indexLast = (instance._idx[p + 1] - 1) * 3; } else { indexLast = normals.length - 3; } normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5; normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5; normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5; normals[indexLast] = normals[indexFirst]; normals[indexLast + 1] = normals[indexFirst + 1]; normals[indexLast + 2] = normals[indexFirst + 2]; } } if (!(instance.areNormalsFrozen)) { instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false); } } return instance; } else { // new ribbon creation var ribbon = new BABYLON.Mesh(name, scene); ribbon._originalBuilderSideOrientation = sideOrientation; var vertexData = BABYLON.VertexData.CreateRibbon(options); if (closePath) { ribbon._idx = vertexData._idx; } ribbon._closePath = closePath; ribbon._closeArray = closeArray; vertexData.applyToMesh(ribbon, updatable); return ribbon; } }; /** * Creates a cylinder or a cone mesh * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2). * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1). * * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1). * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder. * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n Color3 elements) and `faceUV` (an array of n Vector4 elements). * * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3 * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7 * * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17 * * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface. * * If `enclose` is false, a ring surface is one element. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces. * * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379 * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. * @param name defines the name of the mesh * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns the cylinder mesh * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone */ MeshBuilder.CreateCylinder = function (name, options, scene) { var cylinder = new BABYLON.Mesh(name, scene); options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); cylinder._originalBuilderSideOrientation = options.sideOrientation; var vertexData = BABYLON.VertexData.CreateCylinder(options); vertexData.applyToMesh(cylinder, options.updatable); return cylinder; }; /** * Creates a torus mesh * * The parameter `diameter` sets the diameter size (float) of the torus (default 1) * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5) * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16) * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. * @param name defines the name of the mesh * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns the torus mesh * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus */ MeshBuilder.CreateTorus = function (name, options, scene) { var torus = new BABYLON.Mesh(name, scene); options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); torus._originalBuilderSideOrientation = options.sideOrientation; var vertexData = BABYLON.VertexData.CreateTorus(options); vertexData.applyToMesh(torus, options.updatable); return torus; }; /** * Creates a torus knot mesh * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2) * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32) * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32) * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3) * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. * @param name defines the name of the mesh * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns the torus knot mesh * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot */ MeshBuilder.CreateTorusKnot = function (name, options, scene) { var torusKnot = new BABYLON.Mesh(name, scene); options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); torusKnot._originalBuilderSideOrientation = options.sideOrientation; var vertexData = BABYLON.VertexData.CreateTorusKnot(options); vertexData.applyToMesh(torusKnot, options.updatable); return torusKnot; }; /** * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh * * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function * * The parameter `lines` is an array of lines, each line being an array of successive Vector3 * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster) * * Updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system * @param name defines the name of the new line system * @param options defines the options used to create the line system * @param scene defines the hosting scene * @returns a new line system mesh */ MeshBuilder.CreateLineSystem = function (name, options, scene) { var instance = options.instance; var lines = options.lines; var colors = options.colors; if (instance) { // lines update var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind); var vertexColor; var lineColors; if (colors) { vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind); } var i = 0; var c = 0; for (var l = 0; l < lines.length; l++) { var points = lines[l]; for (var p = 0; p < points.length; p++) { positions[i] = points[p].x; positions[i + 1] = points[p].y; positions[i + 2] = points[p].z; if (colors && vertexColor) { lineColors = colors[l]; vertexColor[c] = lineColors[p].r; vertexColor[c + 1] = lineColors[p].g; vertexColor[c + 2] = lineColors[p].b; vertexColor[c + 3] = lineColors[p].a; c += 4; } i += 3; } } instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false); if (colors && vertexColor) { instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false); } return instance; } // line system creation var useVertexColor = (colors) ? true : false; var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha); var vertexData = BABYLON.VertexData.CreateLineSystem(options); vertexData.applyToMesh(lineSystem, options.updatable); return lineSystem; }; /** * Creates a line mesh * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function * * The parameter `points` is an array successive Vector3 * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines * * The optional parameter `colors` is an array of successive Color4, one per line point * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster) * * When updating an instance, remember that only point positions can change, not the number of points * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines * @param name defines the name of the new line system * @param options defines the options used to create the line system * @param scene defines the hosting scene * @returns a new line mesh */ MeshBuilder.CreateLines = function (name, options, scene) { if (scene === void 0) { scene = null; } var colors = (options.colors) ? [options.colors] : null; var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene); return lines; }; /** * Creates a dashed line mesh * * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function * * The parameter `points` is an array successive Vector3 * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200) * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3) * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1) * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines * * When updating an instance, remember that only point positions can change, not the number of points * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created * @param name defines the name of the mesh * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns the dashed line mesh * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines */ MeshBuilder.CreateDashedLines = function (name, options, scene) { if (scene === void 0) { scene = null; } var points = options.points; var instance = options.instance; var gapSize = options.gapSize || 1; var dashSize = options.dashSize || 3; if (instance) { // dashed lines update var positionFunction = function (positions) { var curvect = BABYLON.Vector3.Zero(); var nbSeg = positions.length / 6; var lg = 0; var nb = 0; var shft = 0; var dashshft = 0; var curshft = 0; var p = 0; var i = 0; var j = 0; for (i = 0; i < points.length - 1; i++) { points[i + 1].subtractToRef(points[i], curvect); lg += curvect.length(); } shft = lg / nbSeg; dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize); for (i = 0; i < points.length - 1; i++) { points[i + 1].subtractToRef(points[i], curvect); nb = Math.floor(curvect.length() / shft); curvect.normalize(); j = 0; while (j < nb && p < positions.length) { curshft = shft * j; positions[p] = points[i].x + curshft * curvect.x; positions[p + 1] = points[i].y + curshft * curvect.y; positions[p + 2] = points[i].z + curshft * curvect.z; positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x; positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y; positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z; p += 6; j++; } } while (p < positions.length) { positions[p] = points[i].x; positions[p + 1] = points[i].y; positions[p + 2] = points[i].z; p += 3; } }; instance.updateMeshPositions(positionFunction, false); return instance; } // dashed lines creation var dashedLines = new BABYLON.LinesMesh(name, scene); var vertexData = BABYLON.VertexData.CreateDashedLines(options); vertexData.applyToMesh(dashedLines, options.updatable); dashedLines.dashSize = dashSize; dashedLines.gapSize = gapSize; return dashedLines; }; /** * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along. * * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve. * * The parameter `scale` (float, default 1) is the value to scale the shape. * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. * @param name defines the name of the mesh * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns the extruded shape mesh * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes */ MeshBuilder.ExtrudeShape = function (name, options, scene) { if (scene === void 0) { scene = null; } var path = options.path; var shape = options.shape; var scale = options.scale || 1; var rotation = options.rotation || 0; var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP; var updatable = options.updatable; var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); var instance = options.instance || null; var invertUV = options.invertUV || false; return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable ? true : false, sideOrientation, instance, invertUV, options.frontUVs || null, options.backUVs || null); }; /** * Creates an custom extruded shape mesh. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along. * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path * * It must returns a float value that will be the rotation in radians applied to the shape on each path point. * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path * * It must returns a float value that will be the scale value applied to the shape on each path point * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray` * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray` * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created * @param name defines the name of the mesh * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns the custom extruded shape mesh * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes */ MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) { var path = options.path; var shape = options.shape; var scaleFunction = options.scaleFunction || (function () { return 1; }); var rotationFunction = options.rotationFunction || (function () { return 0; }); var ribbonCloseArray = options.ribbonCloseArray || false; var ribbonClosePath = options.ribbonClosePath || false; var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP; var updatable = options.updatable; var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); var instance = options.instance; var invertUV = options.invertUV || false; return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable ? true : false, sideOrientation, instance || null, invertUV, options.frontUVs || null, options.backUVs || null); }; /** * Creates lathe mesh. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero * * The parameter `radius` (positive float, default 1) is the radius value of the lathe * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe * * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc" * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created * @param name defines the name of the mesh * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns the lathe mesh * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe */ MeshBuilder.CreateLathe = function (name, options, scene) { var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0; var closed = (options.closed === undefined) ? true : options.closed; var shape = options.shape; var radius = options.radius || 1; var tessellation = options.tessellation || 64; var updatable = options.updatable; var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); var cap = options.cap || BABYLON.Mesh.NO_CAP; var pi2 = Math.PI * 2; var paths = new Array(); var invertUV = options.invertUV || false; var i = 0; var p = 0; var step = pi2 / tessellation * arc; var rotated; var path = new Array(); for (i = 0; i <= tessellation; i++) { var path = []; if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) { path.push(new BABYLON.Vector3(0, shape[0].y, 0)); path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius)); } for (p = 0; p < shape.length; p++) { rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius); path.push(rotated); } if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) { path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius)); path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0)); } paths.push(path); } // lathe ribbon var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene); return lathe; }; /** * Creates a plane mesh * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1) * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`) * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created * @param name defines the name of the mesh * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns the plane mesh * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane */ MeshBuilder.CreatePlane = function (name, options, scene) { var plane = new BABYLON.Mesh(name, scene); options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); plane._originalBuilderSideOrientation = options.sideOrientation; var vertexData = BABYLON.VertexData.CreatePlane(options); vertexData.applyToMesh(plane, options.updatable); if (options.sourcePlane) { plane.translate(options.sourcePlane.normal, options.sourcePlane.d); var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z)); var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal); plane.rotate(vectorProduct, product); } return plane; }; /** * Creates a ground mesh * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created * @param name defines the name of the mesh * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns the ground mesh * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane */ MeshBuilder.CreateGround = function (name, options, scene) { var ground = new BABYLON.GroundMesh(name, scene); ground._setReady(false); ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1; ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1; ground._width = options.width || 1; ground._height = options.height || 1; ground._maxX = ground._width / 2; ground._maxZ = ground._height / 2; ground._minX = -ground._maxX; ground._minZ = -ground._maxZ; var vertexData = BABYLON.VertexData.CreateGround(options); vertexData.applyToMesh(ground, options.updatable); ground._setReady(true); return ground; }; /** * Creates a tiled ground mesh * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. * @param name defines the name of the mesh * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns the tiled ground mesh * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground */ MeshBuilder.CreateTiledGround = function (name, options, scene) { var tiledGround = new BABYLON.Mesh(name, scene); var vertexData = BABYLON.VertexData.CreateTiledGround(options); vertexData.applyToMesh(tiledGround, options.updatable); return tiledGround; }; /** * Creates a ground mesh from a height map * * The parameter `url` sets the URL of the height map image resource. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground. * * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height. * * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time). * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. * @param name defines the name of the mesh * @param url defines the url to the height map * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns the ground mesh * @see http://doc.babylonjs.com/babylon101/height_map * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map */ MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) { var width = options.width || 10.0; var height = options.height || 10.0; var subdivisions = options.subdivisions || 1 | 0; var minHeight = options.minHeight || 0.0; var maxHeight = options.maxHeight || 1.0; var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11); var updatable = options.updatable; var onReady = options.onReady; var ground = new BABYLON.GroundMesh(name, scene); ground._subdivisionsX = subdivisions; ground._subdivisionsY = subdivisions; ground._width = width; ground._height = height; ground._maxX = ground._width / 2.0; ground._maxZ = ground._height / 2.0; ground._minX = -ground._maxX; ground._minZ = -ground._maxZ; ground._setReady(false); var onload = function (img) { // Getting height map data var canvas = document.createElement("canvas"); var context = canvas.getContext("2d"); if (!context) { throw new Error("Unable to get 2d context for CreateGroundFromHeightMap"); } if (scene.isDisposed) { return; } var bufferWidth = img.width; var bufferHeight = img.height; canvas.width = bufferWidth; canvas.height = bufferHeight; context.drawImage(img, 0, 0); // Create VertexData from map data // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949 var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data; var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({ width: width, height: height, subdivisions: subdivisions, minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter, buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight }); vertexData.applyToMesh(ground, updatable); //execute ready callback, if set if (onReady) { onReady(ground); } ground._setReady(true); }; BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database); return ground; }; /** * Creates a polygon mesh * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh * * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4) * * Remember you can only change the shape positions, not their number when updating a polygon * @param name defines the name of the mesh * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns the polygon mesh */ MeshBuilder.CreatePolygon = function (name, options, scene) { options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); var shape = options.shape; var holes = options.holes || []; var depth = options.depth || 0; var contours = []; var hole = []; for (var i = 0; i < shape.length; i++) { contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z); } var epsilon = 0.00000001; if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) { contours.pop(); } var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene); for (var hNb = 0; hNb < holes.length; hNb++) { hole = []; for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) { hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z)); } polygonTriangulation.addHole(hole); } var polygon = polygonTriangulation.build(options.updatable, depth); polygon._originalBuilderSideOrientation = options.sideOrientation; var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs); vertexData.applyToMesh(polygon, options.updatable); return polygon; }; ; /** * Creates an extruded polygon mesh, with depth in the Y direction. * * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements) * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors * @param name defines the name of the mesh * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns the polygon mesh */ MeshBuilder.ExtrudePolygon = function (name, options, scene) { return MeshBuilder.CreatePolygon(name, options, scene); }; ; /** * Creates a tube mesh. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube * * The parameter `radius` (positive float, default 1) sets the tube radius size * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius` * * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. It must return a radius value (positive float) * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL * * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created * @param name defines the name of the mesh * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns the tube mesh * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube */ MeshBuilder.CreateTube = function (name, options, scene) { var path = options.path; var instance = options.instance; var radius = 1.0; if (instance) { radius = instance.radius; } if (options.radius !== undefined) { radius = options.radius; } ; var tessellation = options.tessellation || 64 | 0; var radiusFunction = options.radiusFunction || null; var cap = options.cap || BABYLON.Mesh.NO_CAP; var invertUV = options.invertUV || false; var updatable = options.updatable; var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0; // tube geometry var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) { var tangents = path3D.getTangents(); var normals = path3D.getNormals(); var distances = path3D.getDistances(); var pi2 = Math.PI * 2; var step = pi2 / tessellation * arc; var returnRadius = function () { return radius; }; var radiusFunctionFinal = radiusFunction || returnRadius; var circlePath; var rad; var normal; var rotated; var rotationMatrix = BABYLON.Tmp.Matrix[0]; var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2; for (var i = 0; i < path.length; i++) { rad = radiusFunctionFinal(i, distances[i]); // current radius circlePath = Array(); // current circle array normal = normals[i]; // current normal for (var t = 0; t < tessellation; t++) { BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix); rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero(); BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated); rotated.scaleInPlace(rad).addInPlace(path[i]); circlePath[t] = rotated; } circlePaths[index] = circlePath; index++; } // cap var capPath = function (nbPoints, pathIndex) { var pointCap = Array(); for (var i = 0; i < nbPoints; i++) { pointCap.push(path[pathIndex]); } return pointCap; }; switch (cap) { case BABYLON.Mesh.NO_CAP: break; case BABYLON.Mesh.CAP_START: circlePaths[0] = capPath(tessellation, 0); circlePaths[1] = circlePaths[2].slice(0); break; case BABYLON.Mesh.CAP_END: circlePaths[index] = circlePaths[index - 1].slice(0); circlePaths[index + 1] = capPath(tessellation, path.length - 1); break; case BABYLON.Mesh.CAP_ALL: circlePaths[0] = capPath(tessellation, 0); circlePaths[1] = circlePaths[2].slice(0); circlePaths[index] = circlePaths[index - 1].slice(0); circlePaths[index + 1] = capPath(tessellation, path.length - 1); break; default: break; } return circlePaths; }; var path3D; var pathArray; if (instance) { // tube update var arc = options.arc || instance.arc; path3D = (instance.path3D).update(path); pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc); instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance }); instance.path3D = path3D; instance.pathArray = pathArray; instance.arc = arc; instance.radius = radius; return instance; } // tube creation path3D = new BABYLON.Path3D(path); var newPathArray = new Array(); cap = (cap < 0 || cap > 3) ? 0 : cap; pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc); var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene); tube.pathArray = pathArray; tube.path3D = path3D; tube.tessellation = tessellation; tube.cap = cap; tube.arc = options.arc; tube.radius = radius; return tube; }; /** * Creates a polyhedron mesh * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type * * The parameter `size` (positive float, default 1) sets the polygon size * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value) * * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type` * * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron * * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`) * * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors * * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created * @param name defines the name of the mesh * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns the polyhedron mesh * @see http://doc.babylonjs.com/how_to/polyhedra_shapes */ MeshBuilder.CreatePolyhedron = function (name, options, scene) { var polyhedron = new BABYLON.Mesh(name, scene); options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation); polyhedron._originalBuilderSideOrientation = options.sideOrientation; var vertexData = BABYLON.VertexData.CreatePolyhedron(options); vertexData.applyToMesh(polyhedron, options.updatable); return polyhedron; }; /** * Creates a decal mesh. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal * @param name defines the name of the mesh * @param sourceMesh defines the mesh where the decal must be applied * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns the decal mesh * @see http://doc.babylonjs.com/how_to/decals */ MeshBuilder.CreateDecal = function (name, sourceMesh, options) { var indices = sourceMesh.getIndices(); var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind); var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind); var position = options.position || BABYLON.Vector3.Zero(); var normal = options.normal || BABYLON.Vector3.Up(); var size = options.size || BABYLON.Vector3.One(); var angle = options.angle || 0; // Getting correct rotation if (!normal) { var target = new BABYLON.Vector3(0, 0, 1); var camera = sourceMesh.getScene().activeCamera; var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix()); normal = camera.globalPosition.subtract(cameraWorldTarget); } var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2; var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z); var pitch = Math.atan2(normal.y, len); // Matrix var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z)); var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix); var meshWorldMatrix = sourceMesh.getWorldMatrix(); var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix); var vertexData = new BABYLON.VertexData(); vertexData.indices = []; vertexData.positions = []; vertexData.normals = []; vertexData.uvs = []; var currentVertexDataIndex = 0; var extractDecalVector3 = function (indexId) { var result = new BABYLON.PositionNormalVertex(); if (!indices || !positions || !normals) { return result; } var vertexId = indices[indexId]; result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]); // Send vector to decal local world result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix); // Get normal result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]); result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix); return result; }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js var clip = function (vertices, axis) { if (vertices.length === 0) { return vertices; } var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis)); var clipVertices = function (v0, v1) { var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize); return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor)); }; var result = new Array(); for (var index = 0; index < vertices.length; index += 3) { var v1Out; var v2Out; var v3Out; var total = 0; var nV1 = null; var nV2 = null; var nV3 = null; var nV4 = null; var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize; var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize; var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize; v1Out = d1 > 0; v2Out = d2 > 0; v3Out = d3 > 0; total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0); switch (total) { case 0: result.push(vertices[index]); result.push(vertices[index + 1]); result.push(vertices[index + 2]); break; case 1: if (v1Out) { nV1 = vertices[index + 1]; nV2 = vertices[index + 2]; nV3 = clipVertices(vertices[index], nV1); nV4 = clipVertices(vertices[index], nV2); } if (v2Out) { nV1 = vertices[index]; nV2 = vertices[index + 2]; nV3 = clipVertices(vertices[index + 1], nV1); nV4 = clipVertices(vertices[index + 1], nV2); result.push(nV3); result.push(nV2.clone()); result.push(nV1.clone()); result.push(nV2.clone()); result.push(nV3.clone()); result.push(nV4); break; } if (v3Out) { nV1 = vertices[index]; nV2 = vertices[index + 1]; nV3 = clipVertices(vertices[index + 2], nV1); nV4 = clipVertices(vertices[index + 2], nV2); } if (nV1 && nV2 && nV3 && nV4) { result.push(nV1.clone()); result.push(nV2.clone()); result.push(nV3); result.push(nV4); result.push(nV3.clone()); result.push(nV2.clone()); } break; case 2: if (!v1Out) { nV1 = vertices[index].clone(); nV2 = clipVertices(nV1, vertices[index + 1]); nV3 = clipVertices(nV1, vertices[index + 2]); result.push(nV1); result.push(nV2); result.push(nV3); } if (!v2Out) { nV1 = vertices[index + 1].clone(); nV2 = clipVertices(nV1, vertices[index + 2]); nV3 = clipVertices(nV1, vertices[index]); result.push(nV1); result.push(nV2); result.push(nV3); } if (!v3Out) { nV1 = vertices[index + 2].clone(); nV2 = clipVertices(nV1, vertices[index]); nV3 = clipVertices(nV1, vertices[index + 1]); result.push(nV1); result.push(nV2); result.push(nV3); } break; case 3: break; } } return result; }; for (var index = 0; index < indices.length; index += 3) { var faceVertices = new Array(); faceVertices.push(extractDecalVector3(index)); faceVertices.push(extractDecalVector3(index + 1)); faceVertices.push(extractDecalVector3(index + 2)); // Clip faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0)); faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0)); faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0)); faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0)); faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1)); faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1)); if (faceVertices.length === 0) { continue; } // Add UVs and get back to world for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) { var vertex = faceVertices[vIndex]; //TODO check for Int32Array | Uint32Array | Uint16Array vertexData.indices.push(currentVertexDataIndex); vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3); vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3); vertexData.uvs.push(0.5 + vertex.position.x / size.x); vertexData.uvs.push(0.5 + vertex.position.y / size.y); currentVertexDataIndex++; } } // Return mesh var decal = new BABYLON.Mesh(name, sourceMesh.getScene()); vertexData.applyToMesh(decal); decal.position = position.clone(); decal.rotation = new BABYLON.Vector3(pitch, yaw, angle); return decal; }; // Privates MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) { // extrusion geometry var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) { var tangents = path3D.getTangents(); var normals = path3D.getNormals(); var binormals = path3D.getBinormals(); var distances = path3D.getDistances(); var angle = 0; var returnScale = function () { return scale !== null ? scale : 1; }; var returnRotation = function () { return rotation !== null ? rotation : 0; }; var rotate = custom && rotateFunction ? rotateFunction : returnRotation; var scl = custom && scaleFunction ? scaleFunction : returnScale; var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2; var rotationMatrix = BABYLON.Tmp.Matrix[0]; for (var i = 0; i < curve.length; i++) { var shapePath = new Array(); var angleStep = rotate(i, distances[i]); var scaleRatio = scl(i, distances[i]); for (var p = 0; p < shape.length; p++) { BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix); var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y))); var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero(); BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated); rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]); shapePath[p] = rotated; } shapePaths[index] = shapePath; angle += angleStep; index++; } // cap var capPath = function (shapePath) { var pointCap = Array(); var barycenter = BABYLON.Vector3.Zero(); var i; for (i = 0; i < shapePath.length; i++) { barycenter.addInPlace(shapePath[i]); } barycenter.scaleInPlace(1.0 / shapePath.length); for (i = 0; i < shapePath.length; i++) { pointCap.push(barycenter); } return pointCap; }; switch (cap) { case BABYLON.Mesh.NO_CAP: break; case BABYLON.Mesh.CAP_START: shapePaths[0] = capPath(shapePaths[2]); shapePaths[1] = shapePaths[2]; break; case BABYLON.Mesh.CAP_END: shapePaths[index] = shapePaths[index - 1]; shapePaths[index + 1] = capPath(shapePaths[index - 1]); break; case BABYLON.Mesh.CAP_ALL: shapePaths[0] = capPath(shapePaths[2]); shapePaths[1] = shapePaths[2]; shapePaths[index] = shapePaths[index - 1]; shapePaths[index + 1] = capPath(shapePaths[index - 1]); break; default: break; } return shapePaths; }; var path3D; var pathArray; if (instance) { // instance update path3D = (instance.path3D).update(curve); pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom); instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance); return instance; } // extruded shape creation path3D = new BABYLON.Path3D(curve); var newShapePaths = new Array(); cap = (cap < 0 || cap > 3) ? 0 : cap; pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom); var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene); extrudedGeneric.pathArray = pathArray; extrudedGeneric.path3D = path3D; extrudedGeneric.cap = cap; return extrudedGeneric; }; return MeshBuilder; }()); BABYLON.MeshBuilder = MeshBuilder; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.meshBuilder.js.map BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n\n#include\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#include\n#include\n#include\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include\n#include\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}"}; BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; icurrRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif"}; var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this); globalObject["BABYLON"] = BABYLON; //backwards compatibility if(typeof earcut !== 'undefined') { globalObject["Earcut"] = { earcut: earcut }; } return BABYLON; }); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(17))) /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var deepmerge = __webpack_require__(21); var expDm = deepmerge['default']; exports.deepmerge = expDm; /** * Is the provided string a URL? * * @param urlToCheck the url to inspect */ function isUrl(urlToCheck) { if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) { return true; } return false; } exports.isUrl = isUrl; /** * Convert a string from kebab-case to camelCase * @param s string to convert */ function kebabToCamel(s) { return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); }); } exports.kebabToCamel = kebabToCamel; //https://gist.github.com/youssman/745578062609e8acac9f /** * Convert a string from camelCase to kebab-case * @param str string to convert */ function camelToKebab(str) { return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); }); } exports.camelToKebab = camelToKebab; /** * This will extend an object with configuration values. * What it practically does it take the keys from the configuration and set them on the object. * I the configuration is a tree, it will traverse into the tree. * @param object the object to extend * @param config the configuration object that will extend the object */ function extendClassWithConfig(object, config) { if (!config) return; Object.keys(config).forEach(function (key) { if (key in object && typeof object[key] !== 'function') { // if (typeof object[key] === 'function') return; // if it is an object, iterate internally until reaching basic types if (typeof object[key] === 'object') { extendClassWithConfig(object[key], config[key]); } else { if (config[key] !== undefined) { object[key] = config[key]; } } } }); } exports.extendClassWithConfig = extendClassWithConfig; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvaGVscGVyL2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEscUNBQXVDO0FBRXZDLElBQUksS0FBSyxHQUFHLFNBQVMsQ0FBQyxTQUFTLENBQUMsQ0FBQztBQUNmLDBCQUFTO0FBRTNCOzs7O0dBSUc7QUFDSCxlQUFzQixVQUFrQjtJQUNwQyxJQUFJLFVBQVUsQ0FBQyxPQUFPLENBQUMsTUFBTSxDQUFDLEtBQUssQ0FBQyxJQUFJLFVBQVUsQ0FBQyxPQUFPLENBQUMsR0FBRyxDQUFDLEtBQUssQ0FBQyxJQUFJLFVBQ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UNwRCxpREFBaUQ7WUFDakQsb0VBQW9FO1lBQ3BFLElBQUksT0FBTyxNQUFNLENBQUMsR0FBRyxDQUFDLEtBQUssUUFBUSxFQUFFO2dCQUNqQyxxQkFBcUIsQ0FBQyxNQUFNLENBQUMsR0FBRyxDQUFDLEVBQUUsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUM7YUFDbkQ7aUJBQU07Z0JBQ0gsSUFBSSxNQUFNLENBQUMsR0FBRyxDQUFDLEtBQUssU0FBUyxFQUFFO29CQUMzQixNQUFNLENBQUMsR0FBRyxDQUFDLEdBQUcsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDO2lCQUM3QjthQUNKO1NBQ0o7SUFDTCxDQUFDLENBQUMsQ0FBQztBQUNQLENBQUM7QUFmRCxzREFlQyJ9 /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(__webpack_require__(31)); __export(__webpack_require__(33)); __export(__webpack_require__(39)); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvYXNzZXRzL2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7O0FBQUEsNEJBQXVCO0FBQ3ZCLDJCQUFzQjtBQUN0QixpQ0FBNEIifQ== /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var babylonjs_1 = __webpack_require__(0); var _1 = __webpack_require__(1); /** * This is a simple HTML mapper. * This mapper parses a single HTML element and returns the configuration from its attributes. * it parses numbers and boolean values to the corresponding variable types. * The following HTML element: *
will result in the following configuration: * * { * test: 1, //a number! * randomFlag: boolean, //camelCase and boolean * a: { * string: { * object: "test" //dot-separated object levels * } * } * } */ var HTMLMapper = /** @class */ (function () { function HTMLMapper() { } /** * Map a specific element and get configuration from it * @param element the HTML element to analyze. */ HTMLMapper.prototype.map = function (element) { var config = {}; var _loop_1 = function (attrIdx) { var attr = element.attributes.item(attrIdx); if (!attr) { return "continue"; } // map "object.property" to the right configuration place. var split = attr.nodeName.split('.'); split.reduce(function (currentConfig, key, idx) { //convert html-style to json-style var camelKey = _1.kebabToCamel(key); if (idx === split.length - 1) { var val = attr.nodeValue; // firefox warns nodeValue is deprecated, but I found no sign of it anywhere. if (val === "true") { val = true; } else if (val === "false") { val = false; } else { var isnum = !isNaN(parseFloat(val)) && isFinite(val); ///^\d+$/.test(val); if (isnum) { var number = parseFloat(val); if (!isNaN(number)) { val = number; } } } currentConfig[camelKey] = val; } else { currentConfig[camelKey] = currentConfig[camelKey] || {}; } return currentConfig[camelKey]; }, config); }; for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) { _loop_1(attrIdx); } return config; }; return HTMLMapper; }()); /** * A simple string-to-JSON mapper. * This is the main mapper, used to analyze downloaded JSON-Configuration or JSON payload */ var JSONMapper = /** @class */ (function () { function JSONMapper() { } JSONMapper.prototype.map = function (rawSource) { return JSON.parse(rawSource); }; return JSONMapper; }()); /** * The DOM Mapper will traverse an entire DOM Tree and will load the configuration from the * DOM elements and attributes. */ var DOMMapper = /** @class */ (function () { function DOMMapper() { } /** * The mapping function that will convert HTML data to a viewer configuration object * @param baseElement the baseElement from which to start traversing * @returns a ViewerCOnfiguration object from the provided HTML Element */ DOMMapper.prototype.map = function (baseElement) { var htmlMapper = new HTMLMapper(); var config = htmlMapper.map(baseElement); var traverseChildren = function (element, partConfig) { var children = element.children; if (children.length) { for (var i = 0; i < children.length; ++i) { var item = children.item(i); // use the HTML Mapper to read configuration from a single element var configMapped = htmlMapper.map(item); var key = _1.kebabToCamel(item.nodeName.toLowerCase()); if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') { partConfig[key] = []; } else { if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') { partConfig.push(configMapped); } else if (partConfig[key]) { //exists already! probably an array element.setAttribute('array', 'true'); var oldItem = partConfig[key]; partConfig = [oldItem, configMapped]; } else { partConfig[key] = configMapped; } } traverseChildren(item, partConfig[key] || configMapped); } } return partConfig; }; traverseChildren(baseElement, config); return config; }; return DOMMapper; }()); /** * The MapperManager manages the different implemented mappers. * It allows the user to register new mappers as well and use them to parse their own configuration data */ var MapperManager = /** @class */ (function () { function MapperManager() { this._mappers = { "html": new HTMLMapper(), "json": new JSONMapper(), "dom": new DOMMapper() }; } /** * Get a specific configuration mapper. * * @param type the name of the mapper to load */ MapperManager.prototype.getMapper = function (type) { if (!this._mappers[type]) { babylonjs_1.Tools.Error("No mapper defined for " + type); } return this._mappers[type]; }; /** * Use this functio to register your own configuration mapper. * After a mapper is registered, it can be used to parse the specific type fo configuration to the standard ViewerConfiguration. * @param type the name of the mapper. This will be used to define the configuration type and/or to get the mapper * @param mapper The implemented mapper */ MapperManager.prototype.registerMapper = function (type, mapper) { this._mappers[type] = mapper; }; /** * Dispose the mapper manager and all of its mappers. */ MapperManager.prototype.dispose = function () { this._mappers = {}; }; /** * The default mapper is the JSON mapper. */ MapperManager.DefaultMapper = 'json'; return MapperManager; }()); exports.MapperManager = MapperManager; /** * mapperManager is a singleton of the type MapperManager. * The mapperManager can be disposed directly with calling mapperManager.dispose() * or indirectly with using BabylonViewer.disposeAll() */ exports.mapperManager = new MapperManager(); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWFwcGVycy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL21hcHBlcnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBa0M7QUFHbEMsK0JBQTBDO0FBUzFDOzs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UMsS0FBSyxDQUFDLHdCQUF3QixHQUFHLElBQUksQ0FBQyxDQUFDO1NBQ2hEO1FBQ0QsT0FBTyxJQUFJLENBQUMsUUFBUSxDQUFDLElBQUksQ0FBQyxDQUFDO0lBQy9CLENBQUM7SUFFRDs7Ozs7T0FLRztJQUNJLHNDQUFjLEdBQXJCLFVBQXNCLElBQVksRUFBRSxNQUFlO1FBQy9DLElBQUksQ0FBQyxRQUFRLENBQUMsSUFBSSxDQUFDLEdBQUcsTUFBTSxDQUFDO0lBQ2pDLENBQUM7SUFFRDs7T0FFRztJQUNJLCtCQUFPLEdBQWQ7UUFDSSxJQUFJLENBQUMsUUFBUSxHQUFHLEVBQUUsQ0FBQztJQUN2QixDQUFDO0lBeENEOztPQUVHO0lBQ1csMkJBQWEsR0FBRyxNQUFNLENBQUM7SUF1Q3pDLG9CQUFDO0NBQUEsQUE3Q0QsSUE2Q0M7QUE3Q1ksc0NBQWE7QUErQzFCOzs7O0dBSUc7QUFDUSxRQUFBLGFBQWEsR0FBRyxJQUFJLGFBQWEsRUFBRSxDQUFDIn0= /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var babylonjs_1 = __webpack_require__(0); var ViewerGlobals = /** @class */ (function () { function ViewerGlobals() { this.disableInit = false; this.disableWebGL2Support = false; } Object.defineProperty(ViewerGlobals.prototype, "version", { get: function () { return babylonjs_1.Engine.Version; }, enumerable: true, configurable: true }); return ViewerGlobals; }()); exports.ViewerGlobals = ViewerGlobals; exports.viewerGlobals = new ViewerGlobals(); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ2xvYmFscy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2dsb2JhbHMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBbUM7QUFFbkM7SUFBQTtRQUVXLGdCQUFXLEdBQVksS0FBSyxDQUFDO1FBQzdCLHlCQUFvQixHQUFZLEtBQUssQ0FBQztJQU1qRCxDQUFDO0lBSkcsc0JBQVcsa0NBQU87YUFBbEI7WUFDSSxPQUFPLGtCQUFNLENBQUMsT0FBTyxDQUFDO1FBQzFCLENBQUM7OztPQUFBO0lBRUwsb0JBQUM7QUFBRCxDQUFDLEFBVEQsSUFTQztBQVRZLHNDQUFhO0FBV2YsUUFBQSxhQUFhLEdBQWtCLElBQUksYUFBYSxFQUFFLENBQUMifQ== /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var babylonjs_1 = __webpack_require__(0); var modelAnimation_1 = __webpack_require__(23); var _1 = __webpack_require__(1); /** * The current state of the model */ var ModelState; (function (ModelState) { ModelState[ModelState["INIT"] = 0] = "INIT"; ModelState[ModelState["LOADING"] = 1] = "LOADING"; ModelState[ModelState["LOADED"] = 2] = "LOADED"; ModelState[ModelState["ENTRY"] = 3] = "ENTRY"; ModelState[ModelState["ENTRYDONE"] = 4] = "ENTRYDONE"; ModelState[ModelState["COMPLETE"] = 5] = "COMPLETE"; ModelState[ModelState["CANCELED"] = 6] = "CANCELED"; ModelState[ModelState["ERROR"] = 7] = "ERROR"; })(ModelState = exports.ModelState || (exports.ModelState = {})); /** * The viewer model is a container for all assets representing a sngle loaded model. */ var ViewerModel = /** @class */ (function () { function ViewerModel(_observablesManager, modelConfiguration, _configurationContainer) { var _this = this; this._observablesManager = _observablesManager; this._configurationContainer = _configurationContainer; /** * the list of meshes that are a part of this model */ this._meshes = []; /** * ParticleSystems connected to this model */ this.particleSystems = []; /** * Skeletons defined in this model */ this.skeletons = []; this._loaderDone = false; this._animatables = []; this._frameRate = 60; this._shadowsRenderedAfterLoad = false; this.onLoadedObservable = new babylonjs_1.Observable(); this.onLoadErrorObservable = new babylonjs_1.Observable(); this.onLoadProgressObservable = new babylonjs_1.Observable(); this.onCompleteObservable = new babylonjs_1.Observable(); this.onAfterConfigure = new babylonjs_1.Observable(); this.state = ModelState.INIT; this.rootMesh = new babylonjs_1.AbstractMesh("modelRootMesh"); this._pivotMesh = new babylonjs_1.AbstractMesh("pivotMesh"); this._pivotMesh.parent = this.rootMesh; // rotate 180, gltf fun this._pivotMesh.rotation.y += Math.PI; this._scaleTransition = new babylonjs_1.Animation("scaleAnimation", "scaling", this._frameRate, babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3, babylonjs_1.Animation.ANIMATIONLOOPMODE_CONSTANT); this._animations = []; //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer this._modelConfiguration = _1.deepmerge((this._configurationContainer && this._configurationContainer.configuration.model) || {}, modelConfiguration); if (this._observablesManager) { this._observablesManager.onModelAddedObservable.notifyObservers(this); } if (this._modelConfiguration.entryAnimation) { this.rootMesh.setEnabled(false); } this.onLoadedObservable.add(function () { _this.updateConfiguration(_this._modelConfiguration); if (_this._observablesManager) { _this._observablesManager.onModelLoadedObservable.notifyObservers(_this); } _this._initAnimations(); }); this.onCompleteObservable.add(function () { _this.state = ModelState.COMPLETE; }); } Object.defineProperty(ViewerModel.prototype, "shadowsRenderedAfterLoad", { get: function () { return this._shadowsRenderedAfterLoad; }, set: function (rendered) { if (!rendered) { throw new Error("can only be enabled"); } else { this._shadowsRenderedAfterLoad = rendered; } }, enumerable: true, configurable: true }); ViewerModel.prototype.getViewerId = function () { return this._configurationContainer && this._configurationContainer.viewerId; }; Object.defineProperty(ViewerModel.prototype, "enabled", { /** * Is this model enabled? */ get: function () { return this.rootMesh.isEnabled(); }, /** * Set whether this model is enabled or not. */ set: function (enable) { this.rootMesh.setEnabled(enable); }, enumerable: true, configurable: true }); Object.defineProperty(ViewerModel.prototype, "loaderDone", { set: function (done) { this._loaderDone = done; this._checkCompleteState(); }, enumerable: true, configurable: true }); ViewerModel.prototype._checkCompleteState = function () { if (this._loaderDone && (this.state === ModelState.ENTRYDONE)) { this._modelComplete(); } }; /** * Add a mesh to this model. * Any mesh that has no parent will be provided with the root mesh as its new parent. * * @param mesh the new mesh to add * @param triggerLoaded should this mesh trigger the onLoaded observable. Used when adding meshes manually. */ ViewerModel.prototype.addMesh = function (mesh, triggerLoaded) { if (!mesh.parent) { mesh.parent = this._pivotMesh; } mesh.receiveShadows = !!this.configuration.receiveShadows; this._meshes.push(mesh); if (triggerLoaded) { return this.onLoadedObservable.notifyObserversWithPromise(this); } }; Object.defineProperty(ViewerModel.prototype, "meshes", { /** * get the list of meshes (excluding the root mesh) */ get: function () { return this._meshes; }, enumerable: true, configurable: true }); Object.defineProperty(ViewerModel.prototype, "configuration", { /** * Get the model's configuration */ get: function () { return this._modelConfiguration; }, /** * (Re-)set the model's entire configuration * @param newConfiguration the new configuration to replace the new one */ set: function (newConfiguration) { this._modelConfiguration = newConfiguration; this._configureModel(); }, enumerable: true, configurable: true }); /** * Update the current configuration with new values. * Configuration will not be overwritten, but merged with the new configuration. * Priority is to the new configuration * @param newConfiguration the configuration to be merged into the current configuration; */ ViewerModel.prototype.updateConfiguration = function (newConfiguration) { this._modelConfiguration = _1.deepmerge(this._modelConfiguration, newConfiguration); this._configureModel(); }; ViewerModel.prototype._initAnimations = function () { var _this = this; // check if this is not a gltf loader and init the animations if (this.skeletons.length) { this.skeletons.forEach(function (skeleton, idx) { var ag = new babylonjs_1.AnimationGroup("animation-" + idx); skeleton.getAnimatables().forEach(function (a) { if (a.animations[0]) { ag.addTargetedAnimation(a.animations[0], a); } }); _this.addAnimationGroup(ag); }); } var completeCallback = function () { }; if (this._modelConfiguration.animation) { if (this._modelConfiguration.animation.playOnce) { this._animations.forEach(function (a) { a.playMode = 0 /* ONCE */; }); } if (this._modelConfiguration.animation.autoStart && this._animations.length) { var animationName_1 = this._modelConfiguration.animation.autoStart === true ? this._animations[0].name : this._modelConfiguration.animation.autoStart; completeCallback = function () { _this.playAnimation(animationName_1); }; } } this._enterScene(completeCallback); }; /** * Animates the model from the current position to the default position * @param completeCallback A function to call when the animation has completed */ ViewerModel.prototype._enterScene = function (completeCallback) { var _this = this; var scene = this.rootMesh.getScene(); var previousValue = scene.animationPropertiesOverride.enableBlending; var callback = function () { _this.state = ModelState.ENTRYDONE; scene.animationPropertiesOverride.enableBlending = previousValue; _this._checkCompleteState(); if (completeCallback) completeCallback(); }; if (!this._entryAnimation) { callback(); return; } this.rootMesh.setEnabled(true); // disable blending for the sake of the entry animation; scene.animationPropertiesOverride.enableBlending = false; this._applyAnimation(this._entryAnimation, true, callback); }; /** * Animates the model from the current position to the exit-screen position * @param completeCallback A function to call when the animation has completed */ ViewerModel.prototype._exitScene = function (completeCallback) { if (!this._exitAnimation) { completeCallback(); return; } this._applyAnimation(this._exitAnimation, false, completeCallback); }; ViewerModel.prototype._modelComplete = function () { var _this = this; //reapply material defines to be sure: var meshes = this._pivotMesh.getChildMeshes(false); meshes.filter(function (m) { return m.material; }).forEach(function (mesh) { _this._applyModelMaterialConfiguration(mesh.material); }); this.state = ModelState.COMPLETE; this.onCompleteObservable.notifyObservers(this); }; /** * Add a new animation group to this model. * @param animationGroup the new animation group to be added */ ViewerModel.prototype.addAnimationGroup = function (animationGroup) { this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup)); }; /** * Get the ModelAnimation array */ ViewerModel.prototype.getAnimations = function () { return this._animations; }; /** * Get the animations' names. Using the names you can play a specific animation. */ ViewerModel.prototype.getAnimationNames = function () { return this._animations.map(function (a) { return a.name; }); }; /** * Get an animation by the provided name. Used mainly when playing n animation. * @param name the name of the animation to find */ ViewerModel.prototype._getAnimationByName = function (name) { // can't use .find, noe available on IE var filtered = this._animations.filter(function (a) { return a.name === name; }); // what the next line means - if two animations have the same name, they will not be returned! if (filtered.length === 1) { return filtered[0]; } else { return null; } }; /** * Choose an initialized animation using its name and start playing it * @param name the name of the animation to play * @returns The model aniamtion to be played. */ ViewerModel.prototype.playAnimation = function (name) { var animation = this.setCurrentAnimationByName(name); if (animation) { animation.start(); } return animation; }; ViewerModel.prototype.setCurrentAnimationByName = function (name) { var animation = this._getAnimationByName(name); if (animation) { if (this.currentAnimation && this.currentAnimation.state !== 3 /* STOPPED */) { this.currentAnimation.stop(); } this.currentAnimation = animation; return animation; } else { throw new Error("animation not found - " + name); } }; ViewerModel.prototype._configureModel = function () { var _this = this; // this can be changed to the meshes that have rootMesh a parent without breaking anything. var meshesWithNoParent = [this.rootMesh]; //this._meshes.filter(m => m.parent === this.rootMesh); var updateMeshesWithNoParent = function (variable, value, param) { meshesWithNoParent.forEach(function (mesh) { if (param) { mesh[variable][param] = value; } else { mesh[variable] = value; } }); }; var updateXYZ = function (variable, configValues) { if (configValues.x !== undefined) { updateMeshesWithNoParent(variable, configValues.x, 'x'); } if (configValues.y !== undefined) { updateMeshesWithNoParent(variable, configValues.y, 'y'); } if (configValues.z !== undefined) { updateMeshesWithNoParent(variable, configValues.z, 'z'); } if (configValues.w !== undefined) { updateMeshesWithNoParent(variable, configValues.w, 'w'); } }; if (this._modelConfiguration.normalize) { var center = false; var unitSize = false; var parentIndex = void 0; if (this._modelConfiguration.normalize === true) { center = true; unitSize = true; } else { center = !!this._modelConfiguration.normalize.center; unitSize = !!this._modelConfiguration.normalize.unitSize; parentIndex = this._modelConfiguration.normalize.parentIndex; } var meshesToNormalize = []; if (parentIndex !== undefined) { meshesToNormalize.push(this._meshes[parentIndex]); } else { meshesToNormalize = this._pivotMesh.getChildMeshes(true).length === 1 ? [this._pivotMesh] : meshesWithNoParent; } if (unitSize) { meshesToNormalize.forEach(function (mesh) { mesh.normalizeToUnitCube(true); mesh.computeWorldMatrix(true); }); } if (center) { meshesToNormalize.forEach(function (mesh) { var boundingInfo = mesh.getHierarchyBoundingVectors(true); var sizeVec = boundingInfo.max.subtract(boundingInfo.min); var halfSizeVec = sizeVec.scale(0.5); var center = boundingInfo.min.add(halfSizeVec); mesh.position = center.scale(-1); mesh.position.y += halfSizeVec.y; // Recompute Info. mesh.computeWorldMatrix(true); }); } } else { // if centered, should be done here } // position? if (this._modelConfiguration.position) { updateXYZ('position', this._modelConfiguration.position); } if (this._modelConfiguration.rotation) { //quaternion? if (this._modelConfiguration.rotation.w) { meshesWithNoParent.forEach(function (mesh) { if (!mesh.rotationQuaternion) { mesh.rotationQuaternion = new babylonjs_1.Quaternion(); } }); updateXYZ('rotationQuaternion', this._modelConfiguration.rotation); } else { updateXYZ('rotation', this._modelConfiguration.rotation); } } if (this._modelConfiguration.rotationOffsetAxis) { var rotationAxis_1 = new babylonjs_1.Vector3(0, 0, 0).copyFrom(this._modelConfiguration.rotationOffsetAxis); meshesWithNoParent.forEach(function (m) { if (_this._modelConfiguration.rotationOffsetAngle) { m.rotate(rotationAxis_1, _this._modelConfiguration.rotationOffsetAngle); } }); } if (this._modelConfiguration.scaling) { updateXYZ('scaling', this._modelConfiguration.scaling); } if (this._modelConfiguration.castShadow) { this._meshes.forEach(function (mesh) { babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow'); }); } var meshes = this._pivotMesh.getChildMeshes(false); meshes.filter(function (m) { return m.material; }).forEach(function (mesh) { _this._applyModelMaterialConfiguration(mesh.material); }); if (this._modelConfiguration.entryAnimation) { this._entryAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.entryAnimation); } if (this._modelConfiguration.exitAnimation) { this._exitAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.exitAnimation); } this.onAfterConfigure.notifyObservers(this); }; ViewerModel.prototype._modelAnimationConfigurationToObject = function (animConfig) { var anim = { time: 0.5 }; if (animConfig.scaling) { anim.scaling = babylonjs_1.Vector3.Zero(); } if (animConfig.easingFunction !== undefined) { anim.easingFunction = animConfig.easingFunction; } if (animConfig.easingMode !== undefined) { anim.easingMode = animConfig.easingMode; } _1.extendClassWithConfig(anim, animConfig); return anim; }; /** * Apply a material configuration to a material * @param material Material to apply configuration to */ ViewerModel.prototype._applyModelMaterialConfiguration = function (material) { if (!this._modelConfiguration.material) return; _1.extendClassWithConfig(material, this._modelConfiguration.material); if (material instanceof babylonjs_1.PBRMaterial) { if (this._modelConfiguration.material.directIntensity !== undefined) { material.directIntensity = this._modelConfiguration.material.directIntensity; } if (this._modelConfiguration.material.emissiveIntensity !== undefined) { material.emissiveIntensity = this._modelConfiguration.material.emissiveIntensity; } if (this._modelConfiguration.material.environmentIntensity !== undefined) { material.environmentIntensity = this._modelConfiguration.material.environmentIntensity; } if (this._modelConfiguration.material.directEnabled !== undefined) { material.disableLighting = !this._modelConfiguration.material.directEnabled; } if (this._configurationContainer && this._configurationContainer.reflectionColor) { material.reflectionColor = this._configurationContainer.reflectionColor; } } else if (material instanceof babylonjs_1.MultiMaterial) { for (var i = 0; i < material.subMaterials.length; i++) { var subMaterial = material.subMaterials[i]; if (subMaterial) { this._applyModelMaterialConfiguration(subMaterial); } } } }; /** * Start entry/exit animation given an animation configuration * @param animationConfiguration Entry/Exit animation configuration * @param isEntry Pass true if the animation is an entry animation * @param completeCallback Callback to execute when the animation completes */ ViewerModel.prototype._applyAnimation = function (animationConfiguration, isEntry, completeCallback) { var animations = []; //scale if (animationConfiguration.scaling) { var scaleStart = isEntry ? animationConfiguration.scaling : new babylonjs_1.Vector3(1, 1, 1); var scaleEnd = isEntry ? new babylonjs_1.Vector3(1, 1, 1) : animationConfiguration.scaling; if (!scaleStart.equals(scaleEnd)) { this.rootMesh.scaling = scaleStart; this._setLinearKeys(this._scaleTransition, this.rootMesh.scaling, scaleEnd, animationConfiguration.time); animations.push(this._scaleTransition); } } //Start the animation(s) this.transitionTo(animations, animationConfiguration.time, this._createEasingFunction(animationConfiguration.easingFunction), animationConfiguration.easingMode, function () { if (completeCallback) completeCallback(); }); }; /** * Begin @animations with the specified @easingFunction * @param animations The BABYLON Animations to begin * @param duration of transition, in seconds * @param easingFunction An easing function to apply * @param easingMode A easing mode to apply to the easingFunction * @param onAnimationEnd Call back trigger at the end of the animation. */ ViewerModel.prototype.transitionTo = function (animations, duration, easingFunction, easingMode, onAnimationEnd) { if (easingMode === void 0) { easingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT; } if (easingFunction) { for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) { var animation = animations_1[_i]; easingFunction.setEasingMode(easingMode); animation.setEasingFunction(easingFunction); } } //Stop any current animations before starting the new one - merging not yet supported. this.stopAllAnimations(); this.rootMesh.animations = animations; if (this.rootMesh.getScene().beginAnimation) { var animatable = this.rootMesh.getScene().beginAnimation(this.rootMesh, 0, this._frameRate * duration, false, 1, function () { if (onAnimationEnd) { onAnimationEnd(); } }); this._animatables.push(animatable); } }; /** * Sets key values on an Animation from first to last frame. * @param animation The Babylon animation object to set keys on * @param startValue The value of the first key * @param endValue The value of the last key * @param duration The duration of the animation, used to determine the end frame */ ViewerModel.prototype._setLinearKeys = function (animation, startValue, endValue, duration) { animation.setKeys([ { frame: 0, value: startValue }, { frame: this._frameRate * duration, value: endValue } ]); }; /** * Creates and returns a Babylon easing funtion object based on a string representing the Easing function * @param easingFunctionID The enum of the easing funtion to create * @return The newly created Babylon easing function object */ ViewerModel.prototype._createEasingFunction = function (easingFunctionID) { var easingFunction; switch (easingFunctionID) { case 1 /* CircleEase */: easingFunction = new babylonjs_1.CircleEase(); break; case 2 /* BackEase */: easingFunction = new babylonjs_1.BackEase(0.3); break; case 3 /* BounceEase */: easingFunction = new babylonjs_1.BounceEase(); break; case 4 /* CubicEase */: easingFunction = new babylonjs_1.CubicEase(); break; case 5 /* ElasticEase */: easingFunction = new babylonjs_1.ElasticEase(); break; case 6 /* ExponentialEase */: easingFunction = new babylonjs_1.ExponentialEase(); break; case 7 /* PowerEase */: easingFunction = new babylonjs_1.PowerEase(); break; case 8 /* QuadraticEase */: easingFunction = new babylonjs_1.QuadraticEase(); break; case 9 /* QuarticEase */: easingFunction = new babylonjs_1.QuarticEase(); break; case 10 /* QuinticEase */: easingFunction = new babylonjs_1.QuinticEase(); break; case 11 /* SineEase */: easingFunction = new babylonjs_1.SineEase(); break; default: babylonjs_1.Tools.Log("No ease function found"); break; } return easingFunction; }; /** * Stops and removes all animations that have been applied to the model */ ViewerModel.prototype.stopAllAnimations = function () { if (this.rootMesh) { this.rootMesh.animations = []; } if (this.currentAnimation) { this.currentAnimation.stop(); } while (this._animatables.length) { this._animatables[0].onAnimationEnd = null; this._animatables[0].stop(); this._animatables.shift(); } }; /** * Will remove this model from the viewer (but NOT dispose it). */ ViewerModel.prototype.remove = function () { this.stopAllAnimations(); // hide it this.rootMesh.isVisible = false; if (this._observablesManager) { this._observablesManager.onModelRemovedObservable.notifyObservers(this); } }; /** * Dispose this model, including all of its associated assets. */ ViewerModel.prototype.dispose = function () { this.remove(); this.onAfterConfigure.clear(); this.onLoadedObservable.clear(); this.onLoadErrorObservable.clear(); this.onLoadProgressObservable.clear(); if (this.loader && this.loader.name === "gltf") { this.loader.dispose(); } this.particleSystems.forEach(function (ps) { return ps.dispose(); }); this.particleSystems.length = 0; this.skeletons.forEach(function (s) { return s.dispose(); }); this.skeletons.length = 0; this._animations.forEach(function (ag) { return ag.dispose(); }); this._animations.length = 0; this.rootMesh.dispose(false, true); }; return ViewerModel; }()); exports.ViewerModel = ViewerModel; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTW9kZWwuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbW9kZWwvdmlld2VyTW9kZWwudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBc2Q7QUFJdGQsbURBQXdKO0FBRXhKLCtCQUE4RDtBQUs5RDs7R0FFRztBQUNILElBQVksVUFTWDtBQVRELFdBQVksVUFBVTtJQUNsQiwyQ0FBSSxDQUFBO0lBQ0osaURBQU8sQ0FBQTtJQUNQLCtDQUFNLENBQUE7SUFDTiw2Q0FBSyxDQUFBO0lBQ0wscURBQVMsQ0FBQTtJQUNULG1EQUFRLENBQUE7SUFDUixtREFBUSxDQUFBO0lBQ1IsNkNBQUssQ0FBQTtBQUNULENBQUMsRU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0FBQyxDQUFDO1FBQ2hDLElBQUksQ0FBQyxTQUFTLENBQUMsT0FBTyxDQUFDLFVBQUEsQ0FBQyxJQUFJLE9BQUEsQ0FBQyxDQUFDLE9BQU8sRUFBRSxFQUFYLENBQVcsQ0FBQyxDQUFDO1FBQ3pDLElBQUksQ0FBQyxTQUFTLENBQUMsTUFBTSxHQUFHLENBQUMsQ0FBQztRQUMxQixJQUFJLENBQUMsV0FBVyxDQUFDLE9BQU8sQ0FBQyxVQUFBLEVBQUUsSUFBSSxPQUFBLEVBQUUsQ0FBQyxPQUFPLEVBQUUsRUFBWixDQUFZLENBQUMsQ0FBQztRQUM3QyxJQUFJLENBQUMsV0FBVyxDQUFDLE1BQU0sR0FBRyxDQUFDLENBQUM7UUFDNUIsSUFBSSxDQUFDLFFBQVEsQ0FBQyxPQUFPLENBQUMsS0FBSyxFQUFFLElBQUksQ0FBQyxDQUFDO0lBQ3ZDLENBQUM7SUFDTCxrQkFBQztBQUFELENBQUMsQUE1dEJELElBNHRCQztBQTV0Qlksa0NBQVcifQ== /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var babylonjs_1 = __webpack_require__(0); /** * Receives Telemetry events and raises events to the API */ var TelemetryManager = /** @class */ (function () { function TelemetryManager() { this.onEventBroadcastedObservable = new babylonjs_1.Observable(); this._event = this._eventEnabled; } Object.defineProperty(TelemetryManager.prototype, "broadcast", { /** * Receives a telemetry event * @param event The name of the Telemetry event * @param details An additional value, or an object containing a list of property/value pairs */ get: function () { return this._event; }, enumerable: true, configurable: true }); /** * Log a Telemetry event for errors raised on the WebGL context. * @param engine The Babylon engine with the WebGL context. */ TelemetryManager.prototype.flushWebGLErrors = function (engine, viewerId) { if (!engine) { return; } var logErrors = true; while (logErrors) { var gl = engine._gl; if (gl && gl.getError) { var error = gl.getError(); if (error === gl.NO_ERROR) { logErrors = false; } else { this.broadcast("WebGL Error", viewerId, { error: error }); } } else { logErrors = false; } } }; Object.defineProperty(TelemetryManager.prototype, "enable", { /** * Enable or disable telemetry events * @param enabled Boolan, true if events are enabled */ set: function (enabled) { if (enabled) { this._event = this._eventEnabled; } else { this._event = this._eventDisabled; } }, enumerable: true, configurable: true }); /** * Called on event when disabled, typically do nothing here */ TelemetryManager.prototype._eventDisabled = function () { // nothing to do }; /** * Called on event when enabled * @param event - The name of the Telemetry event * @param details An additional value, or an object containing a list of property/value pairs */ TelemetryManager.prototype._eventEnabled = function (event, viewerId, details) { var telemetryData = { viewerId: viewerId, event: event, session: this.session, date: new Date(), now: window.performance ? window.performance.now() : Date.now(), detail: null }; if (typeof details === "object") { for (var attr in details) { if (details.hasOwnProperty(attr)) { telemetryData[attr] = details[attr]; } } } else if (details) { telemetryData.detail = details; } this.onEventBroadcastedObservable.notifyObservers(telemetryData); }; Object.defineProperty(TelemetryManager.prototype, "session", { /** * Returns the current session ID or creates one if it doesn't exixt * @return The current session ID */ get: function () { if (!this._currentSessionId) { //String + Timestamp + Random Integer this._currentSessionId = "SESSION_" + Date.now() + Math.floor(Math.random() * 0x10000); } return this._currentSessionId; }, enumerable: true, configurable: true }); /** * Disposes the telemetry manager */ TelemetryManager.prototype.dispose = function () { this.onEventBroadcastedObservable.clear(); delete this.onEventBroadcastedObservable; }; return TelemetryManager; }()); exports.TelemetryManager = TelemetryManager; exports.telemetryManager = new TelemetryManager(); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVsZW1ldHJ5TWFuYWdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9tYW5hZ2Vycy90ZWxlbWV0cnlNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQStDO0FBYy9DOztHQUVHO0FBQ0g7SUFBQTtRQUVXLGlDQUE0QixHQUE4QixJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUkxRSx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UMsSUFBSSxDQUFDLGlCQUFpQixFQUFFO2dCQUN6QixxQ0FBcUM7Z0JBQ3JDLElBQUksQ0FBQyxpQkFBaUIsR0FBRyxVQUFVLEdBQUcsSUFBSSxDQUFDLEdBQUcsRUFBRSxHQUFHLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLE1BQU0sRUFBRSxHQUFHLE9BQU8sQ0FBQyxDQUFDO2FBQzFGO1lBQ0QsT0FBTyxJQUFJLENBQUMsaUJBQWlCLENBQUM7UUFDbEMsQ0FBQzs7O09BQUE7SUFFRDs7T0FFRztJQUNJLGtDQUFPLEdBQWQ7UUFDSSxJQUFJLENBQUMsNEJBQTRCLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDMUMsT0FBTyxJQUFJLENBQUMsNEJBQTRCLENBQUM7SUFDN0MsQ0FBQztJQUNMLHVCQUFDO0FBQUQsQ0FBQyxBQTVHRCxJQTRHQztBQTVHWSw0Q0FBZ0I7QUE4R2hCLFFBQUEsZ0JBQWdCLEdBQUcsSUFBSSxnQkFBZ0IsRUFBRSxDQUFDIn0= /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var babylonjs_1 = __webpack_require__(0); /** * The viewer manager is the container for all viewers currently registered on this page. * It is possible to have more than one viewer on a single page. */ var ViewerManager = /** @class */ (function () { function ViewerManager() { this._viewers = {}; this.onViewerAddedObservable = new babylonjs_1.Observable(); this.onViewerRemovedObservable = new babylonjs_1.Observable(); } /** * Adding a new viewer to the viewer manager and start tracking it. * @param viewer the viewer to add */ ViewerManager.prototype.addViewer = function (viewer) { this._viewers[viewer.getBaseId()] = viewer; this._onViewerAdded(viewer); }; /** * remove a viewer from the viewer manager * @param viewer the viewer to remove */ ViewerManager.prototype.removeViewer = function (viewer) { var id = viewer.getBaseId(); delete this._viewers[id]; this.onViewerRemovedObservable.notifyObservers(id); }; /** * Get a viewer by its baseId (if the container element has an ID, it is the this is. if not, a random id was assigned) * @param id the id of the HTMl element (or the viewer's, if none provided) */ ViewerManager.prototype.getViewerById = function (id) { return this._viewers[id]; }; /** * Get a viewer using a container element * @param element the HTML element to search viewers associated with */ ViewerManager.prototype.getViewerByHTMLElement = function (element) { for (var id in this._viewers) { if (this._viewers[id].containerElement === element) { return this.getViewerById(id); } } }; /** * Get a promise that will fullfil when this viewer was initialized. * Since viewer initialization and template injection is asynchronous, using the promise will guaranty that * you will get the viewer after everything was already configured. * @param id the viewer id to find */ ViewerManager.prototype.getViewerPromiseById = function (id) { var _this = this; return new Promise(function (resolve, reject) { var localViewer = _this.getViewerById(id); if (localViewer) { return resolve(localViewer); } var viewerFunction = function (viewer) { if (viewer.getBaseId() === id) { resolve(viewer); _this.onViewerAddedObservable.removeCallback(viewerFunction); } }; _this.onViewerAddedObservable.add(viewerFunction); }); }; ViewerManager.prototype._onViewerAdded = function (viewer) { this.onViewerAdded && this.onViewerAdded(viewer); this.onViewerAddedObservable.notifyObservers(viewer); }; /** * dispose the manager and all of its associated viewers */ ViewerManager.prototype.dispose = function () { delete this._onViewerAdded; for (var id in this._viewers) { this._viewers[id].dispose(); } this.onViewerAddedObservable.clear(); this.onViewerRemovedObservable.clear(); }; return ViewerManager; }()); exports.ViewerManager = ViewerManager; exports.viewerManager = new ViewerManager(); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTWFuYWdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy92aWV3ZXIvdmlld2VyTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUF1QztBQUd2Qzs7O0dBR0c7QUFDSDtJQWlCSTtRQUNJLElBQUksQ0FBQyxRQUFRLEdBQUcsRUFBRSxDQUFDO1FBQ25CLElBQUksQ0FBQyx1QkFBdUIsR0FBRyxJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQU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tBQUssRUFBRSxDQUFDO1FBQ3JDLElBQUksQ0FBQyx5QkFBeUIsQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUMzQyxDQUFDO0lBQ0wsb0JBQUM7QUFBRCxDQUFDLEFBdEdELElBc0dDO0FBdEdZLHNDQUFhO0FBd0dmLFFBQUEsYUFBYSxHQUFHLElBQUksYUFBYSxFQUFFLENBQUMifQ== /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var viewer_1 = __webpack_require__(9); var babylonjs_1 = __webpack_require__(0); /** * The Default viewer is the default implementation of the AbstractViewer. * It uses the templating system to render a new canvas and controls. */ var DefaultViewer = /** @class */ (function (_super) { __extends(DefaultViewer, _super); /** * Create a new default viewer * @param containerElement the element in which the templates will be rendered * @param initialConfiguration the initial configuration. Defaults to extending the default configuration */ function DefaultViewer(containerElement, initialConfiguration) { if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; } var _this = _super.call(this, containerElement, initialConfiguration) || this; _this.containerElement = containerElement; _this._handlePointerDown = function (event) { var pointerDown = event.event; if (pointerDown.button !== 0) return; var element = event.event.target; if (!element) { return; } var parentClasses = element.parentElement.classList; switch (element.id) { case "speed-button": case "types-button": if (parentClasses.contains("open")) { parentClasses.remove("open"); } else { parentClasses.add("open"); } break; case "play-pause-button": _this._togglePlayPause(); break; case "label-option-button": var label = element.dataset["value"]; if (label) { _this._updateAnimationType(label); } break; case "speed-option-button": if (!_this._currentAnimation) { return; } var speed = element.dataset["value"]; if (speed) _this._updateAnimationSpeed(speed); break; case "progress-wrapper": _this._resumePlay = !_this._isAnimationPaused; if (_this._resumePlay) { _this._togglePlayPause(true); } break; case "fullscreen-button": _this.toggleFullscreen(); break; default: return; } }; /** * Plays or Pauses animation */ _this._togglePlayPause = function (noUiUpdate) { if (!_this._currentAnimation) { return; } if (_this._isAnimationPaused) { _this._currentAnimation.restart(); } else { _this._currentAnimation.pause(); } _this._isAnimationPaused = !_this._isAnimationPaused; if (noUiUpdate) return; var navbar = _this.templateManager.getTemplate('navBar'); if (!navbar) return; navbar.updateParams({ paused: _this._isAnimationPaused, }); }; /** * Control progress bar position based on animation current frame */ _this._updateProgressBar = function () { var navbar = _this.templateManager.getTemplate('navBar'); if (!navbar) return; var progressSlider = navbar.parent.querySelector("input#progress-wrapper"); if (progressSlider && _this._currentAnimation) { var progress = _this._currentAnimation.currentFrame / _this._currentAnimation.frames * 100; var currentValue = progressSlider.valueAsNumber; if (Math.abs(currentValue - progress) > 0.5) { // Only move if greater than a 1% change progressSlider.value = '' + progress; } if (_this._currentAnimation.state === 1 /* PLAYING */) { if (_this.sceneManager.camera.autoRotationBehavior && !_this._oldIdleRotationValue) { _this._oldIdleRotationValue = _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed; _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = 0; } } else { if (_this.sceneManager.camera.autoRotationBehavior && _this._oldIdleRotationValue) { _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = _this._oldIdleRotationValue; _this._oldIdleRotationValue = 0; } } } }; /** * Update Current Animation Speed */ _this._updateAnimationSpeed = function (speed, paramsObject) { var navbar = _this.templateManager.getTemplate('navBar'); if (!navbar) return; if (speed && _this._currentAnimation) { _this._currentAnimation.speedRatio = parseFloat(speed); if (!_this._isAnimationPaused) { _this._currentAnimation.restart(); } if (paramsObject) { paramsObject.selectedSpeed = speed + "x"; } else { navbar.updateParams({ selectedSpeed: speed + "x", }); } } }; /** * Update Current Animation Type */ _this._updateAnimationType = function (label, paramsObject) { var navbar = _this.templateManager.getTemplate('navBar'); if (!navbar) return; if (label) { _this._currentAnimation = _this.sceneManager.models[0].setCurrentAnimationByName(label); } if (paramsObject) { paramsObject.selectedAnimation = (_this._animationList.indexOf(label) + 1); paramsObject.selectedAnimationName = label; } else { navbar.updateParams({ selectedAnimation: (_this._animationList.indexOf(label) + 1), selectedAnimationName: label }); } _this._updateAnimationSpeed("1.0", paramsObject); }; /** * Toggle fullscreen of the entire viewer */ _this.toggleFullscreen = function () { var viewerTemplate = _this.templateManager.getTemplate('viewer'); var viewerElement = viewerTemplate && viewerTemplate.parent; if (viewerElement) { var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement; if (!fullscreenElement) { var requestFullScreen = viewerElement.requestFullscreen || viewerElement.webkitRequestFullscreen || viewerElement.msRequestFullscreen || viewerElement.mozRequestFullScreen; requestFullScreen.call(viewerElement); } else { var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen; exitFullscreen.call(document); } } }; _this._onModelLoaded = function (model) { _this._configureTemplate(model); // with a short timeout, making sure everything is there already. var hideLoadingDelay = 20; if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) { hideLoadingDelay = _this.configuration.lab.hideLoadingDelay; } setTimeout(function () { _this.sceneManager.scene.executeWhenReady(function () { _this.hideLoadingScreen(); }); }, hideLoadingDelay); return; }; _this.onModelLoadedObservable.add(_this._onModelLoaded); _this.onModelRemovedObservable.add(function () { _this._configureTemplate(); }); _this.onEngineInitObservable.add(function () { _this.sceneManager.onLightsConfiguredObservable.add(function (data) { _this._configureLights(data.newConfiguration, data.model); }); }); return _this; } /** * This will be executed when the templates initialize. */ DefaultViewer.prototype._onTemplatesLoaded = function () { var _this = this; this.showLoadingScreen(); // navbar this._initNavbar(); // close overlay button var closeButton = document.getElementById('close-button'); if (closeButton) { closeButton.addEventListener('pointerdown', function () { _this.hideOverlayScreen(); }); } if (this.configuration.templates && this.configuration.templates.viewer) { if (this.configuration.templates.viewer.params && this.configuration.templates.viewer.params.enableDragAndDrop) { var filesInput = new babylonjs_1.FilesInput(this.engine, this.sceneManager.scene, function () { }, function () { }, function () { }, function () { }, function () { }, function (file) { _this.loadModel(file); }, function () { }); filesInput.monitorElementForDragNDrop(this.templateManager.getCanvas()); } } return _super.prototype._onTemplatesLoaded.call(this); }; DefaultViewer.prototype._dropped = function (evt) { }; DefaultViewer.prototype._initNavbar = function () { var _this = this; var navbar = this.templateManager.getTemplate('navBar'); if (navbar) { this.onFrameRenderedObservable.add(this._updateProgressBar); this.templateManager.eventManager.registerCallback('navBar', this._handlePointerDown, 'pointerdown'); // an example how to trigger the help button. publiclly available this.templateManager.eventManager.registerCallback("navBar", function () { // do your thing }, "pointerdown", "#help-button"); this.templateManager.eventManager.registerCallback("navBar", function (event) { var evt = event.event; var element = (evt.target); if (!_this._currentAnimation) return; var gotoFrame = +element.value / 100 * _this._currentAnimation.frames; if (isNaN(gotoFrame)) return; _this._currentAnimation.goToFrame(gotoFrame); }, "input"); this.templateManager.eventManager.registerCallback("navBar", function (e) { if (_this._resumePlay) { _this._togglePlayPause(true); } _this._resumePlay = false; }, "pointerup", "#progress-wrapper"); } }; /** * Preparing the container element to present the viewer */ DefaultViewer.prototype._prepareContainerElement = function () { this.containerElement.style.position = 'relative'; this.containerElement.style.height = '100%'; this.containerElement.style.display = 'flex'; }; /** * This function will configure the templates and update them after a model was loaded * It is mainly responsible to changing the title and subtitle etc'. * @param model the model to be used to configure the templates by */ DefaultViewer.prototype._configureTemplate = function (model) { var navbar = this.templateManager.getTemplate('navBar'); if (!navbar) return; var newParams = navbar.configuration.params || {}; if (!model) { newParams.animations = null; } else { var animationNames = model.getAnimationNames(); newParams.animations = animationNames; if (animationNames.length) { this._isAnimationPaused = (model.configuration.animation && !model.configuration.animation.autoStart) || !model.configuration.animation; this._animationList = animationNames; newParams.paused = this._isAnimationPaused; var animationIndex = 0; if (model.configuration.animation && typeof model.configuration.animation.autoStart === 'string') { animationIndex = animationNames.indexOf(model.configuration.animation.autoStart); if (animationIndex === -1) { animationIndex = 0; } } this._updateAnimationType(animationNames[animationIndex], newParams); } else { newParams.animations = null; } if (model.configuration.thumbnail) { newParams.logoImage = model.configuration.thumbnail; } } navbar.updateParams(newParams, false); }; /** * This will load a new model to the default viewer * overriding the AbstractViewer's loadModel. * The scene will automatically be cleared of the old models, if exist. * @param model the configuration object (or URL) to load. */ DefaultViewer.prototype.loadModel = function (model) { var _this = this; if (!model) { model = this.configuration.model; } this.showLoadingScreen(); return _super.prototype.loadModel.call(this, model, true).catch(function (error) { console.log(error); _this.hideLoadingScreen(); _this.showOverlayScreen('error'); return Promise.reject(error); }); }; /** * Show the overlay and the defined sub-screen. * Mainly used for help and errors * @param subScreen the name of the subScreen. Those can be defined in the configuration object */ DefaultViewer.prototype.showOverlayScreen = function (subScreen) { var _this = this; var template = this.templateManager.getTemplate('overlay'); if (!template) return Promise.resolve('Overlay template not found'); return template.show((function (template) { var canvasRect = _this.containerElement.getBoundingClientRect(); template.parent.style.display = 'flex'; template.parent.style.width = canvasRect.width + "px"; template.parent.style.height = canvasRect.height + "px"; template.parent.style.opacity = "1"; var subTemplate = _this.templateManager.getTemplate(subScreen); if (!subTemplate) { return Promise.reject(subScreen + ' template not found'); } return subTemplate.show((function (template) { template.parent.style.display = 'flex'; return Promise.resolve(template); })); })); }; /** * Hide the overlay screen. */ DefaultViewer.prototype.hideOverlayScreen = function () { var template = this.templateManager.getTemplate('overlay'); if (!template) return Promise.resolve('Overlay template not found'); return template.hide((function (template) { template.parent.style.opacity = "0"; var onTransitionEnd = function () { template.parent.removeEventListener("transitionend", onTransitionEnd); template.parent.style.display = 'none'; }; template.parent.addEventListener("transitionend", onTransitionEnd); var overlays = template.parent.querySelectorAll('.overlay'); if (overlays) { for (var i = 0; i < overlays.length; ++i) { var htmlElement = overlays.item(i); htmlElement.style.display = 'none'; } } return Promise.resolve(template); })); }; /** * show the viewer (in case it was hidden) * * @param visibilityFunction an optional function to execute in order to show the container */ DefaultViewer.prototype.show = function (visibilityFunction) { var template = this.templateManager.getTemplate('main'); //not possible, but yet: if (!template) return Promise.reject('Main template not found'); return template.show(visibilityFunction); }; /** * hide the viewer (in case it is visible) * * @param visibilityFunction an optional function to execute in order to hide the container */ DefaultViewer.prototype.hide = function (visibilityFunction) { var template = this.templateManager.getTemplate('main'); //not possible, but yet: if (!template) return Promise.reject('Main template not found'); return template.hide(visibilityFunction); }; /** * Show the loading screen. * The loading screen can be configured using the configuration object */ DefaultViewer.prototype.showLoadingScreen = function () { var _this = this; var template = this.templateManager.getTemplate('loadingScreen'); if (!template) return Promise.resolve('Loading Screen template not found'); return template.show((function (template) { var canvasRect = _this.containerElement.getBoundingClientRect(); // var canvasPositioning = window.getComputedStyle(this.containerElement).position; template.parent.style.display = 'flex'; template.parent.style.width = canvasRect.width + "px"; template.parent.style.height = canvasRect.height + "px"; template.parent.style.opacity = "1"; // from the configuration!!! var color = "black"; if (_this.configuration.templates && _this.configuration.templates.loadingScreen) { color = (_this.configuration.templates.loadingScreen.params && _this.configuration.templates.loadingScreen.params.backgroundColor) || color; } template.parent.style.backgroundColor = color; return Promise.resolve(template); })); }; /** * Hide the loading screen */ DefaultViewer.prototype.hideLoadingScreen = function () { var template = this.templateManager.getTemplate('loadingScreen'); if (!template) return Promise.resolve('Loading Screen template not found'); return template.hide((function (template) { template.parent.style.opacity = "0"; var onTransitionEnd = function () { template.parent.removeEventListener("transitionend", onTransitionEnd); template.parent.style.display = 'none'; }; template.parent.addEventListener("transitionend", onTransitionEnd); return Promise.resolve(template); })); }; DefaultViewer.prototype.dispose = function () { this.templateManager.dispose(); _super.prototype.dispose.call(this); }; DefaultViewer.prototype._onConfigurationLoaded = function (configuration) { var _this = this; _super.prototype._onConfigurationLoaded.call(this, configuration); // initialize the templates var templateConfiguration = this.configuration.templates || {}; this.templateManager.initTemplate(templateConfiguration); // when done, execute onTemplatesLoaded() this.templateManager.onAllLoaded.add(function () { var canvas = _this.templateManager.getCanvas(); if (canvas) { _this._canvas = canvas; } _this._onTemplateLoaded(); }); }; /** * An extension of the light configuration of the abstract viewer. * @param lightsConfiguration the light configuration to use * @param model the model that will be used to configure the lights (if the lights are model-dependant) */ DefaultViewer.prototype._configureLights = function (lightsConfiguration, model) { var _this = this; if (lightsConfiguration === void 0) { lightsConfiguration = {}; } // labs feature - flashlight if (this.configuration.lab && this.configuration.lab.flashlight) { var pointerPosition = babylonjs_1.Vector3.Zero(); var lightTarget_1; var angle = 0.5; var exponent = Math.PI / 2; if (typeof this.configuration.lab.flashlight === "object") { exponent = this.configuration.lab.flashlight.exponent || exponent; angle = this.configuration.lab.flashlight.angle || angle; } var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.sceneManager.scene); if (typeof this.configuration.lab.flashlight === "object") { flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity; if (this.configuration.lab.flashlight.diffuse) { flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r; flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g; flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b; } if (this.configuration.lab.flashlight.specular) { flashlight.specular.r = this.configuration.lab.flashlight.specular.r; flashlight.specular.g = this.configuration.lab.flashlight.specular.g; flashlight.specular.b = this.configuration.lab.flashlight.specular.b; } } this.sceneManager.scene.constantlyUpdateMeshUnderPointer = true; this.sceneManager.scene.onPointerObservable.add(function (eventData, eventState) { if (eventData.type === 4 && eventData.pickInfo) { lightTarget_1 = (eventData.pickInfo.pickedPoint); } else { lightTarget_1 = undefined; } }); var updateFlashlightFunction = function () { if (_this.sceneManager.camera && flashlight) { flashlight.position.copyFrom(_this.sceneManager.camera.position); if (lightTarget_1) { lightTarget_1.subtractToRef(flashlight.position, flashlight.direction); } } }; this.sceneManager.scene.registerBeforeRender(updateFlashlightFunction); this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction); } }; return Defa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BYyxHQXlpQmhEO0FBemlCWSxzQ0FBYSJ9 /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var viewerManager_1 = __webpack_require__(7); var sceneManager_1 = __webpack_require__(22); var loader_1 = __webpack_require__(28); var babylonjs_1 = __webpack_require__(0); var modelLoader_1 = __webpack_require__(13); var globals_1 = __webpack_require__(4); var telemetryManager_1 = __webpack_require__(6); var _1 = __webpack_require__(1); var observablesManager_1 = __webpack_require__(59); var configurationContainer_1 = __webpack_require__(60); var templateManager_1 = __webpack_require__(61); /** * The AbstractViewr is the center of Babylon's viewer. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates */ var AbstractViewer = /** @class */ (function () { function AbstractViewer(containerElement, initialConfiguration) { if (initialConfiguration === void 0) { initialConfiguration = {}; } var _this = this; this.containerElement = containerElement; /** * A flag that controls whether or not the render loop should be executed */ this.runRenderLoop = true; /** * is this viewer disposed? */ this._isDisposed = false; /** * The resize function that will be registered with the window object */ this._resize = function () { // Only resize if Canvas is in the DOM if (!_this.isCanvasInDOM()) { return; } if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) { return; } if (_this.configuration.engine && _this.configuration.engine.disableResize) { return; } _this.engine.resize(); }; /** * render loop that will be executed by the engine */ this._render = function (force) { if (force === void 0) { force = false; } if (force || (_this.sceneManager.scene && _this.sceneManager.scene.activeCamera)) { if (_this.runRenderLoop || force) { _this.engine.performanceMonitor.enable(); _this.sceneManager.scene.render(); _this.onFrameRenderedObservable.notifyObservers(_this); } else { _this.engine.performanceMonitor.disable(); // update camera instead of rendering _this.sceneManager.scene.activeCamera && _this.sceneManager.scene.activeCamera.update(); } } }; // if exists, use the container id. otherwise, generate a random string. if (containerElement.id) { this.baseId = containerElement.id; } else { this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8); } this._registeredOnBeforeRenderFunctions = []; this._configurationContainer = new configurationContainer_1.ConfigurationContainer(); // add this viewer to the viewer manager viewerManager_1.viewerManager.addViewer(this); this.observablesManager = new observablesManager_1.ObservablesManager(); this.modelLoader = new modelLoader_1.ModelLoader(this.observablesManager, this._configurationContainer); babylonjs_1.RenderingManager.AUTOCLEAR = false; // extend the configuration this._configurationLoader = new loader_1.ConfigurationLoader(); this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) { _this._onConfigurationLoaded(configuration); }); this.onSceneInitObservable.add(function () { _this.updateConfiguration(); }); this.onInitDoneObservable.add(function () { _this._isInit = true; _this.engine.runRenderLoop(_this._render); }); this._prepareContainerElement(); } Object.defineProperty(AbstractViewer.prototype, "onSceneInitObservable", { // observables /** * Will notify when the scene was initialized */ get: function () { return this.observablesManager.onSceneInitObservable; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractViewer.prototype, "onEngineInitObservable", { /** * will notify when the engine was initialized */ get: function () { return this.observablesManager.onEngineInitObservable; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractViewer.prototype, "onModelAddedObservable", { /** * Will notify when a new model was added to the scene. * Note that added does not neccessarily mean loaded! */ get: function () { return this.observablesManager.onModelAddedObservable; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractViewer.prototype, "onModelLoadedObservable", { /** * will notify after every model load */ get: function () { return this.observablesManager.onModelLoadedObservable; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractViewer.prototype, "onModelLoadProgressObservable", { /** * will notify when any model notify of progress */ get: function () { return this.observablesManager.onModelLoadProgressObservable; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractViewer.prototype, "onModelLoadErrorObservable", { /** * will notify when any model load failed. */ get: function () { return this.observablesManager.onModelLoadErrorObservable; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractViewer.prototype, "onModelRemovedObservable", { /** * Will notify when a model was removed from the scene; */ get: function () { return this.observablesManager.onModelRemovedObservable; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractViewer.prototype, "onLoaderInitObservable", { /** * will notify when a new loader was initialized. * Used mainly to know when a model starts loading. */ get: function () { return this.observablesManager.onLoaderInitObservable; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractViewer.prototype, "onInitDoneObservable", { /** * Observers registered here will be executed when the entire load process has finished. */ get: function () { return this.observablesManager.onViewerInitDoneObservable; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractViewer.prototype, "onFrameRenderedObservable", { /** * Functions added to this observable will be executed on each frame rendered. */ get: function () { return this.observablesManager.onFrameRenderedObservable; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractViewer.prototype, "canvas", { /** * The (single) canvas of this viewer */ get: function () { return this._canvas; }, enumerable: true, configurable: true }); Object.defineProperty(AbstractViewer.prototype, "configurationContainer", { get: function () { return this._configurationContainer; }, enumerable: true, configurable: true }); /** * get the baseId of this viewer */ AbstractViewer.prototype.getBaseId = function () { return this.baseId; }; /** * Do we have a canvas to render on, and is it a part of the scene */ AbstractViewer.prototype.isCanvasInDOM = function () { return !!this._canvas && !!this._canvas.parentElement; }; Object.defineProperty(AbstractViewer.prototype, "renderInBackground", { /** * Is the engine currently set to rende even when the page is in background */ get: function () { return this.engine && this.engine.renderEvenInBackground; }, /** * Set the viewer's background rendering flag. */ set: function (value) { if (this.engine) { this.engine.renderEvenInBackground = value; } }, enumerable: true, configurable: true }); Object.defineProperty(AbstractViewer.prototype, "configuration", { /** * Get the configuration object. This is a reference only. * The configuration can ONLY be updated using the updateConfiguration function. * changing this object will have no direct effect on the scene. */ get: function () { return this._configurationContainer.configuration; }, enumerable: true, configurable: true }); /** * force resizing the engine. */ AbstractViewer.prototype.forceResize = function () { this._resize(); }; AbstractViewer.prototype._onConfigurationLoaded = function (configuration) { var _this = this; this._configurationContainer.configuration = _1.deepmerge(this.configuration || {}, configuration); if (this.configuration.observers) { this._configureObservers(this.configuration.observers); } // TODO remove this after testing, as this is done in the updateCOnfiguration as well. if (this.configuration.loaderPlugins) { Object.keys(this.configuration.loaderPlugins).forEach((function (name) { if (_this.configuration.loaderPlugins && _this.configuration.loaderPlugins[name]) { _this.modelLoader.addPlugin(name); } })); } this.templateManager = new templateManager_1.TemplateManager(this.containerElement); }; /** * Force a single render loop execution. */ AbstractViewer.prototype.forceRender = function () { this._render(true); }; /** * Takes a screenshot of the scene and returns it as a base64 encoded png. * @param callback optional callback that will be triggered when screenshot is done. * @param width Optional screenshot width (default to 512). * @param height Optional screenshot height (default to 512). * @returns a promise with the screenshot data */ AbstractViewer.prototype.takeScreenshot = function (callback, width, height) { var _this = this; if (width === void 0) { width = 0; } if (height === void 0) { height = 0; } width = width || this.canvas.clientWidth; height = height || this.canvas.clientHeight; // Create the screenshot return new Promise(function (resolve, reject) { try { BABYLON.Tools.CreateScreenshot(_this.engine, _this.sceneManager.camera, { width: width, height: height }, function (data) { if (callback) { callback(data); } resolve(data); }); } catch (e) { reject(e); } }); }; /** * Update the current viewer configuration with new values. * Only provided information will be updated, old configuration values will be kept. * If this.configuration was manually changed, you can trigger this function with no parameters, * and the entire configuration will be updated. * @param newConfiguration the partial configuration to update * */ AbstractViewer.prototype.updateConfiguration = function (newConfiguration) { var _this = this; if (newConfiguration === void 0) { newConfiguration = this.configuration; } // update this.configuration with the new data this._configurationContainer.configuration = _1.deepmerge(this.configuration || {}, newConfiguration); this.sceneManager.updateConfiguration(newConfiguration); // observers in configuration if (newConfiguration.observers) { this._configureObservers(newConfiguration.observers); } if (newConfiguration.loaderPlugins) { Object.keys(newConfiguration.loaderPlugins).forEach((function (name) { if (newConfiguration.loaderPlugins && newConfiguration.loaderPlugins[name]) { _this.modelLoader.addPlugin(name); } })); } }; /** * this is used to register native functions using the configuration object. * This will configure the observers. * @param observersConfiguration observers configuration */ AbstractViewer.prototype._configureObservers = function (observersConfiguration) { if (observersConfiguration.onEngineInit) { this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]); } else { if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) { this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]); } } if (observersConfiguration.onSceneInit) { this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]); } else { if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) { this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]); } } if (observersConfiguration.onModelLoaded) { this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]); } else { if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) { this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]); } } }; /** * Dispoe the entire viewer including the scene and the engine */ AbstractViewer.prototype.dispose = function () { if (this._isDisposed) { return; } window.removeEventListener('resize', this._resize); if (this.sceneManager) { if (this.sceneManager.scene && this.sceneManager.scene.activeCamera) { this.sceneManager.scene.activeCamera.detachControl(this.canvas); } this.sceneManager.dispose(); } this._fpsTimeoutInterval && clearInterval(this._fpsTimeoutInterval); this.observablesManager.dispose(); this.modelLoader.dispose(); if (this.engine) { this.engine.dispose(); } viewerManager_1.viewerManager.removeViewer(this); this._isDisposed = true; }; /** * This function will execute when the HTML templates finished initializing. * It should initialize the engine and continue execution. * * @returns {Promise} The viewer object will be returned after the object was loaded. */ AbstractViewer.prototype._onTemplatesLoaded = function () { return Promise.resolve(this); }; /** * This will force the creation of an engine and a scene. * It will also load a model if preconfigured. * But first - it will load the extendible onTemplateLoaded()! */ AbstractViewer.prototype._onTemplateLoaded = function () { var _this = this; // check if viewer was disposed right after created if (this._isDisposed) { return Promise.reject("viewer was disposed"); } return this._onTemplatesLoaded().then(function () { var autoLoad = typeof _this.configuration.model === 'string' || (_this.configuration.model && _this.configuration.model.url); return _this._initEngine().then(function (engine) { return _this.onEngineInitObservable.notifyObserversWithPromise(engine); }).then(function () { _this._initTelemetryEvents(); if (autoLoad) { return _this.loadModel(_this.configuration.model).catch(function (e) { }).then(function () { return _this.sceneManager.scene; }); } else { return _this.sceneManager.scene || _this.sceneManager.initScene(_this.configuration.scene); } }).then(function () { return _this.onInitDoneObservable.notifyObserversWithPromise(_this); }).catch(function (e) { babylonjs_1.Tools.Warn(e.toString()); return _this; }); }); }; /** * Initialize the engine. Retruns a promise in case async calls are needed. * * @protected * @returns {Promise} * @memberof Viewer */ AbstractViewer.prototype._initEngine = function () { // init custom shaders this._injectCustomShaders(); //let canvasElement = this.templateManager.getCanvas(); if (!this.canvas) { return Promise.reject('Canvas element not found!'); } var config = this.configuration.engine || {}; // TDO enable further configuration // check for webgl2 support, force-disable if needed. if (globals_1.viewerGlobals.disableWebGL2Support) { config.engineOptions = config.engineOptions || {}; config.engineOptions.disableWebGL2Support = true; } this.engine = new babylonjs_1.Engine(this.canvas, !!config.antialiasing, config.engineOptions); // Disable manifest checking babylonjs_1.Database.IDBStorageEnabled = false; if (!config.disableResize) { window.addEventListener('resize', this._resize); } if (this.configuration.engine && this.configuration.engine.adaptiveQuality) { var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2)); this.engine.setHardwareScalingLevel(scale); } // create a new template manager for this viewer this.sceneManager = new sceneManager_1.SceneManager(this.engine, this._configurationContainer, this.observablesManager); return Promise.resolve(this.engine); }; /** * Initialize a model loading. The returned object (a ViewerModel object) will be loaded in the background. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading. * * @param modelConfig model configuration to use when loading the model. * @param clearScene should the scene be cleared before loading this model * @returns a ViewerModel object that is not yet fully loaded. */ AbstractViewer.prototype.initModel = function (modelConfig, clearScene) { var _this = this; if (clearScene === void 0) { clearScene = true; } var configuration; if (typeof modelConfig === 'string') { configuration = { url: modelConfig }; } else if (modelConfig instanceof File) { configuration = { file: modelConfig, root: "file:" }; } else { configuration = modelConfig; } if (!configuration.url && !configuration.file) { throw new Error("no model provided"); } if (clearScene) { this.sceneManager.clearScene(true, false); } //merge the configuration for future models: if (this.configuration.model && typeof this.configuration.model === 'object') { var globalConfig = _1.deepmerge({}, this.configuration.model); configuration = _1.deepmerge(globalConfig, configuration); if (modelConfig instanceof File) { configuration.file = modelConfig; } } else { this.configuration.model = configuration; } this._isLoading = true; var model = this.modelLoader.load(configuration); this.lastUsedLoader = model.loader; model.onLoadErrorObservable.add(function (errorObject) { _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject); }); model.onLoadProgressObservable.add(function (progressEvent) { _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent); }); this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader); model.onLoadedObservable.add(function () { _this._isLoading = false; }); return model; }; /** * load a model using the provided configuration. * This function, as opposed to initModel, will return a promise that resolves when the model is loaded, and rejects with error. * If you want to attach to the observables of the model, use initModle instead. * * @param modelConfig the model configuration or URL to load. * @param clearScene Should the scene be cleared before loading the model * @returns a Promise the fulfills when the model finished loading successfully. */ AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) { var _this = this; if (clearScene === void 0) { clearScene = true; } if (this._isLoading) { // We can decide here whether or not to cancel the lst load, but the developer can do that. return Promise.reject("another model is curently being loaded."); } return Promise.resolve(this.sceneManager.scene).then(function (scene) { if (!scene) return _this.sceneManager.initScene(_this.configuration.scene, _this.configuration.optimizer); return scene; }).then(function () { var model = _this.initModel(modelConfig, clearScene); return new Promise(function (resolve, reject) { // at this point, configuration.model is an object, not a string model.onLoadedObservable.add(function () { resolve(model); }); model.onLoadErrorObservable.add(function (error) { reject(error); }); }); }); }; AbstractViewer.prototype._initTelemetryEvents = function () { var _this = this; telemetryManager_1.telemetryManager.broadcast("Engine Capabilities", this.baseId, this.engine.getCaps()); telemetryManager_1.telemetryManager.broadcast("Platform Details", this.baseId, { userAgent: navigator.userAgent, platform: navigator.platform }); telemetryManager_1.telemetryManager.flushWebGLErrors(this.engine, this.baseId); var trackFPS = function () { telemetryManager_1.telemetryManager.broadcast("Current FPS", _this.baseId, { fps: _this.engine.getFps() }); }; trackFPS(); // Track the FPS again after 60 seconds this._fpsTimeoutInterval = window.setInterval(trackFPS, 60 * 1000); }; /** * Injects all the spectre shader in the babylon shader store */ AbstractViewer.prototype._injectCustomShaders = function () { var customShaders = this.configuration.customShaders; // Inject all the spectre shader in the babylon shader store. if (!customShaders) { return; } if (customShaders.shaders) { Object.keys(customShaders.shaders).forEach(function (key) { // typescript considers a callback "unsafe", so... '!' babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key]; }); } if (customShaders.includes) { Object.keys(customShaders.includes).forEach(function (key) { // typescript considers a callback "unsafe", so... '!' babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key]; }); } }; return AbstractViewer; }()); exports.AbstractViewer = AbstractViewer; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3ZpZXdlci92aWV3ZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpREFBZ0Q7QUFDaEQseURBQXdEO0FBQ3hELGtEQUE4RDtBQUM5RCx1Q0FBbWdCO0FBS25nQixxREFBb0Q7QUFFcEQsb0RBQXlEO0FBRXpELGlFQUFnRTtBQUNoRSwrQkFBdUM7QUFDdkMscUVBQW9FO0FBQ3BFLGtGQUFpRjtBQUNqRixpRUFBZ0U7QUFFaEU7OztHQUdHO0FBQ0g7SUFnSkksd0JBQW1CLGdCQUE2QixFQUFFLG9CQUE4QztRQUE5QyxxQ0FBQSxFQUFBLHlCQUE4QztRQUFoRyxpQkFzQ0M7UUF0Q2tCLHFCQUFnQixHQUFoQixnQkFBZ0IsQ0FBYTtRQXJIaEQ7O1dBRUc7UUFDSSxrQkFBYSxHQUFZLElBQUksQ0FBQztRQXdGckM7O1dBRUc7UUFDTyxnQkFBVyxHQUFZLEtBQUssQ0FBQztRQTZHdkM7O1dBRUc7UUFDTyxZQUFPLEdBQUc7WUFDaEIsc0NBQXNDO1lBQ3RDLElBQUksQ0FBQyxLQUFJLENBQUMsYUFBYSxFQUFFLEVBQUU7Z0JBQ3ZCLE9BQU87YUFDVjtZQU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DLG1CQUFtQixHQUFHLE1BQU0sQ0FBQyxXQUFXLENBQUMsUUFBUSxFQUFFLEVBQUUsR0FBRyxJQUFJLENBQUMsQ0FBQztJQUN2RSxDQUFDO0lBRUQ7O09BRUc7SUFDTyw2Q0FBb0IsR0FBOUI7UUFDSSxJQUFJLGFBQWEsR0FBRyxJQUFJLENBQUMsYUFBYSxDQUFDLGFBQWEsQ0FBQztRQUNyRCw2REFBNkQ7UUFDN0QsSUFBSSxDQUFDLGFBQWEsRUFBRTtZQUNoQixPQUFPO1NBQ1Y7UUFDRCxJQUFJLGFBQWEsQ0FBQyxPQUFPLEVBQUU7WUFDdkIsTUFBTSxDQUFDLElBQUksQ0FBQyxhQUFhLENBQUMsT0FBTyxDQUFDLENBQUMsT0FBTyxDQUFDLFVBQUEsR0FBRztnQkFDMUMsc0RBQXNEO2dCQUN0RCxrQkFBTSxDQUFDLFlBQVksQ0FBQyxHQUFHLENBQUMsR0FBRyxhQUFjLENBQUMsT0FBUSxDQUFDLEdBQUcsQ0FBQyxDQUFDO1lBQzVELENBQUMsQ0FBQyxDQUFDO1NBQ047UUFDRCxJQUFJLGFBQWEsQ0FBQyxRQUFRLEVBQUU7WUFDeEIsTUFBTSxDQUFDLElBQUksQ0FBQyxhQUFhLENBQUMsUUFBUSxDQUFDLENBQUMsT0FBTyxDQUFDLFVBQUEsR0FBRztnQkFDM0Msc0RBQXNEO2dCQUN0RCxrQkFBTSxDQUFDLG9CQUFvQixDQUFDLEdBQUcsQ0FBQyxHQUFHLGFBQWMsQ0FBQyxRQUFTLENBQUMsR0FBRyxDQUFDLENBQUM7WUFDckUsQ0FBQyxDQUFDLENBQUM7U0FDTjtJQUNMLENBQUM7SUFDTCxxQkFBQztBQUFELENBQUMsQUE5bkJELElBOG5CQztBQTluQnFCLHdDQUFjIn0= /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(__webpack_require__(11)); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7OztBQUFBLHFDQUFnQyJ9 /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function getConfigurationKey(key, configObject) { var splits = key.split('.'); if (splits.length === 0 || !configObject) return; else if (splits.length === 1) { if (configObject[key] !== undefined) { return configObject[key]; } } else { var firstKey = splits.shift(); return getConfigurationKey(splits.join("."), configObject[firstKey]); } } exports.getConfigurationKey = getConfigurationKey; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2NvbmZpZ3VyYXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFHQSw2QkFBb0MsR0FBVyxFQUFFLFlBQWlCO0lBQzlELElBQUksTUFBTSxHQUFHLEdBQUcsQ0FBQyxLQUFLLENBQUMsR0FBRyxDQUFDLENBQUM7SUFFNUIsSUFBSSxNQUFNLENBQUMsTUFBTSxLQUFLLENBQUMsSUFBSSxDQUFDLFlBQVk7UUFBRSxPQUFPO1NBQzVDLElBQUksTUFBTSxDQUFDLE1BQU0sS0FBSyxDQUFDLEVBQUU7UUFDMUIsSUFBSSxZQUFZLENBQUMsR0FBRyxDQUFDLEtBQUssU0FBUyxFQUFFO1lBQ2pDLE9BQU8sWUFBWSxDQUFDLEdBQUcsQ0FBQyxDQUFDO1NBQzVCO0tBQ0o7U0FBTTtRQUNILElBQUksUUFBUSxHQUFHLE1BQU0sQ0FBQyxLQUFLLEVBQUUsQ0FBQztRQUM5QixPQUFPLG1CQUFtQixDQUFDLE1BQU0sQ0FBQyxJQUFJLENBQUMsR0FBRyxDQUFDLEVBQUUsWUFBWSxDQUFDLFFBQVMsQ0FBQyxDQUFDLENBQUE7S0FDeEU7QUFDTCxDQUFDO0FBWkQsa0RBWUMifQ== /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var babylonjs_1 = __webpack_require__(0); /** * A minimal WebGL cubemap descriptor */ var TextureCube = /** @class */ (function () { /** * constructor * @param internalFormat WebGL pixel format for the texture on the GPU * @param type WebGL pixel type of the supplied data and texture on the GPU * @param source An array containing mipmap levels of faces, where each mipmap level is an array of faces and each face is a TextureSource object */ function TextureCube(internalFormat, type, source) { if (source === void 0) { source = []; } this.internalFormat = internalFormat; this.type = type; this.source = source; } Object.defineProperty(TextureCube.prototype, "Width", { /** * Returns the width of a face of the texture or 0 if not available */ get: function () { return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].width : 0; }, enumerable: true, configurable: true }); Object.defineProperty(TextureCube.prototype, "Height", { /** * Returns the height of a face of the texture or 0 if not available */ get: function () { return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].height : 0; }, enumerable: true, configurable: true }); return TextureCube; }()); exports.TextureCube = TextureCube; /** * A static class providing methods to aid working with Bablyon textures. */ var TextureUtils = /** @class */ (function () { function TextureUtils() { } /** * Returns a BabylonCubeTexture instance from a Spectre texture cube, subject to sampling parameters. * If such a texture has already been requested in the past, this texture will be returned, otherwise a new one will be created. * The advantage of this is to enable working with texture objects without the need to initialize on the GPU until desired. * @param scene A Babylon Scene instance * @param textureCube A Spectre TextureCube object * @param parameters WebGL texture sampling parameters * @param automaticMipmaps Pass true to enable automatic mipmap generation where possible (requires power of images) * @param environment Specifies that the texture will be used as an environment * @param singleLod Specifies that the texture will be a singleLod (for environment) * @return Babylon cube texture */ TextureUtils.GetBabylonCubeTexture = function (scene, textureCube, automaticMipmaps, environment, singleLod) { if (environment === void 0) { environment = false; } if (singleLod === void 0) { singleLod = false; } if (!textureCube) throw new Error("no texture cube provided"); var parameters; if (environment) { parameters = singleLod ? TextureUtils._EnvironmentSingleMipSampling : TextureUtils._EnvironmentSampling; } else { parameters = { magFilter: 9728 /* NEAREST */, minFilter: 9728 /* NEAREST */, wrapS: 33071 /* CLAMP_TO_EDGE */, wrapT: 33071 /* CLAMP_TO_EDGE */ }; } var key = TextureUtils.BabylonTextureKeyPrefix + parameters.magFilter + '' + parameters.minFilter + '' + parameters.wrapS + '' + parameters.wrapT; var babylonTexture = textureCube[key]; if (!babylonTexture) { //initialize babylon texture babylonTexture = new babylonjs_1.CubeTexture('', scene); if (environment) { babylonTexture.lodGenerationOffset = TextureUtils.EnvironmentLODOffset; babylonTexture.lodGenerationScale = TextureUtils.EnvironmentLODScale; } babylonTexture.gammaSpace = false; var internalTexture_1 = new babylonjs_1.InternalTexture(scene.getEngine(), babylonjs_1.InternalTexture.DATASOURCE_CUBERAW); var glTexture_1 = internalTexture_1._webGLTexture; //babylon properties internalTexture_1.isCube = true; internalTexture_1.generateMipMaps = false; babylonTexture._texture = internalTexture_1; TextureUtils.ApplySamplingParameters(babylonTexture, parameters); var maxMipLevel_1 = automaticMipmaps ? 0 : textureCube.source.length - 1; var texturesUploaded_1 = 0; var textureComplete = function () { return texturesUploaded_1 === ((maxMipLevel_1 + 1) * 6); }; var uploadFace = function (i, level, face) { if (!glTexture_1) return; if (i === 0 && level === 0) { internalTexture_1.width = face.width; internalTexture_1.height = face.height; } var gl = (scene.getEngine())._gl; gl.bindTexture(gl.TEXTURE_CUBE_MAP, glTexture_1); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0); if (face instanceof HTMLElement || face instanceof ImageData) { gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureCube.internalFormat, textureCube.type, face); } else { var textureData = face; gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureData.width, textureData.height, 0, textureData.format, textureCube.type, textureData.data); } texturesUploaded_1++; if (textureComplete()) { //generate mipmaps if (automaticMipmaps) { var w = face.width; var h = face.height; var isPot = (((w !== 0) && (w & (w - 1))) === 0) && (((h !== 0) && (h & (h - 1))) === 0); if (isPot) { gl.generateMipmap(gl.TEXTURE_CUBE_MAP); } } // Upload Separate lods in case there is no support for texture lod. if (environment && !scene.getEngine().getCaps().textureLOD && !singleLod) { var mipSlices = 3; for (var i_1 = 0; i_1 < mipSlices; i_1++) { var lodKey = TextureUtils.BabylonTextureKeyPrefix + 'lod' + i_1; var lod = textureCube[lodKey]; //initialize lod texture if it doesn't already exist if (lod == null && textureCube.Width) { //compute LOD from even spacing in smoothness (matching shader calculation) var smoothness = i_1 / (mipSlices - 1); var roughness = 1 - smoothness; var kMinimumVariance = 0.0005; var alphaG = roughness * roughness + kMinimumVariance; var microsurfaceAverageSlopeTexels = alphaG * textureCube.Width; var environmentSpecularLOD = TextureUtils.EnvironmentLODScale * (babylonjs_1.Scalar.Log2(microsurfaceAverageSlopeTexels)) + TextureUtils.EnvironmentLODOffset; var maxLODIndex = textureCube.source.length - 1; var mipmapIndex = Math.min(Math.max(Math.round(environmentSpecularLOD), 0), maxLODIndex); lod = TextureUtils.GetBabylonCubeTexture(scene, new TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */, [textureCube.source[mipmapIndex]]), false, true, true); if (i_1 === 0) { internalTexture_1._lodTextureLow = lod; } else if (i_1 === 1) { internalTexture_1._lodTextureMid = lod; } else { internalTexture_1._lodTextureHigh = lod; } textureCube[lodKey] = lod; } } } internalTexture_1.isReady = true; } gl.bindTexture(gl.TEXTURE_CUBE_MAP, null); scene.getEngine().resetTextureCache(); }; var _loop_1 = function (i) { var faces = textureCube.source[i]; var _loop_2 = function (j) { var face = faces[j]; if (face instanceof HTMLImageElement && !face.complete) { face.addEventListener('load', function () { uploadFace(j, i, face); }, false); } else { uploadFace(j, i, face); } }; for (var j = 0; j < faces.length; j++) { _loop_2(j); } }; for (var i = 0; i <= maxMipLevel_1; i++) { _loop_1(i); } scene.getEngine().resetTextureCache(); babylonTexture.isReady = function () { return textureComplete(); }; textureCube[key] = babylonTexture; } return babylonTexture; }; /** * Applies Spectre SamplingParameters to a Babylon texture by directly setting texture parameters on the internal WebGLTexture as well as setting Babylon fields * @param babylonTexture Babylon texture to apply texture to (requires the Babylon texture has an initialize _texture field) * @param parameters Spectre SamplingParameters to apply */ TextureUtils.ApplySamplingParameters = function (babylonTexture, parameters) { var scene = babylonTexture.getScene(); if (!scene) return; var gl = (scene.getEngine())._gl; var target = babylonTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D; var internalTexture = babylonTexture._texture; if (!internalTexture) return; var glTexture = internalTexture._webGLTexture; gl.bindTexture(target, glTexture); if (parameters.magFilter != null) gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, parameters.magFilter); if (parameters.minFilter != null) gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, parameters.minFilter); if (parameters.wrapS != null) gl.texParameteri(target, gl.TEXTURE_WRAP_S, parameters.wrapS); if (parameters.wrapT != null) gl.texParameteri(target, gl.TEXTURE_WRAP_T, parameters.wrapT); //set babylon wrap modes from sampling parameter switch (parameters.wrapS) { case 10497 /* REPEAT */: babylonTexture.wrapU = babylonjs_1.Texture.WRAP_ADDRESSMODE; break; case 33071 /* CLAMP_TO_EDGE */: babylonTexture.wrapU = babylonjs_1.Texture.CLAMP_ADDRESSMODE; break; case 33648 /* MIRRORED_REPEAT */: babylonTexture.wrapU = babylonjs_1.Texture.MIRROR_ADDRESSMODE; break; default: babylonTexture.wrapU = babylonjs_1.Texture.CLAMP_ADDRESSMODE; } switch (parameters.wrapT) { case 10497 /* REPEAT */: babylonTexture.wrapV = babylonjs_1.Texture.WRAP_ADDRESSMODE; break; case 33071 /* CLAMP_TO_EDGE */: babylonTexture.wrapV = babylonjs_1.Texture.CLAMP_ADDRESSMODE; break; case 33648 /* MIRRORED_REPEAT */: babylonTexture.wrapV = babylonjs_1.Texture.MIRROR_ADDRESSMODE; break; default: babylonTexture.wrapV = babylonjs_1.Texture.CLAMP_ADDRESSMODE; } if (parameters.maxAnisotropy != null && parameters.maxAnisotropy > 1) { var anisotropicExt = gl.getExtension('EXT_texture_filter_anisotropic'); if (anisotropicExt) { var maxAnisotropicSamples = gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT); var maxAnisotropy = Math.min(parameters.maxAnisotropy, maxAnisotropicSamples); gl.texParameterf(target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropy); babylonTexture.anisotropicFilteringLevel = maxAnisotropy; } } gl.bindTexture(target, null); scene.getEngine().resetTextureCache(); }; /** * A prefix used when storing a babylon texture object reference on a Spectre texture object */ TextureUtils.BabylonTextureKeyPrefix = '__babylonTexture_'; /** * Controls anisotropic filtering for deserialized textures. */ TextureUtils.MaxAnisotropy = 4; TextureUtils._EnvironmentSampling = { magFilter: 9729 /* LINEAR */, minFilter: 9987 /* LINEAR_MIPMAP_LINEAR */, wrapS: 33071 /* CLAMP_TO_EDGE */, wrapT: 33071 /* CLAMP_TO_EDGE */, maxAnisotropy: 1 }; TextureUtils._EnvironmentSingleMipSampling = { magFilter: 9729 /* LINEAR */, minFilter: 9729 /* LINEAR */, wrapS: 33071 /* CLAMP_TO_EDGE */, wrapT: 33071 /* CLAMP_TO_EDGE */, maxAnisotropy: 1 }; //from "/Internal/Lighting.EnvironmentFilterScale" in Engine/*/Configuration.cpp /** * Environment preprocessing dedicated value (Internal Use or Advanced only). */ TextureUtils.EnvironmentLODScale = 0.8; /** * Environment preprocessing dedicated value (Internal Use or Advanced only).. */ TextureUtils.EnvironmentLODOffset = 1.0; return TextureUtils; }()); exports.TextureUtils = TextureUtils; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJ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yxHQUFHLENBQUM7SUFDN0MsbUJBQUM7Q0FBQSxBQTFQRCxJQTBQQztBQTFQWSxvQ0FBWSJ9 /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var babylonjs_1 = __webpack_require__(0); var babylonjs_loaders_1 = __webpack_require__(14); var viewerModel_1 = __webpack_require__(5); var _1 = __webpack_require__(54); /** * An instance of the class is in charge of loading the model correctly. * This class will continously be expended with tasks required from the specific loaders Babylon has. * * A Model loader is unique per (Abstract)Viewer. It is being generated by the viewer */ var ModelLoader = /** @class */ (function () { /** * Create a new Model loader * @param _viewer the viewer using this model loader */ function ModelLoader(_observablesManager, _configurationContainer) { this._observablesManager = _observablesManager; this._configurationContainer = _configurationContainer; this._disposed = false; this._loaders = []; this._loadId = 0; this._plugins = []; } /** * Adds a new plugin to the loader process. * * @param plugin the plugin name or the plugin itself */ ModelLoader.prototype.addPlugin = function (plugin) { var actualPlugin = {}; if (typeof plugin === 'string') { var loadedPlugin = _1.getLoaderPluginByName(plugin); if (loadedPlugin) { actualPlugin = loadedPlugin; } } else { actualPlugin = plugin; } if (actualPlugin && this._plugins.indexOf(actualPlugin) === -1) { this._plugins.push(actualPlugin); } }; /** * Load a model using predefined configuration * @param modelConfiguration the modelConfiguration to use to load the model */ ModelLoader.prototype.load = function (modelConfiguration) { var _this = this; var model = new viewerModel_1.ViewerModel(this._observablesManager, modelConfiguration); model.loadId = this._loadId++; if (!modelConfiguration.url) { model.state = viewerModel_1.ModelState.ERROR; babylonjs_1.Tools.Error("No URL provided"); return model; } var base; var filename; if (modelConfiguration.file) { base = "file:"; filename = modelConfiguration.file; } else { filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url; base = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url); } var plugin = modelConfiguration.loader; var scene = model.rootMesh.getScene(); model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, scene, function (meshes, particleSystems, skeletons, animationGroups) { meshes.forEach(function (mesh) { babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh"); model.addMesh(mesh); }); model.particleSystems = particleSystems; model.skeletons = skeletons; for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) { var animationGroup = animationGroups_1[_i]; model.addAnimationGroup(animationGroup); } _this._checkAndRun("onLoaded", model); scene.executeWhenReady(function () { model.onLoadedObservable.notifyObservers(model); }); }, function (progressEvent) { _this._checkAndRun("onProgress", progressEvent); model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent); }, function (scene, m, exception) { model.state = viewerModel_1.ModelState.ERROR; babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m); _this._checkAndRun("onError", m, exception); model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception }); }, plugin); if (model.loader.name === "gltf") { var gltfLoader_1 = model.loader; gltfLoader_1.animationStartMode = babylonjs_loaders_1.GLTFLoaderAnimationStartMode.NONE; gltfLoader_1.compileMaterials = true; if (!modelConfiguration.file) { gltfLoader_1.rewriteRootURL = function (rootURL, responseURL) { return modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(responseURL || modelConfiguration.url || ''); }; } // if ground is set to "mirror": if (this._configurationContainer && this._configurationContainer.configuration && this._configurationContainer.configuration.ground && typeof this._configurationContainer.configuration.ground === 'object' && this._configurationContainer.configuration.ground.mirror) { gltfLoader_1.useClipPlane = true; } Object.keys(gltfLoader_1).filter(function (name) { return name.indexOf('on') === 0 && name.indexOf('Observable') !== -1; }).forEach(function (functionName) { gltfLoader_1[functionName].add(function (payload) { _this._checkAndRun(functionName.replace("Observable", ''), payload); }); }); gltfLoader_1.onParsedObservable.add(function (data) { if (data && data.json && data.json['asset']) { model.loadInfo = data.json['asset']; } }); gltfLoader_1.onCompleteObservable.add(function () { model.loaderDone = true; }); } else { model.loaderDone = true; } this._checkAndRun("onInit", model.loader, model); this._loaders.push(model.loader); return model; }; ModelLoader.prototype.cancelLoad = function (model) { var loader = model.loader || this._loaders[model.loadId]; // ATM only available in the GLTF Loader if (loader && loader.name === "gltf") { var gltfLoader = loader; gltfLoader.dispose(); model.state = viewerModel_1.ModelState.CANCELED; } else { babylonjs_1.Tools.Warn("This type of loader cannot cancel the request"); } }; /** * dispose the model loader. * If loaders are registered and are in the middle of loading, they will be disposed and the request(s) will be cancelled. */ ModelLoader.prototype.dispose = function () { this._loaders.forEach(function (loader) { if (loader.name === "gltf") { loader.dispose(); } }); this._loaders.length = 0; this._disposed = true; }; ModelLoader.prototype._checkAndRun = function (functionName) { var _this = this; var payload = []; for (var _i = 1; _i < arguments.length; _i++) { payload[_i - 1] = arguments[_i]; } if (this._disposed) return; this._plugins.filter(function (p) { return p[functionName]; }).forEach(function (plugin) { try { plugin[functionName].apply(_this, payload); } catch (e) { } }); }; return ModelLoader; }()); exports.ModelLoader = ModelLoader; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kZWxMb2FkZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbG9hZGVyL21vZGVsTG9hZGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQWtHO0FBQ2xHLHVEQUFpRjtBQUdqRixvREFBK0Q7QUFDL0QsK0JBQXlGO0FBSXpGOzs7OztHQUtHO0FBQ0g7SUFTSTs7O09BR0c7SUFDSCxxQkFBb0IsbUJBQXVDLEVBQVUsdUJBQWdEO1FBQWpHLHdCQUFtQixHQUFuQixtQkFBbUIsQ0FBb0I7UUFBVSw0QkFBdUIsR0FBdkIsdUJBQXVCLENBQXlCO1FBVjdHLGNBQVMsR0FBRyxLQUFLLENBQUM7UUFXdEIsSUFBSSxDQUFDLFFBQVEsR0FBRyxFQUFFLENBQUM7UUFDbkIsSUFBSSxDQUFDLE9BQU8sR0FBRyxDQUFDLENBQUM7UUFDakIsSUFBSSxDQUFDL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MsT0FBTyxDQUFDLFVBQUEsTUFBTTtZQUNyRCxJQUFJO2dCQUNBLE1BQU0sQ0FBQyxZQUFZLENBQUMsQ0FBQyxLQUFLLENBQUMsS0FBSSxFQUFFLE9BQU8sQ0FBQyxDQUFDO2FBQzdDO1lBQUMsT0FBTyxDQUFDLEVBQUUsR0FBRztRQUNuQixDQUFDLENBQUMsQ0FBQTtJQUNOLENBQUM7SUFDTCxrQkFBQztBQUFELENBQUMsQUFoTEQsSUFnTEM7QUFoTFksa0NBQVcifQ== /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { (function universalModuleDefinition(root, factory) { var amdDependencies = []; var BABYLON = root.BABYLON || this.BABYLON; if(true) { BABYLON = BABYLON || __webpack_require__(0); module.exports = factory(BABYLON); } else if(typeof define === 'function' && define.amd) { amdDependencies.push("babylonjs"); define("babylonjs-loaders", amdDependencies, factory); } else if(typeof exports === 'object') { BABYLON = BABYLON || require("babylonjs"); exports["babylonjs-loaders"] = factory(BABYLON); } else { root["BABYLON"] = factory(BABYLON); } })(this, function(BABYLON) { BABYLON = BABYLON || this.BABYLON; var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n}; var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(); var BABYLON; (function (BABYLON) { var STLFileLoader = /** @class */ (function () { function STLFileLoader() { this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g; this.facetsPattern = /facet([\s\S]*?)endfacet/g; this.normalPattern = /normal[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g; this.vertexPattern = /vertex[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g; this.name = "stl"; // force data to come in as an ArrayBuffer // we'll convert to string if it looks like it's an ASCII .stl this.extensions = { ".stl": { isBinary: true }, }; } STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) { var matches; if (this.isBinary(data)) { // binary .stl var babylonMesh = new BABYLON.Mesh("stlmesh", scene); this.parseBinary(babylonMesh, data); if (meshes) { meshes.push(babylonMesh); } return true; } // ASCII .stl // convert to string var array_buffer = new Uint8Array(data); var str = ''; for (var i = 0; i < data.byteLength; i++) { str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian } data = str; while (matches = this.solidPattern.exec(data)) { var meshName = matches[1]; var meshNameFromEnd = matches[3]; if (meshName != meshNameFromEnd) { BABYLON.Tools.Error("Error in STL, solid name != endsolid name"); return false; } // check meshesNames if (meshesNames && meshName) { if (meshesNames instanceof Array) { if (!meshesNames.indexOf(meshName)) { continue; } } else { if (meshName !== meshesNames) { continue; } } } // stl mesh name can be empty as well meshName = meshName || "stlmesh"; var babylonMesh = new BABYLON.Mesh(meshName, scene); this.parseASCII(babylonMesh, matches[2]); if (meshes) { meshes.push(babylonMesh); } } return true; }; STLFileLoader.prototype.load = function (scene, data, rootUrl) { var result = this.importMesh(null, scene, data, rootUrl, null, null, null); if (result) { scene.createDefaultCameraOrLight(); } return result; }; STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) { var container = new BABYLON.AssetContainer(scene); this.importMesh(null, scene, data, rootUrl, container.meshes, null, null); container.removeAllFromScene(); return container; }; STLFileLoader.prototype.isBinary = function (data) { // check if file size is correct for binary stl var faceSize, nFaces, reader; reader = new DataView(data); faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8); nFaces = reader.getUint32(80, true); if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) { return true; } // check characters higher than ASCII to confirm binary var fileLength = reader.byteLength; for (var index = 0; index < fileLength; index++) { if (reader.getUint8(index) > 127) { return true; } } return false; }; STLFileLoader.prototype.parseBinary = function (mesh, data) { var reader = new DataView(data); var faces = reader.getUint32(80, true); var dataOffset = 84; var faceLength = 12 * 4 + 2; var offset = 0; var positions = new Float32Array(faces * 3 * 3); var normals = new Float32Array(faces * 3 * 3); var indices = new Uint32Array(faces * 3); var indicesCount = 0; for (var face = 0; face < faces; face++) { var start = dataOffset + face * faceLength; var normalX = reader.getFloat32(start, true); var normalY = reader.getFloat32(start + 4, true); var normalZ = reader.getFloat32(start + 8, true); for (var i = 1; i <= 3; i++) { var vertexstart = start + i * 12; // ordering is intentional to match ascii import positions[offset] = reader.getFloat32(vertexstart, true); positions[offset + 2] = reader.getFloat32(vertexstart + 4, true); positions[offset + 1] = reader.getFloat32(vertexstart + 8, true); normals[offset] = normalX; normals[offset + 2] = normalY; normals[offset + 1] = normalZ; offset += 3; } indices[indicesCount] = indicesCount++; indices[indicesCount] = indicesCount++; indices[indicesCount] = indicesCount++; } mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions); mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals); mesh.setIndices(indices); mesh.computeWorldMatrix(true); }; STLFileLoader.prototype.parseASCII = function (mesh, solidData) { var positions = []; var normals = []; var indices = []; var indicesCount = 0; //load facets, ignoring loop as the standard doesn't define it can contain more than vertices var matches; while (matches = this.facetsPattern.exec(solidData)) { var facet = matches[1]; //one normal per face var normalMatches = this.normalPattern.exec(facet); this.normalPattern.lastIndex = 0; if (!normalMatches) { continue; } var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])]; var vertexMatch; while (vertexMatch = this.vertexPattern.exec(facet)) { positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3])); normals.push(normal[0], normal[1], normal[2]); } indices.push(indicesCount++, indicesCount++, indicesCount++); this.vertexPattern.lastIndex = 0; } this.facetsPattern.lastIndex = 0; mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions); mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals); mesh.setIndices(indices); mesh.computeWorldMatrix(true); }; return STLFileLoader; }()); BABYLON.STLFileLoader = STLFileLoader; if (BABYLON.SceneLoader) { BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader()); } })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.stlFileLoader.js.map var BABYLON; (function (BABYLON) { /** * Class reading and parsing the MTL file bundled with the obj file. */ var MTLFileLoader = /** @class */ (function () { function MTLFileLoader() { // All material loaded from the mtl will be set here this.materials = []; } /** * This function will read the mtl file and create each material described inside * This function could be improve by adding : * -some component missing (Ni, Tf...) * -including the specific options available * * @param scene * @param data * @param rootUrl */ MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) { if (data instanceof ArrayBuffer) { return; } //Split the lines from the file var lines = data.split('\n'); //Space char var delimiter_pattern = /\s+/; //Array with RGB colors var color; //New material var material = null; //Look at each line for (var i = 0; i < lines.length; i++) { var line = lines[i].trim(); // Blank line or comment if (line.length === 0 || line.charAt(0) === '#') { continue; } //Get the first parameter (keyword) var pos = line.indexOf(' '); var key = (pos >= 0) ? line.substring(0, pos) : line; key = key.toLowerCase(); //Get the data following the key var value = (pos >= 0) ? line.substring(pos + 1).trim() : ""; //This mtl keyword will create the new material if (key === "newmtl") { //Check if it is the first material. // Materials specifications are described after this keyword. if (material) { //Add the previous material in the material array. this.materials.push(material); } //Create a new material. // value is the name of the material read in the mtl file material = new BABYLON.StandardMaterial(value, scene); } else if (key === "kd" && material) { // Diffuse color (color under white light) using RGB values //value = "r g b" color = value.split(delimiter_pattern, 3).map(parseFloat); //color = [r,g,b] //Set tghe color into the material material.diffuseColor = BABYLON.Color3.FromArray(color); } else if (key === "ka" && material) { // Ambient color (color under shadow) using RGB values //value = "r g b" color = value.split(delimiter_pattern, 3).map(parseFloat); //color = [r,g,b] //Set tghe color into the material material.ambientColor = BABYLON.Color3.FromArray(color); } else if (key === "ks" && material) { // Specular color (color when light is reflected from shiny surface) using RGB values //value = "r g b" color = value.split(delimiter_pattern, 3).map(parseFloat); //color = [r,g,b] //Set the color into the material material.specularColor = BABYLON.Color3.FromArray(color); } else if (key === "ke" && material) { // Emissive color using RGB values color = value.split(delimiter_pattern, 3).map(parseFloat); material.emissiveColor = BABYLON.Color3.FromArray(color); } else if (key === "ns" && material) { //value = "Integer" material.specularPower = parseFloat(value); } else if (key === "d" && material) { //d is dissolve for current material. It mean alpha for BABYLON material.alpha = parseFloat(value); //Texture //This part can be improved by adding the possible options of texture } else if (key === "map_ka" && material) { // ambient texture map with a loaded image //We must first get the folder of the image material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene); } else if (key === "map_kd" && material) { // Diffuse texture map with a loaded image material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene); } else if (key === "map_ks" && material) { // Specular texture map with a loaded image //We must first get the folder of the image material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene); } else if (key === "map_ns") { //Specular //Specular highlight component //We must first get the folder of the image // //Not supported by BABYLON // // continue; } else if (key === "map_bump" && material) { //The bump texture material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene); } else if (key === "map_d" && material) { // The dissolve of the material material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene); //Options for illumination } else if (key === "illum") { //Illumination if (value === "0") { //That mean Kd == Kd } else if (value === "1") { //Color on and Ambient on } else if (value === "2") { //Highlight on } else if (value === "3") { //Reflection on and Ray trace on } else if (value === "4") { //Transparency: Glass on, Reflection: Ray trace on } else if (value === "5") { //Reflection: Fresnel on and Ray trace on } else if (value === "6") { //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on } else if (value === "7") { //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on } else if (value === "8") { //Reflection on and Ray trace off } else if (value === "9") { //Transparency: Glass on, Reflection: Ray trace off } else if (value === "10") { //Casts shadows onto invisible surfaces } } else { // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line); } } //At the end of the file, add the last material if (material) { this.materials.push(material); } }; /** * Gets the texture for the material. * * If the material is imported from input file, * We sanitize the url to ensure it takes the textre from aside the material. * * @param rootUrl The root url to load from * @param value The value stored in the mtl * @return The Texture */ MTLFileLoader._getTexture = function (rootUrl, value, scene) { if (!value) { return null; } var url = rootUrl; // Load from input file. if (rootUrl === "file:") { var lastDelimiter = value.lastIndexOf("\\"); if (lastDelimiter === -1) { lastDelimiter = value.lastIndexOf("/"); } if (lastDelimiter > -1) { url += value.substr(lastDelimiter + 1); } else { url += value; } } // Not from input file. else { url += value; } return new BABYLON.Texture(url, scene); }; return MTLFileLoader; }()); BABYLON.MTLFileLoader = MTLFileLoader; var OBJFileLoader = /** @class */ (function () { function OBJFileLoader() { this.name = "obj"; this.extensions = ".obj"; this.obj = /^o/; this.group = /^g/; this.mtllib = /^mtllib /; this.usemtl = /^usemtl /; this.smooth = /^s /; this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/; // vn float float float this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/; // vt float float this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/; // f vertex vertex vertex ... this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/; // f vertex/uvs vertex/uvs vertex/uvs ... this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/; // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ... this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/; // f vertex//normal vertex//normal vertex//normal ... this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/; } /** * Calls synchronously the MTL file attached to this obj. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously. * Without this function materials are not displayed in the first frame (but displayed after). * In consequence it is impossible to get material information in your HTML file * * @param url The URL of the MTL file * @param rootUrl * @param onSuccess Callback function to be called when the MTL file is loaded * @private */ OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) { //The complete path to the mtl file var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url; // Loads through the babylon tools to allow fileInput search. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); }); }; OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) { //get the meshes from OBJ file var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl); //Push meshes from OBJ file into the variable mesh of this function if (meshes) { loadedMeshes.forEach(function (mesh) { meshes.push(mesh); }); } return true; }; OBJFileLoader.prototype.load = function (scene, data, rootUrl) { //Get the 3D model return this.importMesh(null, scene, data, rootUrl, null, null, null); }; OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) { var container = new BABYLON.AssetContainer(scene); this.importMesh(null, scene, data, rootUrl, container.meshes, null, null); container.removeAllFromScene(); return container; }; /** * Read the OBJ file and create an Array of meshes. * Each mesh contains all information given by the OBJ and the MTL file. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material * * @param meshesNames * @param scene BABYLON.Scene The scene where are displayed the data * @param data String The content of the obj file * @param rootUrl String The path to the folder * @returns Array * @private */ OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) { var positions = []; //values for the positions of vertices var normals = []; //Values for the normals var uvs = []; //Values for the textures var meshesFromObj = []; //[mesh] Contains all the obj meshes var handledMesh; //The current mesh of meshes array var indicesForBabylon = []; //The list of indices for VertexData var wrappedPositionForBabylon = []; //The list of position in vectors var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs] var curPositionInIndices = 0; var hasMeshes = false; //Meshes are defined in the file var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z] var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z] var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z] var triangles = []; //Indices from new triangles coming from polygons var materialNameFromObj = ""; //The name of the current material var fileToLoad = ""; //The name of the mtlFile to load var materialsFromMTLFile = new MTLFileLoader(); var objMeshName = ""; //The name of the current obj mesh var increment = 1; //Id for meshes created by the multimaterial var isFirstMaterial = true; /** * Search for obj in the given array. * This function is called to check if a couple of data already exists in an array. * * If found, returns the index of the founded tuple index. Returns -1 if not found * @param arr Array<{ normals: Array, idx: Array }> * @param obj Array * @returns {boolean} */ var isInArray = function (arr, obj) { if (!arr[obj[0]]) arr[obj[0]] = { normals: [], idx: [] }; var idx = arr[obj[0]].normals.indexOf(obj[1]); return idx === -1 ? -1 : arr[obj[0]].idx[idx]; }; var isInArrayUV = function (arr, obj) { if (!arr[obj[0]]) arr[obj[0]] = { normals: [], idx: [], uv: [] }; var idx = arr[obj[0]].normals.indexOf(obj[1]); if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) { return arr[obj[0]].idx[idx]; } return -1; }; /** * This function set the data for each triangle. * Data are position, normals and uvs * If a tuple of (position, normal) is not set, add the data into the corresponding array * If the tuple already exist, add only their indice * * @param indicePositionFromObj Integer The index in positions array * @param indiceUvsFromObj Integer The index in uvs array * @param indiceNormalFromObj Integer The index in normals array * @param positionVectorFromOBJ Vector3 The value of position at index objIndice * @param textureVectorFromOBJ Vector3 The value of uvs * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale */ var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) { //Check if this tuple already exists in the list of tuples var _index; if (OBJFileLoader.OPTIMIZE_WITH_UV) { _index = isInArrayUV(tuplePosNorm, [ indicePositionFromObj, indiceNormalFromObj, indiceUvsFromObj ]); } else { _index = isInArray(tuplePosNorm, [ indicePositionFromObj, indiceNormalFromObj ]); } //If it not exists if (_index == -1) { //Add an new indice. //The array of indices is only an array with his length equal to the number of triangles - 1. //We add vertices data in this order indicesForBabylon.push(wrappedPositionForBabylon.length); //Push the position of vertice for Babylon //Each element is a BABYLON.Vector3(x,y,z) wrappedPositionForBabylon.push(positionVectorFromOBJ); //Push the uvs for Babylon //Each element is a BABYLON.Vector3(u,v) wrappedUvsForBabylon.push(textureVectorFromOBJ); //Push the normals for Babylon //Each element is a BABYLON.Vector3(x,y,z) wrappedNormalsForBabylon.push(normalsVectorFromOBJ); //Add the tuple in the comparison list tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj); tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++); if (OBJFileLoader.OPTIMIZE_WITH_UV) tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj); } else { //The tuple already exists //Add the index of the already existing tuple //At this index we can get the value of position, normal and uvs of vertex indicesForBabylon.push(_index); } }; /** * Transform BABYLON.Vector() object onto 3 digits in an array */ var unwrapData = function () { //Every array has the same length for (var l = 0; l < wrappedPositionForBabylon.length; l++) { //Push the x, y, z values of each element in the unwrapped array unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z); unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z); unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON } // Reset arrays for the next new meshes wrappedPositionForBabylon = []; wrappedNormalsForBabylon = []; wrappedUvsForBabylon = []; tuplePosNorm = []; curPositionInIndices = 0; }; /** * Create triangles from polygons by recursion * The best to understand how it works is to draw it in the same time you get the recursion. * It is important to notice that a triangle is a polygon * We get 4 patterns of face defined in OBJ File : * facePattern1 = ["1","2","3","4","5","6"] * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"] * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"] * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"] * Each pattern is divided by the same method * @param face Array[String] The indices of elements * @param v Integer The variable to increment */ var getTriangles = function (face, v) { //Work for each element of the array if (v + 1 < face.length) { //Add on the triangle variable the indexes to obtain triangles triangles.push(face[0], face[v], face[v + 1]); //Incrementation for recursion v += 1; //Recursion getTriangles(face, v); } //Result obtained after 2 iterations: //Pattern1 => triangle = ["1","2","3","1","3","4"]; //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"]; //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"]; //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"]; }; /** * Create triangles and push the data for each polygon for the pattern 1 * In this pattern we get vertice positions * @param face * @param v */ var setDataForCurrentFaceWithPattern1 = function (face, v) { //Get the indices of triangles for each polygon getTriangles(face, v); //For each element in the triangles array. //This var could contains 1 to an infinity of triangles for (var k = 0; k < triangles.length; k++) { // Set position indice var indicePositionFromObj = parseInt(triangles[k]) - 1; setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined positions[indicePositionFromObj], //Get the vectors data BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors ); } //Reset variable for the next line triangles = []; }; /** * Create triangles and push the data for each polygon for the pattern 2 * In this pattern we get vertice positions and uvsu * @param face * @param v */ var setDataForCurrentFaceWithPattern2 = function (face, v) { //Get the indices of triangles for each polygon getTriangles(face, v); for (var k = 0; k < triangles.length; k++) { //triangle[k] = "1/1" //Split the data for getting position and uv var point = triangles[k].split("/"); // ["1", "1"] //Set position indice var indicePositionFromObj = parseInt(point[0]) - 1; //Set uv indice var indiceUvsFromObj = parseInt(point[1]) - 1; setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals positions[indicePositionFromObj], //Get the values for each element uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals ); } //Reset variable for the next line triangles = []; }; /** * Create triangles and push the data for each polygon for the pattern 3 * In this pattern we get vertice positions, uvs and normals * @param face * @param v */ var setDataForCurrentFaceWithPattern3 = function (face, v) { //Get the indices of triangles for each polygon getTriangles(face, v); for (var k = 0; k < triangles.length; k++) { //triangle[k] = "1/1/1" //Split the data for getting position, uv, and normals var point = triangles[k].split("/"); // ["1", "1", "1"] // Set position indice var indicePositionFromObj = parseInt(point[0]) - 1; // Set uv indice var indiceUvsFromObj = parseInt(point[1]) - 1; // Set normal indice var indiceNormalFromObj = parseInt(point[2]) - 1; setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component ); } //Reset variable for the next line triangles = []; }; /** * Create triangles and push the data for each polygon for the pattern 4 * In this pattern we get vertice positions and normals * @param face * @param v */ var setDataForCurrentFaceWithPattern4 = function (face, v) { getTriangles(face, v); for (var k = 0; k < triangles.length; k++) { //triangle[k] = "1//1" //Split the data for getting position and normals var point = triangles[k].split("//"); // ["1", "1"] // We check indices, and normals var indicePositionFromObj = parseInt(point[0]) - 1; var indiceNormalFromObj = parseInt(point[1]) - 1; setData(indicePositionFromObj, 1, //Default value for uv indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]); } //Reset variable for the next line triangles = []; }; var addPreviousObjMesh = function () { //Check if it is not the first mesh. Otherwise we don't have data. if (meshesFromObj.length > 0) { //Get the previous mesh for applying the data about the faces //=> in obj file, faces definition append after the name of the mesh handledMesh = meshesFromObj[meshesFromObj.length - 1]; //Set the data into Array for the mesh unwrapData(); // Reverse tab. Otherwise face are displayed in the wrong sens indicesForBabylon.reverse(); //Set the information for the mesh //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited handledMesh.indices = indicesForBabylon.slice(); handledMesh.positions = unwrappedPositionsForBabylon.slice(); handledMesh.normals = unwrappedNormalsForBabylon.slice(); handledMesh.uvs = unwrappedUVForBabylon.slice(); //Reset the array for the next mesh indicesForBabylon = []; unwrappedPositionsForBabylon = []; unwrappedNormalsForBabylon = []; unwrappedUVForBabylon = []; } }; //Main function //Split the file into lines var lines = data.split('\n'); //Look at each line for (var i = 0; i < lines.length; i++) { var line = lines[i].trim(); var result; //Comment or newLine if (line.length === 0 || line.charAt(0) === '#') { continue; //Get information about one position possible for the vertices } else if ((result = this.vertexPattern.exec(line)) !== null) { //Create a Vector3 with the position x, y, z //Value of result: // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"] //Add the Vector in the list of positions positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3]))); } else if ((result = this.normalPattern.exec(line)) !== null) { //Create a Vector3 with the normals x, y, z //Value of result // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"] //Add the Vector in the list of normals normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3]))); } else if ((result = this.uvPattern.exec(line)) !== null) { //Create a Vector2 with the normals u, v //Value of result // ["vt 0.1 0.2 0.3", "0.1", "0.2"] //Add the Vector in the list of uvs uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2]))); //Identify patterns of faces //Face could be defined in different type of pattern } else if ((result = this.facePattern3.exec(line)) !== null) { //Value of result: //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...] //Set the data for this face setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"] 1); } else if ((result = this.facePattern4.exec(line)) !== null) { //Value of result: //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...] //Set the data for this face setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"] 1); } else if ((result = this.facePattern2.exec(line)) !== null) { //Value of result: //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...] //Set the data for this face setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"] 1); } else if ((result = this.facePattern1.exec(line)) !== null) { //Value of result //["f 1 2 3", "1 2 3"...] //Set the data for this face setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"] 1); //Define a mesh or an object //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh } else if (this.group.test(line) || this.obj.test(line)) { //Create a new mesh corresponding to the name of the group. //Definition of the mesh var objMesh = //Set the name of the current obj mesh { name: line.substring(2).trim(), indices: undefined, positions: undefined, normals: undefined, uvs: undefined, materialName: "" }; addPreviousObjMesh(); //Push the last mesh created with only the name meshesFromObj.push(objMesh); //Set this variable to indicate that now meshesFromObj has objects defined inside hasMeshes = true; isFirstMaterial = true; increment = 1; //Keyword for applying a material } else if (this.usemtl.test(line)) { //Get the name of the material materialNameFromObj = line.substring(7).trim(); //If this new material is in the same mesh if (!isFirstMaterial) { //Set the data for the previous mesh addPreviousObjMesh(); //Create a new mesh var objMesh = //Set the name of the current obj mesh { name: objMeshName + "_mm" + increment.toString(), indices: undefined, positions: undefined, normals: undefined, uvs: undefined, materialName: materialNameFromObj }; increment++; //If meshes are already defined meshesFromObj.push(objMesh); } //Set the material name if the previous line define a mesh if (hasMeshes && isFirstMaterial) { //Set the material name to the previous mesh (1 material per mesh) meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj; isFirstMaterial = false; } //Keyword for loading the mtl file } else if (this.mtllib.test(line)) { //Get the name of mtl file fileToLoad = line.substring(7).trim(); //Apply smoothing } else if (this.smooth.test(line)) { // smooth shading => apply smoothing //Toda y I don't know it work with babylon and with obj. //With the obj file an integer is set } else { //If there is another possibility console.log("Unhandled expression at line : " + line); } } //At the end of the file, add the last mesh into the meshesFromObj array if (hasMeshes) { //Set the data for the last mesh handledMesh = meshesFromObj[meshesFromObj.length - 1]; //Reverse indices for displaying faces in the good sens indicesForBabylon.reverse(); //Get the good array unwrapData(); //Set array handledMesh.indices = indicesForBabylon; handledMesh.positions = unwrappedPositionsForBabylon; handledMesh.normals = unwrappedNormalsForBabylon; handledMesh.uvs = unwrappedUVForBabylon; } //If any o or g keyword found, create a mesj with a random id if (!hasMeshes) { // reverse tab of indices indicesForBabylon.reverse(); //Get positions normals uvs unwrapData(); //Set data for one mesh meshesFromObj.push({ name: BABYLON.Geometry.RandomId(), indices: indicesForBabylon, positions: unwrappedPositionsForBabylon, normals: unwrappedNormalsForBabylon, uvs: unwrappedUVForBabylon, materialName: materialNameFromObj }); } //Create a BABYLON.Mesh list var babylonMeshesArray = []; //The mesh for babylon var materialToUse = new Array(); //Set data for each mesh for (var j = 0; j < meshesFromObj.length; j++) { //check meshesNames (stlFileLoader) if (meshesNames && meshesFromObj[j].name) { if (meshesNames instanceof Array) { if (meshesNames.indexOf(meshesFromObj[j].name) == -1) { continue; } } else { if (meshesFromObj[j].name !== meshesNames) { continue; } } } //Get the current mesh //Set the data with VertexBuffer for each mesh handledMesh = meshesFromObj[j]; //Create a BABYLON.Mesh with the name of the obj mesh var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene); //Push the name of the material to an array //This is indispensable for the importMesh function materialToUse.push(meshesFromObj[j].materialName); var vertexData = new BABYLON.VertexData(); //The container for the values //Set the data for the babylonMesh vertexData.positions = handledMesh.positions; vertexData.normals = handledMesh.normals; vertexData.uvs = handledMesh.uvs; vertexData.indices = handledMesh.indices; //Set the data from the VertexBuffer to the current BABYLON.Mesh vertexData.applyToMesh(babylonMesh); if (OBJFileLoader.INVERT_Y) { babylonMesh.scaling.y *= -1; } //Push the mesh into an array babylonMeshesArray.push(babylonMesh); } //load the materials //Check if we have a file to load if (fileToLoad !== "") { //Load the file synchronously this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) { //Create materials thanks MTLLoader function materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl); //Look at each material loaded in the mtl file for (var n = 0; n < materialsFromMTLFile.materials.length; n++) { //Three variables to get all meshes with the same material var startIndex = 0; var _indices = []; var _index; //The material from MTL file is used in the meshes loaded //Push the indice in an array //Check if the material is not used for another mesh while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) { _indices.push(_index); startIndex = _index + 1; } //If the material is not used dispose it if (_index == -1 && _indices.length == 0) { //If the material is not needed, remove it materialsFromMTLFile.materials[n].dispose(); } else { for (var o = 0; o < _indices.length; o++) { //Apply the material to the BABYLON.Mesh for each mesh with the material babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n]; } } } }); } //Return an array with all BABYLON.Mesh return babylonMeshesArray; }; OBJFileLoader.OPTIMIZE_WITH_UV = false; OBJFileLoader.INVERT_Y = false; return OBJFileLoader; }()); BABYLON.OBJFileLoader = OBJFileLoader; if (BABYLON.SceneLoader) { //Add this loader into the register plugin BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader()); } })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.objFileLoader.js.map var BABYLON; (function (BABYLON) { /** * Mode that determines the coordinate system to use. */ var GLTFLoaderCoordinateSystemMode; (function (GLTFLoaderCoordinateSystemMode) { /** * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene. */ GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO"; /** * Sets the useRightHandedSystem flag on the scene. */ GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED"; })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {})); /** * Mode that determines what animations will start. */ var GLTFLoaderAnimationStartMode; (function (GLTFLoaderAnimationStartMode) { /** * No animation will start. */ GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE"; /** * The first animation will start. */ GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST"; /** * All animations will start. */ GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL"; })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {})); /** * Loader state. */ var GLTFLoaderState; (function (GLTFLoaderState) { /** * The asset is loading. */ GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING"; /** * The asset is ready for rendering. */ GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY"; /** * The asset is completely loaded. */ GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE"; })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {})); /** * File loader for loading glTF files into a scene. */ var GLTFFileLoader = /** @class */ (function () { function GLTFFileLoader() { // #region Common options /** * Raised when the asset has been parsed */ this.onParsedObservable = new BABYLON.Observable(); // #endregion // #region V2 options /** * The coordinate system mode. Defaults to AUTO. */ this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO; /** * The animation start mode. Defaults to FIRST. */ this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST; /** * Defines if the loader should compile materials before raising the success callback. Defaults to false. */ this.compileMaterials = false; /** * Defines if the loader should also compile materials with clip planes. Defaults to false. */ this.useClipPlane = false; /** * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false. */ this.compileShadowGenerators = false; /** * Defines if the Alpha blended materials are only applied as coverage. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials. * If true, no extra effects are applied to transparent pixels. */ this.transparencyAsCoverage = false; /** @hidden */ this._normalizeAnimationGroupsToBeginAtZero = true; /** * Function called before loading a url referenced by the asset. */ this.preprocessUrlAsync = function (url) { return Promise.resolve(url); }; /** * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh. */ this.onMeshLoadedObservable = new BABYLON.Observable(); /** * Observable raised when the loader creates a texture after parsing the glTF properties of the texture. */ this.onTextureLoadedObservable = new BABYLON.Observable(); /** * Observable raised when the loader creates a material after parsing the glTF properties of the material. */ this.onMaterialLoadedObservable = new BABYLON.Observable(); /** * Observable raised when the loader creates a camera after parsing the glTF properties of the camera. */ this.onCameraLoadedObservable = new BABYLON.Observable(); /** * Observable raised when the asset is completely loaded, immediately before the loader is disposed. * For assets with LODs, raised when all of the LODs are complete. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise. */ this.onCompleteObservable = new BABYLON.Observable(); /** * Observable raised after the loader is disposed. */ this.onDisposeObservable = new BABYLON.Observable(); /** * Observable raised after a loader extension is created. * Set additional options for a loader extension in this event. */ this.onExtensionLoadedObservable = new BABYLON.Observable(); // #endregion this._loader = null; /** * Name of the loader ("gltf") */ this.name = "gltf"; /** * Supported file extensions of the loader (.gltf, .glb) */ this.extensions = { ".gltf": { isBinary: false }, ".glb": { isBinary: true } }; } Object.defineProperty(GLTFFileLoader.prototype, "onParsed", { /** * Raised when the asset has been parsed */ set: function (callback) { if (this._onParsedObserver) { this.onParsedObservable.remove(this._onParsedObserver); } this._onParsedObserver = this.onParsedObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", { /** * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh. */ set: function (callback) { if (this._onMeshLoadedObserver) { this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver); } this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", { /** * Callback raised when the loader creates a texture after parsing the glTF properties of the texture. */ set: function (callback) { if (this._onTextureLoadedObserver) { this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver); } this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", { /** * Callback raised when the loader creates a material after parsing the glTF properties of the material. */ set: function (callback) { if (this._onMaterialLoadedObserver) { this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver); } this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", { /** * Callback raised when the loader creates a camera after parsing the glTF properties of the camera. */ set: function (callback) { if (this._onCameraLoadedObserver) { this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver); } this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(GLTFFileLoader.prototype, "onComplete", { /** * Callback raised when the asset is completely loaded, immediately before the loader is disposed. */ set: function (callback) { if (this._onCompleteObserver) { this.onCompleteObservable.remove(this._onCompleteObserver); } this._onCompleteObserver = this.onCompleteObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(GLTFFileLoader.prototype, "onDispose", { /** * Callback raised after the loader is disposed. */ set: function (callback) { if (this._onDisposeObserver) { this.onDisposeObservable.remove(this._onDisposeObserver); } this._onDisposeObserver = this.onDisposeObservable.add(callback); }, enumerable: true, configurable: true }); Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", { /** * Callback raised after a loader extension is created. */ set: function (callback) { if (this._onExtensionLoadedObserver) { this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver); } this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback); }, enumerable: true, configurable: true }); /** * Returns a promise that resolves when the asset is completely loaded. * @returns a promise that resolves when the asset is completely loaded. */ GLTFFileLoader.prototype.whenCompleteAsync = function () { var _this = this; return new Promise(function (resolve) { _this.onCompleteObservable.addOnce(function () { resolve(); }); }); }; Object.defineProperty(GLTFFileLoader.prototype, "loaderState", { /** * The loader state or null if the loader is not active. */ get: function () { return this._loader ? this._loader.state : null; }, enumerable: true, configurable: true }); /** * Disposes the loader, releases resources during load, and cancels any outstanding requests. */ GLTFFileLoader.prototype.dispose = function () { if (this._loader) { this._loader.dispose(); this._loader = null; } this.preprocessUrlAsync = function (url) { return Promise.resolve(url); }; this.onMeshLoadedObservable.clear(); this.onTextureLoadedObservable.clear(); this.onMaterialLoadedObservable.clear(); this.onCameraLoadedObservable.clear(); this.onCompleteObservable.clear(); this.onExtensionLoadedObservable.clear(); this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); }; /** * Imports one or more meshes from the loaded glTF data and adds them to the scene * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file * @param scene the scene the meshes should be added to * @param data the glTF data to load * @param rootUrl root url to load from * @param onProgress event that fires when loading progress has occured * @returns a promise containg the loaded meshes, particles, skeletons and animations */ GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) { var _this = this; return Promise.resolve().then(function () { var loaderData = _this._parse(data); _this._loader = _this._getLoader(loaderData); return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress); }); }; /** * Imports all objects from the loaded glTF data and adds them to the scene * @param scene the scene the objects should be added to * @param data the glTF data to load * @param rootUrl root url to load from * @param onProgress event that fires when loading progress has occured * @returns a promise which completes when objects have been loaded to the scene */ GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) { var _this = this; return Promise.resolve().then(function () { var loaderData = _this._parse(data); _this._loader = _this._getLoader(loaderData); return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress); }); }; /** * Load into an asset container. * @param scene The scene to load into * @param data The data to import * @param rootUrl The root url for scene and resources * @param onProgress The callback when the load progresses * @returns The loaded asset container */ GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) { var _this = this; return Promise.resolve().then(function () { var loaderData = _this._parse(data); _this._loader = _this._getLoader(loaderData); return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) { var container = new BABYLON.AssetContainer(scene); Array.prototype.push.apply(container.meshes, result.meshes); Array.prototype.push.apply(container.particleSystems, result.particleSystems); Array.prototype.push.apply(container.skeletons, result.skeletons); Array.prototype.push.apply(container.animationGroups, result.animationGroups); container.removeAllFromScene(); return container; }); }); }; /** * If the data string can be loaded directly. * @param data string contianing the file data * @returns if the data can be loaded directly */ GLTFFileLoader.prototype.canDirectLoad = function (data) { return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1)); }; /** * Instantiates a glTF file loader plugin. * @returns the created plugin */ GLTFFileLoader.prototype.createPlugin = function () { return new GLTFFileLoader(); }; GLTFFileLoader.prototype._parse = function (data) { var parsedData; if (data instanceof ArrayBuffer) { parsedData = GLTFFileLoader._parseBinary(data); } else { parsedData = { json: JSON.parse(data), bin: null }; } this.onParsedObservable.notifyObservers(parsedData); this.onParsedObservable.clear(); return parsedData; }; GLTFFileLoader.prototype._getLoader = function (loaderData) { var _this = this; var loaderVersion = { major: 2, minor: 0 }; var asset = loaderData.json.asset || {}; var version = GLTFFileLoader._parseVersion(asset.version); if (!version) { throw new Error("Invalid version: " + asset.version); } if (asset.minVersion !== undefined) { var minVersion = GLTFFileLoader._parseVersion(asset.minVersion); if (!minVersion) { throw new Error("Invalid minimum version: " + asset.minVersion); } if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) { throw new Error("Incompatible minimum version: " + asset.minVersion); } } var createLoaders = { 1: GLTFFileLoader._CreateGLTFLoaderV1, 2: GLTFFileLoader._CreateGLTFLoaderV2 }; var createLoader = createLoaders[version.major]; if (!createLoader) { throw new Error("Unsupported version: " + asset.version); } var loader = createLoader(); loader.coordinateSystemMode = this.coordinateSystemMode; loader.animationStartMode = this.animationStartMode; loader.compileMaterials = this.compileMaterials; loader.useClipPlane = this.useClipPlane; loader.compileShadowGenerators = this.compileShadowGenerators; loader.transparencyAsCoverage = this.transparencyAsCoverage; loader._normalizeAnimationGroupsToBeginAtZero = this._normalizeAnimationGroupsToBeginAtZero; loader.preprocessUrlAsync = this.preprocessUrlAsync; loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); }); loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); }); loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); }); loader.onCameraLoadedObservable.add(function (camera) { return _this.onCameraLoadedObservable.notifyObservers(camera); }); loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); }); loader.onCompleteObservable.add(function () { _this.onMeshLoadedObservable.clear(); _this.onTextureLoadedObservable.clear(); _this.onMaterialLoadedObservable.clear(); _this.onCameraLoadedObservable.clear(); _this.onExtensionLoadedObservable.clear(); _this.onCompleteObservable.notifyObservers(_this); _this.onCompleteObservable.clear(); }); return loader; }; GLTFFileLoader._parseBinary = function (data) { var Binary = { Magic: 0x46546C67 }; var binaryReader = new BinaryReader(data); var magic = binaryReader.readUint32(); if (magic !== Binary.Magic) { throw new Error("Unexpected magic: " + magic); } var version = binaryReader.readUint32(); switch (version) { case 1: return GLTFFileLoader._parseV1(binaryReader); case 2: return GLTFFileLoader._parseV2(binaryReader); } throw new Error("Unsupported version: " + version); }; GLTFFileLoader._parseV1 = function (binaryReader) { var ContentFormat = { JSON: 0 }; var length = binaryReader.readUint32(); if (length != binaryReader.getLength()) { throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength()); } var contentLength = binaryReader.readUint32(); var contentFormat = binaryReader.readUint32(); var content; switch (contentFormat) { case ContentFormat.JSON: { content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength))); break; } default: { throw new Error("Unexpected content format: " + contentFormat); } } var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition(); var body = binaryReader.readUint8Array(bytesRemaining); return { json: content, bin: body }; }; GLTFFileLoader._parseV2 = function (binaryReader) { var ChunkFormat = { JSON: 0x4E4F534A, BIN: 0x004E4942 }; var length = binaryReader.readUint32(); if (length !== binaryReader.getLength()) { throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength()); } // JSON chunk var chunkLength = binaryReader.readUint32(); var chunkFormat = binaryReader.readUint32(); if (chunkFormat !== ChunkFormat.JSON) { throw new Error("First chunk format is not JSON"); } var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength))); // Look for BIN chunk var bin = null; while (binaryReader.getPosition() < binaryReader.getLength()) { var chunkLength_1 = binaryReader.readUint32(); var chunkFormat_1 = binaryReader.readUint32(); switch (chunkFormat_1) { case ChunkFormat.JSON: { throw new Error("Unexpected JSON chunk"); } case ChunkFormat.BIN: { bin = binaryReader.readUint8Array(chunkLength_1); break; } default: { // ignore unrecognized chunkFormat binaryReader.skipBytes(chunkLength_1); break; } } } return { json: json, bin: bin }; }; GLTFFileLoader._parseVersion = function (version) { if (version === "1.0" || version === "1.0.1") { return { major: 1, minor: 0 }; } var match = (version + "").match(/^(\d+)\.(\d+)/); if (!match) { return null; } return { major: parseInt(match[1]), minor: parseInt(match[2]) }; }; GLTFFileLoader._compareVersion = function (a, b) { if (a.major > b.major) return 1; if (a.major < b.major) return -1; if (a.minor > b.minor) return 1; if (a.minor < b.minor) return -1; return 0; }; GLTFFileLoader._decodeBufferToText = function (buffer) { var result = ""; var length = buffer.byteLength; for (var i = 0; i < length; i++) { result += String.fromCharCode(buffer[i]); } return result; }; // #endregion // #region V1 options /** * Set this property to false to disable incremental loading which delays the loader from calling the success callback until after loading the meshes and shaders. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled. * Defaults to true. * @hidden */ GLTFFileLoader.IncrementalLoading = true; /** * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates. * @hidden */ GLTFFileLoader.HomogeneousCoordinates = false; return GLTFFileLoader; }()); BABYLON.GLTFFileLoader = GLTFFileLoader; var BinaryReader = /** @class */ (function () { function BinaryReader(arrayBuffer) { this._arrayBuffer = arrayBuffer; this._dataView = new DataView(arrayBuffer); this._byteOffset = 0; } BinaryReader.prototype.getPosition = function () { return this._byteOffset; }; BinaryReader.prototype.getLength = function () { return this._arrayBuffer.byteLength; }; BinaryReader.prototype.readUint32 = function () { var value = this._dataView.getUint32(this._byteOffset, true); this._byteOffset += 4; return value; }; BinaryReader.prototype.readUint8Array = function (length) { var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length); this._byteOffset += length; return value; }; BinaryReader.prototype.skipBytes = function (length) { this._byteOffset += length; }; return BinaryReader; }()); if (BABYLON.SceneLoader) { BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader()); } })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.glTFFileLoader.js.map var BABYLON; (function (BABYLON) { var GLTF1; (function (GLTF1) { /** * Enums */ var EComponentType; (function (EComponentType) { EComponentType[EComponentType["BYTE"] = 5120] = "BYTE"; EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; EComponentType[EComponentType["SHORT"] = 5122] = "SHORT"; EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT"; })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {})); var EShaderType; (function (EShaderType) { EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT"; EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX"; })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {})); var EParameterType; (function (EParameterType) { EParameterType[EParameterType["BYTE"] = 5120] = "BYTE"; EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; EParameterType[EParameterType["SHORT"] = 5122] = "SHORT"; EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; EParameterType[EParameterType["INT"] = 5124] = "INT"; EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT"; EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT"; EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2"; EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3"; EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4"; EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2"; EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3"; EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4"; EParameterType[EParameterType["BOOL"] = 35670] = "BOOL"; EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2"; EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3"; EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4"; EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2"; EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3"; EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4"; EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D"; })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {})); var ETextureWrapMode; (function (ETextureWrapMode) { ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE"; ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT"; })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {})); var ETextureFilterType; (function (ETextureFilterType) { ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST"; ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR"; ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST"; ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST"; ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR"; ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR"; })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {})); var ETextureFormat; (function (ETextureFormat) { ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA"; ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB"; ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA"; ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE"; ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {})); var ECullingType; (function (ECullingType) { ECullingType[ECullingType["FRONT"] = 1028] = "FRONT"; ECullingType[ECullingType["BACK"] = 1029] = "BACK"; ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK"; })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {})); var EBlendingFunction; (function (EBlendingFunction) { EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO"; EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE"; EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR"; EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR"; EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR"; EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR"; EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA"; EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA"; EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA"; EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA"; EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR"; EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR"; EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA"; EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA"; EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE"; })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {})); })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map var BABYLON; (function (BABYLON) { var GLTF1; (function (GLTF1) { /** * Tokenizer. Used for shaders compatibility * Automatically map world, view, projection, worldViewProjection, attributes and so on */ var ETokenType; (function (ETokenType) { ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER"; ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN"; ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT"; })(ETokenType || (ETokenType = {})); var Tokenizer = /** @class */ (function () { function Tokenizer(toParse) { this._pos = 0; this.currentToken = ETokenType.UNKNOWN; this.currentIdentifier = ""; this.currentString = ""; this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/; this._toParse = toParse; this._maxPos = toParse.length; } Tokenizer.prototype.getNextToken = function () { if (this.isEnd()) return ETokenType.END_OF_INPUT; this.currentString = this.read(); this.currentToken = ETokenType.UNKNOWN; if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) { this.currentToken = ETokenType.IDENTIFIER; this.currentIdentifier = this.currentString; while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) { this.currentIdentifier += this.currentString; this.forward(); } } return this.currentToken; }; Tokenizer.prototype.peek = function () { return this._toParse[this._pos]; }; Tokenizer.prototype.read = function () { return this._toParse[this._pos++]; }; Tokenizer.prototype.forward = function () { this._pos++; }; Tokenizer.prototype.isEnd = function () { return this._pos >= this._maxPos; }; return Tokenizer; }()); /** * Values */ var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"]; var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"]; var glTFAnimationPaths = ["translation", "rotation", "scale"]; var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"]; /** * Parse */ var parseBuffers = function (parsedBuffers, gltfRuntime) { for (var buf in parsedBuffers) { var parsedBuffer = parsedBuffers[buf]; gltfRuntime.buffers[buf] = parsedBuffer; gltfRuntime.buffersCount++; } }; var parseShaders = function (parsedShaders, gltfRuntime) { for (var sha in parsedShaders) { var parsedShader = parsedShaders[sha]; gltfRuntime.shaders[sha] = parsedShader; gltfRuntime.shaderscount++; } }; var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) { for (var object in parsedObjects) { var parsedObject = parsedObjects[object]; gltfRuntime[runtimeProperty][object] = parsedObject; } }; /** * Utils */ var normalizeUVs = function (buffer) { if (!buffer) { return; } for (var i = 0; i < buffer.length / 2; i++) { buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1]; } }; var getAttribute = function (attributeParameter) { if (attributeParameter.semantic === "NORMAL") { return "normal"; } else if (attributeParameter.semantic === "POSITION") { return "position"; } else if (attributeParameter.semantic === "JOINT") { return "matricesIndices"; } else if (attributeParameter.semantic === "WEIGHT") { return "matricesWeights"; } else if (attributeParameter.semantic === "COLOR") { return "color"; } else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) { var channel = Number(attributeParameter.semantic.split("_")[1]); return "uv" + (channel === 0 ? "" : channel + 1); } return null; }; /** * Loads and creates animations */ var loadAnimations = function (gltfRuntime) { for (var anim in gltfRuntime.animations) { var animation = gltfRuntime.animations[anim]; if (!animation.channels || !animation.samplers) { continue; } var lastAnimation = null; for (var i = 0; i < animation.channels.length; i++) { // Get parameters and load buffers var channel = animation.channels[i]; var sampler = animation.samplers[channel.sampler]; if (!sampler) { continue; } var inputData = null; var outputData = null; if (animation.parameters) { inputData = animation.parameters[sampler.input]; outputData = animation.parameters[sampler.output]; } else { inputData = sampler.input; outputData = sampler.output; } var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]); var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]); var targetID = channel.target.id; var targetNode = gltfRuntime.scene.getNodeByID(targetID); if (targetNode === null) { targetNode = gltfRuntime.scene.getNodeByName(targetID); } if (targetNode === null) { BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to"); continue; } var isBone = targetNode instanceof BABYLON.Bone; // Get target path (position, rotation or scaling) var targetPath = channel.target.path; var targetPathIndex = glTFAnimationPaths.indexOf(targetPath); if (targetPathIndex !== -1) { targetPath = babylonAnimationPaths[targetPathIndex]; } // Determine animation type var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX; if (!isBone) { if (targetPath === "rotationQuaternion") { animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION; targetNode.rotationQuaternion = new BABYLON.Quaternion(); } else { animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3; } } // Create animation and key frames var babylonAnimation = null; var keys = []; var arrayOffset = 0; var modifyKey = false; if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) { babylonAnimation = lastAnimation; modifyKey = true; } if (!modifyKey) { babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE); } // For each frame for (var j = 0; j < bufferInput.length; j++) { var value = null; if (targetPath === "rotationQuaternion") { // VEC4 value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]); arrayOffset += 4; } else { // Position and scaling are VEC3 value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]); arrayOffset += 3; } if (isBone) { var bone = targetNode; var translation = BABYLON.Vector3.Zero(); var rotationQuaternion = new BABYLON.Quaternion(); var scaling = BABYLON.Vector3.Zero(); // Warning on decompose var mat = bone.getBaseMatrix(); if (modifyKey && lastAnimation) { mat = lastAnimation.getKeys()[j].value; } mat.decompose(scaling, rotationQuaternion, translation); if (targetPath === "position") { translation = value; } else if (targetPath === "rotationQuaternion") { rotationQuaternion = value; } else { scaling = value; } value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation); } if (!modifyKey) { keys.push({ frame: bufferInput[j], value: value }); } else if (lastAnimation) { lastAnimation.getKeys()[j].value = value; } } // Finish if (!modifyKey && babylonAnimation) { babylonAnimation.setKeys(keys); targetNode.animations.push(babylonAnimation); } lastAnimation = babylonAnimation; gltfRuntime.scene.stopAnimation(targetNode); gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0); } } }; /** * Returns the bones transformation matrix */ var configureBoneTransformation = function (node) { var mat = null; if (node.translation || node.rotation || node.scale) { var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]); var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]); var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]); mat = BABYLON.Matrix.Compose(scale, rotation, position); } else { mat = BABYLON.Matrix.FromArray(node.matrix); } return mat; }; /** * Returns the parent bone */ var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) { // Try to find for (var i = 0; i < newSkeleton.bones.length; i++) { if (newSkeleton.bones[i].name === jointName) { return newSkeleton.bones[i]; } } // Not found, search in gltf nodes var nodes = gltfRuntime.nodes; for (var nde in nodes) { var node = nodes[nde]; if (!node.jointName) { continue; } var children = node.children; for (var i = 0; i < children.length; i++) { var child = gltfRuntime.nodes[children[i]]; if (!child.jointName) { continue; } if (child.jointName === jointName) { var mat = configureBoneTransformation(node); var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat); bone.id = nde; return bone; } } } return null; }; /** * Returns the appropriate root node */ var getNodeToRoot = function (nodesToRoot, id) { for (var i = 0; i < nodesToRoot.length; i++) { var nodeToRoot = nodesToRoot[i]; for (var j = 0; j < nodeToRoot.node.children.length; j++) { var child = nodeToRoot.node.children[j]; if (child === id) { return nodeToRoot.bone; } } } return null; }; /** * Returns the node with the joint name */ var getJointNode = function (gltfRuntime, jointName) { var nodes = gltfRuntime.nodes; var node = nodes[jointName]; if (node) { return { node: node, id: jointName }; } for (var nde in nodes) { node = nodes[nde]; if (node.jointName === jointName) { return { node: node, id: nde }; } } return null; }; /** * Checks if a nodes is in joints */ var nodeIsInJoints = function (skins, id) { for (var i = 0; i < skins.jointNames.length; i++) { if (skins.jointNames[i] === id) { return true; } } return false; }; /** * Fills the nodes to root for bones and builds hierarchy */ var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) { // Creates nodes for root for (var nde in gltfRuntime.nodes) { var node = gltfRuntime.nodes[nde]; var id = nde; if (!node.jointName || nodeIsInJoints(skins, node.jointName)) { continue; } // Create node to root bone var mat = configureBoneTransformation(node); var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat); bone.id = id; nodesToRoot.push({ bone: bone, node: node, id: id }); } // Parenting for (var i = 0; i < nodesToRoot.length; i++) { var nodeToRoot = nodesToRoot[i]; var children = nodeToRoot.node.children; for (var j = 0; j < children.length; j++) { var child = null; for (var k = 0; k < nodesToRoot.length; k++) { if (nodesToRoot[k].id === children[j]) { child = nodesToRoot[k]; break; } } if (child) { child.bone._parent = nodeToRoot.bone; nodeToRoot.bone.children.push(child.bone); } } } }; /** * Imports a skeleton */ var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) { if (!newSkeleton) { newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene); } if (!skins.babylonSkeleton) { return newSkeleton; } // Find the root bones var nodesToRoot = []; var nodesToRootToAdd = []; getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot); newSkeleton.bones = []; // Joints for (var i = 0; i < skins.jointNames.length; i++) { var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]); if (!jointNode) { continue; } var node = jointNode.node; if (!node) { BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist"); continue; } var id = jointNode.id; // Optimize, if the bone already exists... var existingBone = gltfRuntime.scene.getBoneByID(id); if (existingBone) { newSkeleton.bones.push(existingBone); continue; } // Search for parent bone var foundBone = false; var parentBone = null; for (var j = 0; j < i; j++) { var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]); if (!jointNode_1) { continue; } var joint = jointNode_1.node; if (!joint) { BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent"); continue; } var children = joint.children; if (!children) { continue; } foundBone = false; for (var k = 0; k < children.length; k++) { if (children[k] === id) { parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton); foundBone = true; break; } } if (foundBone) { break; } } // Create bone var mat = configureBoneTransformation(node); if (!parentBone && nodesToRoot.length > 0) { parentBone = getNodeToRoot(nodesToRoot, id); if (parentBone) { if (nodesToRootToAdd.indexOf(parentBone) === -1) { nodesToRootToAdd.push(parentBone); } } } var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat); bone.id = id; } // Polish var bones = newSkeleton.bones; newSkeleton.bones = []; for (var i = 0; i < skins.jointNames.length; i++) { var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]); if (!jointNode) { continue; } for (var j = 0; j < bones.length; j++) { if (bones[j].id === jointNode.id) { newSkeleton.bones.push(bones[j]); break; } } } newSkeleton.prepare(); // Finish for (var i = 0; i < nodesToRootToAdd.length; i++) { newSkeleton.bones.push(nodesToRootToAdd[i]); } return newSkeleton; }; /** * Imports a mesh and its geometries */ var importMesh = function (gltfRuntime, node, meshes, id, newMesh) { if (!newMesh) { newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene); newMesh.id = id; } if (!node.babylonNode) { return newMesh; } var subMaterials = []; var vertexData = null; var verticesStarts = new Array(); var verticesCounts = new Array(); var indexStarts = new Array(); var indexCounts = new Array(); for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) { var meshID = meshes[meshIndex]; var mesh = gltfRuntime.meshes[meshID]; if (!mesh) { continue; } // Positions, normals and UVs for (var i = 0; i < mesh.primitives.length; i++) { // Temporary vertex data var tempVertexData = new BABYLON.VertexData(); var primitive = mesh.primitives[i]; if (primitive.mode !== 4) { // continue; } var attributes = primitive.attributes; var accessor = null; var buffer = null; // Set positions, normal and uvs for (var semantic in attributes) { // Link accessor and buffer view accessor = gltfRuntime.accessors[attributes[semantic]]; buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor); if (semantic === "NORMAL") { tempVertexData.normals = new Float32Array(buffer.length); tempVertexData.normals.set(buffer); } else if (semantic === "POSITION") { if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) { tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4); for (var j = 0; j < buffer.length; j += 4) { tempVertexData.positions[j] = buffer[j]; tempVertexData.positions[j + 1] = buffer[j + 1]; tempVertexData.positions[j + 2] = buffer[j + 2]; } } else { tempVertexData.positions = new Float32Array(buffer.length); tempVertexData.positions.set(buffer); } verticesCounts.push(tempVertexData.positions.length); } else if (semantic.indexOf("TEXCOORD_") !== -1) { var channel = Number(semantic.split("_")[1]); var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1)); var uvs = new Float32Array(buffer.length); uvs.set(buffer); normalizeUVs(uvs); tempVertexData.set(uvs, uvKind); } else if (semantic === "JOINT") { tempVertexData.matricesIndices = new Float32Array(buffer.length); tempVertexData.matricesIndices.set(buffer); } else if (semantic === "WEIGHT") { tempVertexData.matricesWeights = new Float32Array(buffer.length); tempVertexData.matricesWeights.set(buffer); } else if (semantic === "COLOR") { tempVertexData.colors = new Float32Array(buffer.length); tempVertexData.colors.set(buffer); } } // Indices accessor = gltfRuntime.accessors[primitive.indices]; if (accessor) { buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor); tempVertexData.indices = new Int32Array(buffer.length); tempVertexData.indices.set(buffer); indexCounts.push(tempVertexData.indices.length); } else { // Set indices on the fly var indices = []; for (var j = 0; j < tempVertexData.positions.length / 3; j++) { indices.push(j); } tempVertexData.indices = new Int32Array(indices); indexCounts.push(tempVertexData.indices.length); } if (!vertexData) { vertexData = tempVertexData; } else { vertexData.merge(tempVertexData); } // Sub material var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material); subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1); // Update vertices start and index start verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]); indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]); } } var material; if (subMaterials.length > 1) { material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene); material.subMaterials = subMaterials; } else { material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene); } if (subMaterials.length === 1) { material = subMaterials[0]; } if (!newMesh.material) { newMesh.material = material; } // Apply geometry new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh); newMesh.computeWorldMatrix(true); // Apply submeshes newMesh.subMeshes = []; var index = 0; for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) { var meshID = meshes[meshIndex]; var mesh = gltfRuntime.meshes[meshID]; if (!mesh) { continue; } for (var i = 0; i < mesh.primitives.length; i++) { if (mesh.primitives[i].mode !== 4) { //continue; } BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true); index++; } } // Finish return newMesh; }; /** * Configure node transformation from position, rotation and scaling */ var configureNode = function (newNode, position, rotation, scaling) { if (newNode.position) { newNode.position = position; } if (newNode.rotationQuaternion || newNode.rotation) { newNode.rotationQuaternion = rotation; } if (newNode.scaling) { newNode.scaling = scaling; } }; /** * Configures node from transformation matrix */ var configureNodeFromMatrix = function (newNode, node, parent) { if (node.matrix) { var position = new BABYLON.Vector3(0, 0, 0); var rotation = new BABYLON.Quaternion(); var scaling = new BABYLON.Vector3(0, 0, 0); var mat = BABYLON.Matrix.FromArray(node.matrix); mat.decompose(scaling, rotation, position); configureNode(newNode, position, rotation, scaling); } else if (node.translation && node.rotation && node.scale) { configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale)); } newNode.computeWorldMatrix(true); }; /** * Imports a node */ var importNode = function (gltfRuntime, node, id, parent) { var lastNode = null; if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) { if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) { return null; } } // Meshes if (node.skin) { if (node.meshes) { var skin = gltfRuntime.skins[node.skin]; var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode); newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin); if (newMesh.skeleton === null) { newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin); if (!skin.babylonSkeleton) { skin.babylonSkeleton = newMesh.skeleton; } } lastNode = newMesh; } } else if (node.meshes) { /** * Improve meshes property */ var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode); lastNode = newMesh; } // Lights else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) { var light = gltfRuntime.lights[node.light]; if (light) { if (light.type === "ambient") { var ambienLight = light[light.type]; var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene); hemiLight.name = node.name || ""; if (ambienLight.color) { hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color); } lastNode = hemiLight; } else if (light.type === "directional") { var directionalLight = light[light.type]; var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene); dirLight.name = node.name || ""; if (directionalLight.color) { dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color); } lastNode = dirLight; } else if (light.type === "point") { var pointLight = light[light.type]; var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene); ptLight.name = node.name || ""; if (pointLight.color) { ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color); } lastNode = ptLight; } else if (light.type === "spot") { var spotLight = light[light.type]; var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene); spLight.name = node.name || ""; if (spotLight.color) { spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color); } if (spotLight.fallOfAngle) { spLight.angle = spotLight.fallOfAngle; } if (spotLight.fallOffExponent) { spLight.exponent = spotLight.fallOffExponent; } lastNode = spLight; } } } // Cameras else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) { var camera = gltfRuntime.cameras[node.camera]; if (camera) { if (camera.type === "orthographic") { var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false); orthoCamera.name = node.name || ""; orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA; orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas()); lastNode = orthoCamera; } else if (camera.type === "perspective") { var perspectiveCamera = camera[camera.type]; var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false); persCamera.name = node.name || ""; persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas()); if (!perspectiveCamera.aspectRatio) { perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight(); } if (perspectiveCamera.znear && perspectiveCamera.zfar) { persCamera.maxZ = perspectiveCamera.zfar; persCamera.minZ = perspectiveCamera.znear; } lastNode = persCamera; } } } // Empty node if (!node.jointName) { if (node.babylonNode) { return node.babylonNode; } else if (lastNode === null) { var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene); node.babylonNode = dummy; lastNode = dummy; } } if (lastNode !== null) { if (node.matrix && lastNode instanceof BABYLON.Mesh) { configureNodeFromMatrix(lastNode, node, parent); } else { var translation = node.translation || [0, 0, 0]; var rotation = node.rotation || [0, 0, 0, 1]; var scale = node.scale || [1, 1, 1]; configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale)); } lastNode.updateCache(true); node.babylonNode = lastNode; } return lastNode; }; /** * Traverses nodes and creates them */ var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) { if (meshIncluded === void 0) { meshIncluded = false; } var node = gltfRuntime.nodes[id]; var newNode = null; if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) { if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) { meshIncluded = true; } else { meshIncluded = false; } } else { meshIncluded = true; } if (!node.jointName && meshIncluded) { newNode = importNode(gltfRuntime, node, id, parent); if (newNode !== null) { newNode.id = id; newNode.parent = parent; } } if (node.children) { for (var i = 0; i < node.children.length; i++) { traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded); } } }; /** * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.) */ var postLoad = function (gltfRuntime) { // Nodes var currentScene = gltfRuntime.currentScene; if (currentScene) { for (var i = 0; i < currentScene.nodes.length; i++) { traverseNodes(gltfRuntime, currentScene.nodes[i], null); } } else { for (var thing in gltfRuntime.scenes) { currentScene = gltfRuntime.scenes[thing]; for (var i = 0; i < currentScene.nodes.length; i++) { traverseNodes(gltfRuntime, currentScene.nodes[i], null); } } } // Set animations loadAnimations(gltfRuntime); for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) { var skeleton = gltfRuntime.scene.skeletons[i]; gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0); } }; /** * onBind shaderrs callback to set uniforms and matrices */ var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) { var materialValues = material.values || technique.parameters; for (var unif in unTreatedUniforms) { var uniform = unTreatedUniforms[unif]; var type = uniform.type; if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) { if (uniform.semantic && !uniform.source && !uniform.node) { GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect()); } else if (uniform.semantic && (uniform.source || uniform.node)) { var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || ""); if (source === null) { source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || ""); } if (source === null) { continue; } GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect()); } } else { var value = materialValues[technique.uniforms[unif]]; if (!value) { continue; } if (type === GLTF1.EParameterType.SAMPLER_2D) { var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture; if (texture === null || texture === undefined) { continue; } shaderMaterial.getEffect().setTexture(unif, texture); } else { GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type); } } } onSuccess(shaderMaterial); }; /** * Prepare uniforms to send the only one time * Loads the appropriate textures */ var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) { var materialValues = material.values || technique.parameters; var techniqueUniforms = technique.uniforms; /** * Prepare values here (not matrices) */ for (var unif in unTreatedUniforms) { var uniform = unTreatedUniforms[unif]; var type = uniform.type; var value = materialValues[techniqueUniforms[unif]]; if (value === undefined) { // In case the value is the same for all materials value = uniform.value; } if (!value) { continue; } var onLoadTexture = function (uniformName) { return function (texture) { if (uniform.value && uniformName) { // Static uniform shaderMaterial.setTexture(uniformName, texture); delete unTreatedUniforms[uniformName]; } }; }; // Texture (sampler2D) if (type === GLTF1.EParameterType.SAMPLER_2D) { GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); }); } // Others else { if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) { // Static uniform delete unTreatedUniforms[unif]; } } } }; /** * Shader compilation failed */ var onShaderCompileError = function (program, shaderMaterial, onError) { return function (effect, error) { shaderMaterial.dispose(true); onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied"); }; }; /** * Shader compilation success */ var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) { return function (_) { prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms); shaderMaterial.onBind = function (mesh) { onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess); }; }; }; /** * Returns the appropriate uniform if already handled by babylon */ var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) { for (var unif in technique.uniforms) { var uniform = technique.uniforms[unif]; var uniformParameter = technique.parameters[uniform]; if (tokenizer.currentIdentifier === unif) { if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) { var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic); if (transformIndex !== -1) { delete unTreatedUniforms[unif]; return babylonTransforms[transformIndex]; } } } } return tokenizer.currentIdentifier; }; /** * All shaders loaded. Create materials one by one */ var importMaterials = function (gltfRuntime) { // Create materials for (var mat in gltfRuntime.materials) { GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { }); } }; /** * Implementation of the base glTF spec */ var GLTFLoaderBase = /** @class */ (function () { function GLTFLoaderBase() { } GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) { var gltfRuntime = { extensions: {}, accessors: {}, buffers: {}, bufferViews: {}, meshes: {}, lights: {}, cameras: {}, nodes: {}, images: {}, textures: {}, shaders: {}, programs: {}, samplers: {}, techniques: {}, materials: {}, animations: {}, skins: {}, extensionsUsed: [], scenes: {}, buffersCount: 0, shaderscount: 0, scene: scene, rootUrl: rootUrl, loadedBufferCount: 0, loadedBufferViews: {}, loadedShaderCount: 0, importOnlyMeshes: false, dummyNodes: [] }; // Parse if (parsedData.extensions) { parseObject(parsedData.extensions, "extensions", gltfRuntime); } if (parsedData.extensionsUsed) { parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime); } if (parsedData.buffers) { parseBuffers(parsedData.buffers, gltfRuntime); } if (parsedData.bufferViews) { parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime); } if (parsedData.accessors) { parseObject(parsedData.accessors, "accessors", gltfRuntime); } if (parsedData.meshes) { parseObject(parsedData.meshes, "meshes", gltfRuntime); } if (parsedData.lights) { parseObject(parsedData.lights, "lights", gltfRuntime); } if (parsedData.cameras) { parseObject(parsedData.cameras, "cameras", gltfRuntime); } if (parsedData.nodes) { parseObject(parsedData.nodes, "nodes", gltfRuntime); } if (parsedData.images) { parseObject(parsedData.images, "images", gltfRuntime); } if (parsedData.textures) { parseObject(parsedData.textures, "textures", gltfRuntime); } if (parsedData.shaders) { parseShaders(parsedData.shaders, gltfRuntime); } if (parsedData.programs) { parseObject(parsedData.programs, "programs", gltfRuntime); } if (parsedData.samplers) { parseObject(parsedData.samplers, "samplers", gltfRuntime); } if (parsedData.techniques) { parseObject(parsedData.techniques, "techniques", gltfRuntime); } if (parsedData.materials) { parseObject(parsedData.materials, "materials", gltfRuntime); } if (parsedData.animations) { parseObject(parsedData.animations, "animations", gltfRuntime); } if (parsedData.skins) { parseObject(parsedData.skins, "skins", gltfRuntime); } if (parsedData.scenes) { gltfRuntime.scenes = parsedData.scenes; } if (parsedData.scene && parsedData.scenes) { gltfRuntime.currentScene = parsedData.scenes[parsedData.scene]; } return gltfRuntime; }; GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) { var buffer = gltfRuntime.buffers[id]; if (BABYLON.Tools.IsBase64(buffer.uri)) { setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); }); } else { BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) { if (request) { onError(request.status + " " + request.statusText); } }); } }; GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) { var texture = gltfRuntime.textures[id]; if (!texture || !texture.source) { onError(""); return; } if (texture.babylonTexture) { onSuccess(null); return; } var source = gltfRuntime.images[texture.source]; if (BABYLON.Tools.IsBase64(source.uri)) { setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); }); } else { BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) { if (request) { onError(request.status + " " + request.statusText); } }); } }; GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) { var texture = gltfRuntime.textures[id]; if (texture.babylonTexture) { onSuccess(texture.babylonTexture); return; } var sampler = gltfRuntime.samplers[texture.sampler]; var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) || (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) || (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) || (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR); var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; var blob = new Blob([buffer]); var blobURL = URL.createObjectURL(blob); var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); }; var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL); if (sampler.wrapS !== undefined) { newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS); } if (sampler.wrapT !== undefined) { newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT); } newTexture.name = id; texture.babylonTexture = newTexture; onSuccess(newTexture); }; GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) { var shader = gltfRuntime.shaders[id]; if (BABYLON.Tools.IsBase64(shader.uri)) { var shaderString = atob(shader.uri.split(",")[1]); if (onSuccess) { onSuccess(shaderString); } } else { BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) { if (request && onError) { onError(request.status + " " + request.statusText); } }); } }; GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) { var material = gltfRuntime.materials[id]; if (!material.technique) { if (onError) { onError("No technique found."); } return; } var technique = gltfRuntime.techniques[material.technique]; if (!technique) { var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene); defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5); defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation; onSuccess(defaultMaterial); return; } var program = gltfRuntime.programs[technique.program]; var states = technique.states; var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"]; var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"]; var newVertexShader = ""; var newPixelShader = ""; var vertexTokenizer = new Tokenizer(vertexShader); var pixelTokenizer = new Tokenizer(pixelShader); var unTreatedUniforms = {}; var uniforms = []; var attributes = []; var samplers = []; // Fill uniform, sampler2D and attributes for (var unif in technique.uniforms) { var uniform = technique.uniforms[unif]; var uniformParameter = technique.parameters[uniform]; unTreatedUniforms[unif] = uniformParameter; if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) { var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic); if (transformIndex !== -1) { uniforms.push(babylonTransforms[transformIndex]); delete unTreatedUniforms[unif]; } else { uniforms.push(unif); } } else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) { samplers.push(unif); } else { uniforms.push(unif); } } for (var attr in technique.attributes) { var attribute = technique.attributes[attr]; var attributeParameter = technique.parameters[attribute]; if (attributeParameter.semantic) { attributes.push(getAttribute(attributeParameter)); } } // Configure vertex shader while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) { var tokenType = vertexTokenizer.currentToken; if (tokenType !== ETokenType.IDENTIFIER) { newVertexShader += vertexTokenizer.currentString; continue; } var foundAttribute = false; for (var attr in technique.attributes) { var attribute = technique.attributes[attr]; var attributeParameter = technique.parameters[attribute]; if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) { newVertexShader += getAttribute(attributeParameter); foundAttribute = true; break; } } if (foundAttribute) { continue; } newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms); } // Configure pixel shader while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) { var tokenType = pixelTokenizer.currentToken; if (tokenType !== ETokenType.IDENTIFIER) { newPixelShader += pixelTokenizer.currentString; continue; } newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms); } // Create shader material var shaderPath = { vertex: program.vertexShader + id, fragment: program.fragmentShader + id }; var options = { attributes: attributes, uniforms: uniforms, samplers: samplers, needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1 }; BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader; BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader; var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options); shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError); shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess); shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation; if (states && states.functions) { var functions = states.functions; if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) { shaderMaterial.backFaceCulling = false; } var blendFunc = functions.blendFuncSeparate; if (blendFunc) { if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) { shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE; } else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) { shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE; } else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) { shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD; } else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) { shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT; } else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) { shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY; } else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) { shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED; } } } }; return GLTFLoaderBase; }()); GLTF1.GLTFLoaderBase = GLTFLoaderBase; /** * glTF V1 Loader */ var GLTFLoader = /** @class */ (function () { function GLTFLoader() { // #region Stubs for IGLTFLoader interface this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO; this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST; this.compileMaterials = false; this.useClipPlane = false; this.compileShadowGenerators = false; this.transparencyAsCoverage = false; this._normalizeAnimationGroupsToBeginAtZero = true; this.preprocessUrlAsync = function (url) { return Promise.resolve(url); }; this.onMeshLoadedObservable = new BABYLON.Observable(); this.onTextureLoadedObservable = new BABYLON.Observable(); this.onMaterialLoadedObservable = new BABYLON.Observable(); this.onCameraLoadedObservable = new BABYLON.Observable(); this.onCompleteObservable = new BABYLON.Observable(); this.onDisposeObservable = new BABYLON.Observable(); this.onExtensionLoadedObservable = new BABYLON.Observable(); this.state = null; } GLTFLoader.RegisterExtension = function (extension) { if (GLTFLoader.Extensions[extension.name]) { BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists"); return; } GLTFLoader.Extensions[extension.name] = extension; }; GLTFLoader.prototype.dispose = function () { }; // #endregion GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) { var _this = this; scene.useRightHandedSystem = true; GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) { gltfRuntime.importOnlyMeshes = true; if (meshesNames === "") { gltfRuntime.importMeshesNames = []; } else if (typeof meshesNames === "string") { gltfRuntime.importMeshesNames = [meshesNames]; } else if (meshesNames && !(meshesNames instanceof Array)) { gltfRuntime.importMeshesNames = [meshesNames]; } else { gltfRuntime.importMeshesNames = []; BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]"); } // Create nodes _this._createNodes(gltfRuntime); var meshes = new Array(); var skeletons = new Array(); // Fill arrays of meshes and skeletons for (var nde in gltfRuntime.nodes) { var node = gltfRuntime.nodes[nde]; if (node.babylonNode instanceof BABYLON.AbstractMesh) { meshes.push(node.babylonNode); } } for (var skl in gltfRuntime.skins) { var skin = gltfRuntime.skins[skl]; if (skin.babylonSkeleton instanceof BABYLON.Skeleton) { skeletons.push(skin.babylonSkeleton); } } // Load buffers, shaders, materials, etc. _this._loadBuffersAsync(gltfRuntime, function () { _this._loadShadersAsync(gltfRuntime, function () { importMaterials(gltfRuntime); postLoad(gltfRuntime); if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) { onSuccess(meshes, skeletons); } }); }, onProgress); if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) { onSuccess(meshes, skeletons); } }, onError); return true; }; /** * Imports one or more meshes from a loaded gltf file and adds them to the scene * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file * @param scene the scene the meshes should be added to * @param data gltf data containing information of the meshes in a loaded file * @param rootUrl root url to load from * @param onProgress event that fires when loading progress has occured * @returns a promise containg the loaded meshes, particles, skeletons and animations */ GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) { var _this = this; return new Promise(function (resolve, reject) { _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) { resolve({ meshes: meshes, particleSystems: [], skeletons: skeletons, animationGroups: [] }); }, onProgress, function (message) { reject(new Error(message)); }); }); }; GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) { var _this = this; scene.useRightHandedSystem = true; GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) { // Load runtime extensios GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () { // Create nodes _this._createNodes(gltfRuntime); // Load buffers, shaders, materials, etc. _this._loadBuffersAsync(gltfRuntime, function () { _this._loadShadersAsync(gltfRuntime, function () { importMaterials(gltfRuntime); postLoad(gltfRuntime); if (!BABYLON.GLTFFileLoader.IncrementalLoading) { onSuccess(); } }); }); if (BABYLON.GLTFFileLoader.IncrementalLoading) { onSuccess(); } }, onError); }, onError); }; /** * Imports all objects from a loaded gltf file and adds them to the scene * @param scene the scene the objects should be added to * @param data gltf data containing information of the meshes in a loaded file * @param rootUrl root url to load from * @param onProgress event that fires when loading progress has occured * @returns a promise which completes when objects have been loaded to the scene */ GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) { var _this = this; return new Promise(function (resolve, reject) { _this._loadAsync(scene, data, rootUrl, function () { resolve(); }, onProgress, function (message) { reject(new Error(message)); }); }); }; GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) { var hasShaders = false; var processShader = function (sha, shader) { GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) { if (shaderString instanceof ArrayBuffer) { return; } gltfRuntime.loadedShaderCount++; if (shaderString) { BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString; } if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) { onload(); } }, function () { BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri); }); }; for (var sha in gltfRuntime.shaders) { hasShaders = true; var shader = gltfRuntime.shaders[sha]; if (shader) { processShader.bind(this, sha, shader)(); } else { BABYLON.Tools.Error("No shader named: " + sha); } } if (!hasShaders) { onload(); } }; ; GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) { var hasBuffers = false; var processBuffer = function (buf, buffer) { GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) { gltfRuntime.loadedBufferCount++; if (bufferView) { if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) { BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message } gltfRuntime.loadedBufferViews[buf] = bufferView; } if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) { onLoad(); } }, function () { BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri); }); }; for (var buf in gltfRuntime.buffers) { hasBuffers = true; var buffer = gltfRuntime.buffers[buf]; if (buffer) { processBuffer.bind(this, buf, buffer)(); } else { BABYLON.Tools.Error("No buffer named: " + buf); } } if (!hasBuffers) { onLoad(); } }; GLTFLoader.prototype._createNodes = function (gltfRuntime) { var currentScene = gltfRuntime.currentScene; if (currentScene) { // Only one scene even if multiple scenes are defined for (var i = 0; i < currentScene.nodes.length; i++) { traverseNodes(gltfRuntime, currentScene.nodes[i], null); } } else { // Load all scenes for (var thing in gltfRuntime.scenes) { currentScene = gltfRuntime.scenes[thing]; for (var i = 0; i < currentScene.nodes.length; i++) { traverseNodes(gltfRuntime, currentScene.nodes[i], null); } } } }; GLTFLoader.Extensions = {}; return GLTFLoader; }()); GLTF1.GLTFLoader = GLTFLoader; ; BABYLON.GLTFFileLoader._CreateGLTFLoaderV1 = function () { return new GLTFLoader(); }; })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.glTFLoader.js.map var BABYLON; (function (BABYLON) { var GLTF1; (function (GLTF1) { /** * Utils functions for GLTF */ var GLTFUtils = /** @class */ (function () { function GLTFUtils() { } /** * Sets the given "parameter" matrix * @param scene: the {BABYLON.Scene} object * @param source: the source node where to pick the matrix * @param parameter: the GLTF technique parameter * @param uniformName: the name of the shader's uniform * @param shaderMaterial: the shader material */ GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) { var mat = null; if (parameter.semantic === "MODEL") { mat = source.getWorldMatrix(); } else if (parameter.semantic === "PROJECTION") { mat = scene.getProjectionMatrix(); } else if (parameter.semantic === "VIEW") { mat = scene.getViewMatrix(); } else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") { mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert()); } else if (parameter.semantic === "MODELVIEW") { mat = source.getWorldMatrix().multiply(scene.getViewMatrix()); } else if (parameter.semantic === "MODELVIEWPROJECTION") { mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()); } else if (parameter.semantic === "MODELINVERSE") { mat = source.getWorldMatrix().invert(); } else if (parameter.semantic === "VIEWINVERSE") { mat = scene.getViewMatrix().invert(); } else if (parameter.semantic === "PROJECTIONINVERSE") { mat = scene.getProjectionMatrix().invert(); } else if (parameter.semantic === "MODELVIEWINVERSE") { mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert(); } else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") { mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert(); } else if (parameter.semantic === "MODELINVERSETRANSPOSE") { mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert()); } else { debugger; } if (mat) { switch (parameter.type) { case GLTF1.EParameterType.FLOAT_MAT2: shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat)); break; case GLTF1.EParameterType.FLOAT_MAT3: shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat)); break; case GLTF1.EParameterType.FLOAT_MAT4: shaderMaterial.setMatrix(uniformName, mat); break; default: break; } } }; /** * Sets the given "parameter" matrix * @param shaderMaterial: the shader material * @param uniform: the name of the shader's uniform * @param value: the value of the uniform * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4) */ GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) { switch (type) { case GLTF1.EParameterType.FLOAT: shaderMaterial.setFloat(uniform, value); return true; case GLTF1.EParameterType.FLOAT_VEC2: shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value)); return true; case GLTF1.EParameterType.FLOAT_VEC3: shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value)); return true; case GLTF1.EParameterType.FLOAT_VEC4: shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value)); return true; default: return false; } }; /** * Returns the wrap mode of the texture * @param mode: the mode value */ GLTFUtils.GetWrapMode = function (mode) { switch (mode) { case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE; case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE; case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE; default: return BABYLON.Texture.WRAP_ADDRESSMODE; } }; /** * Returns the byte stride giving an accessor * @param accessor: the GLTF accessor objet */ GLTFUtils.GetByteStrideFromType = function (accessor) { // Needs this function since "byteStride" isn't requiered in glTF format var type = accessor.type; switch (type) { case "VEC2": return 2; case "VEC3": return 3; case "VEC4": return 4; case "MAT2": return 4; case "MAT3": return 9; case "MAT4": return 16; default: return 1; } }; /** * Returns the texture filter mode giving a mode value * @param mode: the filter mode value */ GLTFUtils.GetTextureFilterMode = function (mode) { switch (mode) { case GLTF1.ETextureFilterType.LINEAR: case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST: case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE; case GLTF1.ETextureFilterType.NEAREST: case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE; default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE; } }; GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) { var byteOffset = bufferView.byteOffset + byteOffset; var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer]; if (byteOffset + byteLength > loadedBufferView.byteLength) { throw new Error("Buffer access is out of range"); } var buffer = loadedBufferView.buffer; byteOffset += loadedBufferView.byteOffset; switch (componentType) { case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength); case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength); case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength); case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength); default: return new Float32Array(buffer, byteOffset, byteLength); } }; /** * Returns a buffer from its accessor * @param gltfRuntime: the GLTF runtime * @param accessor: the GLTF accessor */ GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) { var bufferView = gltfRuntime.bufferViews[accessor.bufferView]; var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor); return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType); }; /** * Decodes a buffer view into a string * @param view: the buffer view */ GLTFUtils.DecodeBufferToText = function (view) { var result = ""; var length = view.byteLength; for (var i = 0; i < length; ++i) { result += String.fromCharCode(view[i]); } return result; }; /** * Returns the default material of gltf. Related to * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material * @param scene: the Babylon.js scene */ GLTFUtils.GetDefaultMaterial = function (scene) { if (!GLTFUtils._DefaultMaterial) { BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [ "precision highp float;", "", "uniform mat4 worldView;", "uniform mat4 projection;", "", "attribute vec3 position;", "", "void main(void)", "{", " gl_Position = projection * worldView * vec4(position, 1.0);", "}" ].join("\n"); BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [ "precision highp float;", "", "uniform vec4 u_emission;", "", "void main(void)", "{", " gl_FragColor = u_emission;", "}" ].join("\n"); var shaderPath = { vertex: "GLTFDefaultMaterial", fragment: "GLTFDefaultMaterial" }; var options = { attributes: ["position"], uniforms: ["worldView", "projection", "u_emission"], samplers: new Array(), needAlphaBlending: false }; GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options); GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0)); } return GLTFUtils._DefaultMaterial; }; // The GLTF default material GLTFUtils._DefaultMaterial = null; return GLTFUtils; }()); GLTF1.GLTFUtils = GLTFUtils; })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.glTFLoaderUtils.js.map var BABYLON; (function (BABYLON) { var GLTF1; (function (GLTF1) { var GLTFLoaderExtension = /** @class */ (function () { function GLTFLoaderExtension(name) { this._name = name; } Object.defineProperty(GLTFLoaderExtension.prototype, "name", { get: function () { return this._name; }, enumerable: true, configurable: true }); /** * Defines an override for loading the runtime * Return true to stop further extensions from loading the runtime */ GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) { return false; }; /** * Defines an onverride for creating gltf runtime * Return true to stop further extensions from creating the runtime */ GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) { return false; }; /** * Defines an override for loading buffers * Return true to stop further extensions from loading this buffer */ GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) { return false; }; /** * Defines an override for loading texture buffers * Return true to stop further extensions from loading this texture data */ GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) { return false; }; /** * Defines an override for creating textures * Return true to stop further extensions from loading this texture */ GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) { return false; }; /** * Defines an override for loading shader strings * Return true to stop further extensions from loading this shader data */ GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) { return false; }; /** * Defines an override for loading materials * Return true to stop further extensions from loading this material */ GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) { return false; }; // --------- // Utilities // --------- GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) { GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) { return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError); }, function () { setTimeout(function () { if (!onSuccess) { return; } onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl)); }); }); }; GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) { GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) { return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError); }, function () { setTimeout(function () { onSuccess(); }); }); }; GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) { GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) { return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress); }, function () { GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress); }); }; GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) { GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { if (buffer) { GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); } }, onError); }; GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) { GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) { return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError); }, function () { GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError); }); }; GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) { GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) { return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError); }, function () { GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError); }); }; GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) { GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) { return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError); }, function () { GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError); }); }; GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) { GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) { return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, function () { GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }); }; GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) { for (var extensionName in GLTF1.GLTFLoader.Extensions) { var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName]; if (func(loaderExtension)) { return; } } defaultFunc(); }; return GLTFLoaderExtension; }()); GLTF1.GLTFLoaderExtension = GLTFLoaderExtension; })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.glTFLoaderExtension.js.map var BABYLON; (function (BABYLON) { var GLTF1; (function (GLTF1) { var BinaryExtensionBufferName = "binary_glTF"; ; ; var GLTFBinaryExtension = /** @class */ (function (_super) { __extends(GLTFBinaryExtension, _super); function GLTFBinaryExtension() { return _super.call(this, "KHR_binary_glTF") || this; } GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) { var extensionsUsed = data.json.extensionsUsed; if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) { return false; } this._bin = data.bin; onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl)); return true; }; GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) { if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) { return false; } if (id !== BinaryExtensionBufferName) { return false; } onSuccess(this._bin); return true; }; GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) { var texture = gltfRuntime.textures[id]; var source = gltfRuntime.images[texture.source]; if (!source.extensions || !(this.name in source.extensions)) { return false; } var sourceExt = source.extensions[this.name]; var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView]; var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE); onSuccess(buffer); return true; }; GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) { var shader = gltfRuntime.shaders[id]; if (!shader.extensions || !(this.name in shader.extensions)) { return false; } var binaryExtensionShader = shader.extensions[this.name]; var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView]; var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE); setTimeout(function () { var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes); onSuccess(shaderString); }); return true; }; return GLTFBinaryExtension; }(GLTF1.GLTFLoaderExtension)); GLTF1.GLTFBinaryExtension = GLTFBinaryExtension; GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension()); })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.glTFBinaryExtension.js.map var BABYLON; (function (BABYLON) { var GLTF1; (function (GLTF1) { ; ; ; var GLTFMaterialsCommonExtension = /** @class */ (function (_super) { __extends(GLTFMaterialsCommonExtension, _super); function GLTFMaterialsCommonExtension() { return _super.call(this, "KHR_materials_common") || this; } GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) { if (!gltfRuntime.extensions) return false; var extension = gltfRuntime.extensions[this.name]; if (!extension) return false; // Create lights var lights = extension.lights; if (lights) { for (var thing in lights) { var light = lights[thing]; switch (light.type) { case "ambient": var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene); var ambient = light.ambient; if (ambient) { ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]); } break; case "point": var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene); var point = light.point; if (point) { pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]); } break; case "directional": var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene); var directional = light.directional; if (directional) { dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]); } break; case "spot": var spot = light.spot; if (spot) { var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene); spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]); } break; default: BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported"); break; } } } return false; }; GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) { var material = gltfRuntime.materials[id]; if (!material || !material.extensions) return false; var extension = material.extensions[this.name]; if (!extension) return false; var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene); standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation; if (extension.technique === "CONSTANT") { standardMaterial.disableLighting = true; } standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided; standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency; standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess; // Ambient if (typeof extension.values.ambient === "string") { this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError); } else { standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]); } // Diffuse if (typeof extension.values.diffuse === "string") { this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError); } else { standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]); } // Emission if (typeof extension.values.emission === "string") { this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError); } else { standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]); } // Specular if (typeof extension.values.specular === "string") { this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError); } else { standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]); } return true; }; GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) { // Create buffer from texture url GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { // Create texture from buffer GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError); }, onError); }; return GLTFMaterialsCommonExtension; }(GLTF1.GLTFLoaderExtension)); GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension; GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension()); })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map /** * Defines the module used to import/export glTF 2.0 assets */ var BABYLON; (function (BABYLON) { var GLTF2; (function (GLTF2) { var _ArrayItem = /** @class */ (function () { function _ArrayItem() { } _ArrayItem.Assign = function (values) { if (values) { for (var index = 0; index < values.length; index++) { values[index]._index = index; } } }; return _ArrayItem; }()); /** * Loader for loading a glTF 2.0 asset */ var GLTFLoader = /** @class */ (function () { function GLTFLoader() { /** @hidden */ this._completePromises = new Array(); /** @hidden */ this._onReadyObservable = new BABYLON.Observable(); this._disposed = false; this._state = null; this._extensions = {}; this._defaultSampler = {}; this._defaultBabylonMaterials = {}; this._requests = new Array(); /** * Mode that determines the coordinate system to use. */ this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO; /** * Mode that determines what animations will start. */ this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST; /** * Defines if the loader should compile materials. */ this.compileMaterials = false; /** * Defines if the loader should also compile materials with clip planes. */ this.useClipPlane = false; /** * Defines if the loader should compile shadow generators. */ this.compileShadowGenerators = false; /** * Defines if the Alpha blended materials are only applied as coverage. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials. * If true, no extra effects are applied to transparent pixels. */ this.transparencyAsCoverage = false; /** @hidden */ this._normalizeAnimationGroupsToBeginAtZero = true; /** * Function called before loading a url referenced by the asset. */ this.preprocessUrlAsync = function (url) { return Promise.resolve(url); }; /** * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh. */ this.onMeshLoadedObservable = new BABYLON.Observable(); /** * Observable raised when the loader creates a texture after parsing the glTF properties of the texture. */ this.onTextureLoadedObservable = new BABYLON.Observable(); /** * Observable raised when the loader creates a material after parsing the glTF properties of the material. */ this.onMaterialLoadedObservable = new BABYLON.Observable(); /** * Observable raised when the loader creates a camera after parsing the glTF properties of the camera. */ this.onCameraLoadedObservable = new BABYLON.Observable(); /** * Observable raised when the asset is completely loaded, immediately before the loader is disposed. * For assets with LODs, raised when all of the LODs are complete. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise. */ this.onCompleteObservable = new BABYLON.Observable(); /** * Observable raised after the loader is disposed. */ this.onDisposeObservable = new BABYLON.Observable(); /** * Observable raised after a loader extension is created. * Set additional options for a loader extension in this event. */ this.onExtensionLoadedObservable = new BABYLON.Observable(); } /** @hidden */ GLTFLoader._Register = function (name, factory) { if (GLTFLoader._ExtensionFactories[name]) { BABYLON.Tools.Error("Extension with the name '" + name + "' already exists"); return; } GLTFLoader._ExtensionFactories[name] = factory; // Keep the order of registration so that extensions registered first are called first. GLTFLoader._ExtensionNames.push(name); }; Object.defineProperty(GLTFLoader.prototype, "state", { /** * Loader state or null if the loader is not active. */ get: function () { return this._state; }, enumerable: true, configurable: true }); /** * Disposes the loader, releases resources during load, and cancels any outstanding requests. */ GLTFLoader.prototype.dispose = function () { if (this._disposed) { return; } this._disposed = true; this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); this._clear(); }; /** * Imports one or more meshes from the loaded glTF data and adds them to the scene * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file * @param scene the scene the meshes should be added to * @param data the glTF data to load * @param rootUrl root url to load from * @param onProgress event that fires when loading progress has occured * @returns a promise containg the loaded meshes, particles, skeletons and animations */ GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) { var _this = this; return Promise.resolve().then(function () { _this._babylonScene = scene; _this._rootUrl = rootUrl; _this._progressCallback = onProgress; _this._loadData(data); var nodes = null; if (meshesNames) { var nodeMap_1 = {}; if (_this._gltf.nodes) { for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) { var node = _a[_i]; if (node.name) { nodeMap_1[node.name] = node; } } } var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames]; nodes = names.map(function (name) { var node = nodeMap_1[name]; if (!node) { throw new Error("Failed to find node '" + name + "'"); } return node; }); } return _this._loadAsync(nodes).then(function () { return { meshes: _this._getMeshes(), particleSystems: [], skeletons: _this._getSkeletons(), animationGroups: _this._getAnimationGroups() }; }); }); }; /** * Imports all objects from the loaded glTF data and adds them to the scene * @param scene the scene the objects should be added to * @param data the glTF data to load * @param rootUrl root url to load from * @param onProgress event that fires when loading progress has occured * @returns a promise which completes when objects have been loaded to the scene */ GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) { var _this = this; return Promise.resolve().then(function () { _this._babylonScene = scene; _this._rootUrl = rootUrl; _this._progressCallback = onProgress; _this._loadData(data); return _this._loadAsync(null); }); }; GLTFLoader.prototype._loadAsync = function (nodes) { var _this = this; return Promise.resolve().then(function () { _this._state = BABYLON.GLTFLoaderState.LOADING; _this._loadExtensions(); _this._checkExtensions(); var promises = new Array(); if (nodes) { promises.push(_this._loadNodesAsync(nodes)); } else { var scene = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0); promises.push(_this._loadSceneAsync("#/scenes/" + scene._index, scene)); } if (_this.compileMaterials) { promises.push(_this._compileMaterialsAsync()); } if (_this.compileShadowGenerators) { promises.push(_this._compileShadowGeneratorsAsync()); } var resultPromise = Promise.all(promises).then(function () { _this._state = BABYLON.GLTFLoaderState.READY; _this._onReadyObservable.notifyObservers(_this); _this._startAnimations(); }); resultPromise.then(function () { if (_this._rootBabylonMesh) { _this._rootBabylonMesh.setEnabled(true); } BABYLON.Tools.SetImmediate(function () { if (!_this._disposed) { Promise.all(_this._completePromises).then(function () { _this._state = BABYLON.GLTFLoaderState.COMPLETE; _this.onCompleteObservable.notifyObservers(_this); _this.onCompleteObservable.clear(); _this._clear(); }).catch(function (error) { BABYLON.Tools.Error("glTF Loader: " + error.message); _this._clear(); }); } }); }); return resultPromise; }).catch(function (error) { if (!_this._disposed) { BABYLON.Tools.Error("glTF Loader: " + error.message); _this._clear(); throw error; } }); }; GLTFLoader.prototype._loadData = function (data) { this._gltf = data.json; this._setupData(); if (data.bin) { var buffers = this._gltf.buffers; if (buffers && buffers[0] && !buffers[0].uri) { var binaryBuffer = buffers[0]; if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) { BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")"); } binaryBuffer._data = Promise.resolve(data.bin); } else { BABYLON.Tools.Warn("Unexpected BIN chunk"); } } }; GLTFLoader.prototype._setupData = function () { _ArrayItem.Assign(this._gltf.accessors); _ArrayItem.Assign(this._gltf.animations); _ArrayItem.Assign(this._gltf.buffers); _ArrayItem.Assign(this._gltf.bufferViews); _ArrayItem.Assign(this._gltf.cameras); _ArrayItem.Assign(this._gltf.images); _ArrayItem.Assign(this._gltf.materials); _ArrayItem.Assign(this._gltf.meshes); _ArrayItem.Assign(this._gltf.nodes); _ArrayItem.Assign(this._gltf.samplers); _ArrayItem.Assign(this._gltf.scenes); _ArrayItem.Assign(this._gltf.skins); _ArrayItem.Assign(this._gltf.textures); if (this._gltf.nodes) { var nodeParents = {}; for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) { var node = _a[_i]; if (node.children) { for (var _b = 0, _c = node.children; _b < _c.length; _b++) { var index = _c[_b]; nodeParents[index] = node._index; } } } var rootNode = this._createRootNode(); for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) { var node = _e[_d]; var parentIndex = nodeParents[node._index]; node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex]; } } }; GLTFLoader.prototype._loadExtensions = function () { for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) { var name_1 = _a[_i]; var extension = GLTFLoader._ExtensionFactories[name_1](this); this._extensions[name_1] = extension; this.onExtensionLoadedObservable.notifyObservers(extension); } this.onExtensionLoadedObservable.clear(); }; GLTFLoader.prototype._checkExtensions = function () { if (this._gltf.extensionsRequired) { for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) { var name_2 = _a[_i]; var extension = this._extensions[name_2]; if (!extension || !extension.enabled) { throw new Error("Require extension " + name_2 + " is not available"); } } } }; GLTFLoader.prototype._createRootNode = function () { this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene); this._rootBabylonMesh.setEnabled(false); var rootNode = { _babylonMesh: this._rootBabylonMesh }; switch (this.coordinateSystemMode) { case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: { if (!this._babylonScene.useRightHandedSystem) { rootNode.rotation = [0, 1, 0, 0]; rootNode.scale = [1, 1, -1]; GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh); } break; } case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: { this._babylonScene.useRightHandedSystem = true; break; } default: { throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")"); } } this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh); return rootNode; }; GLTFLoader.prototype._loadNodesAsync = function (nodes) { var promises = new Array(); for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { var node = nodes_1[_i]; promises.push(this._loadNodeAsync("#/nodes/" + node._index, node)); } promises.push(this._loadAnimationsAsync()); return Promise.all(promises).then(function () { }); }; /** @hidden */ GLTFLoader.prototype._loadSceneAsync = function (context, scene) { var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene); if (promise) { return promise; } var promises = new Array(); for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) { var index = _a[_i]; var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index); promises.push(this._loadNodeAsync("#/nodes/" + node._index, node)); } promises.push(this._loadAnimationsAsync()); return Promise.all(promises).then(function () { }); }; GLTFLoader.prototype._forEachPrimitive = function (node, callback) { if (node._primitiveBabylonMeshes) { for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) { var babylonMesh = _a[_i]; callback(babylonMesh); } } else { callback(node._babylonMesh); } }; GLTFLoader.prototype._getMeshes = function () { var meshes = new Array(); // Root mesh is always first. meshes.push(this._rootBabylonMesh); var nodes = this._gltf.nodes; if (nodes) { for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { var node = nodes_2[_i]; if (node._babylonMesh) { meshes.push(node._babylonMesh); } if (node._primitiveBabylonMeshes) { for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) { var babylonMesh = _b[_a]; meshes.push(babylonMesh); } } } } return meshes; }; GLTFLoader.prototype._getSkeletons = function () { var skeletons = new Array(); var skins = this._gltf.skins; if (skins) { for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) { var skin = skins_1[_i]; if (skin._babylonSkeleton) { skeletons.push(skin._babylonSkeleton); } } } return skeletons; }; GLTFLoader.prototype._getAnimationGroups = function () { var animationGroups = new Array(); var animations = this._gltf.animations; if (animations) { for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) { var animation = animations_1[_i]; if (animation._babylonAnimationGroup) { animationGroups.push(animation._babylonAnimationGroup); } } } return animationGroups; }; GLTFLoader.prototype._startAnimations = function () { switch (this.animationStartMode) { case BABYLON.GLTFLoaderAnimationStartMode.NONE: { // do nothing break; } case BABYLON.GLTFLoaderAnimationStartMode.FIRST: { var babylonAnimationGroups = this._getAnimationGroups(); if (babylonAnimationGroups.length !== 0) { babylonAnimationGroups[0].start(true); } break; } case BABYLON.GLTFLoaderAnimationStartMode.ALL: { var babylonAnimationGroups = this._getAnimationGroups(); for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) { var babylonAnimationGroup = babylonAnimationGroups_1[_i]; babylonAnimationGroup.start(true); } break; } default: { BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")"); return; } } }; /** @hidden */ GLTFLoader.prototype._loadNodeAsync = function (context, node) { var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node); if (promise) { return promise; } if (node._babylonMesh) { throw new Error(context + ": Invalid recursive node hierarchy"); } var promises = new Array(); var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent ? node._parent._babylonMesh : null); node._babylonMesh = babylonMesh; GLTFLoader._LoadTransform(node, babylonMesh); if (node.mesh != undefined) { var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh); promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh)); } if (node.camera != undefined) { var camera = GLTFLoader._GetProperty(context + "/camera", this._gltf.cameras, node.camera); this._loadCamera("#/cameras/" + camera._index, camera, babylonMesh); } if (node.children) { for (var _i = 0, _a = node.children; _i < _a.length; _i++) { var index = _a[_i]; var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index); promises.push(this._loadNodeAsync("#/nodes/" + index, childNode)); } } this.onMeshLoadedObservable.notifyObservers(babylonMesh); return Promise.all(promises).then(function () { }); }; GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) { var _this = this; var promises = new Array(); var primitives = mesh.primitives; if (!primitives || primitives.length === 0) { throw new Error(context + ": Primitives are missing"); } _ArrayItem.Assign(primitives); if (primitives.length === 1) { var primitive = primitives[0]; promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh)); } else { node._primitiveBabylonMeshes = []; for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) { var primitive = primitives_1[_i]; var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh); node._primitiveBabylonMeshes.push(primitiveBabylonMesh); promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh)); this.onMeshLoadedObservable.notifyObservers(babylonMesh); } } if (node.skin != undefined) { var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin); promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin)); } return Promise.all(promises).then(function () { _this._forEachPrimitive(node, function (babylonMesh) { babylonMesh._refreshBoundingInfo(true); }); }); }; GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) { var _this = this; var promises = new Array(); this._createMorphTargets(context, node, mesh, primitive, babylonMesh); promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) { return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () { babylonGeometry.applyToMesh(babylonMesh); }); })); var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode); if (primitive.material == undefined) { babylonMesh.material = this._getDefaultMaterial(babylonDrawMode); } else { var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material); promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) { babylonMesh.material = babylonMaterial; })); } return Promise.all(promises).then(function () { }); }; GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { var _this = this; var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh); if (promise) { return promise; } var attributes = primitive.attributes; if (!attributes) { throw new Error(context + ": Attributes are missing"); } var promises = new Array(); var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene); if (primitive.indices == undefined) { babylonMesh.isUnIndexed = true; } else { var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices); promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) { babylonGeometry.setIndices(data); })); } var loadAttribute = function (attribute, kind, callback) { if (attributes[attribute] == undefined) { return; } babylonMesh._delayInfo = babylonMesh._delayInfo || []; if (babylonMesh._delayInfo.indexOf(kind) === -1) { babylonMesh._delayInfo.push(kind); } var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]); promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) { babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count); })); if (callback) { callback(accessor); } }; loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind); loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind); loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind); loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind); loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind); loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind); loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind); loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) { if (accessor.type === "VEC4" /* VEC4 */) { babylonMesh.hasVertexAlpha = true; } }); return Promise.all(promises).then(function () { return babylonGeometry; }); }; GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) { if (!primitive.targets) { return; } if (node._numMorphTargets == undefined) { node._numMorphTargets = primitive.targets.length; } else if (primitive.targets.length !== node._numMorphTargets) { throw new Error(context + ": Primitives do not have the same number of targets"); } babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager(); for (var index = 0; index < primitive.targets.length; index++) { var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0; babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight)); // TODO: tell the target whether it has positions, normals, tangents } }; GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) { if (!primitive.targets) { return Promise.resolve(); } var promises = new Array(); var morphTargetManager = babylonMesh.morphTargetManager; for (var index = 0; index < morphTargetManager.numTargets; index++) { var babylonMorphTarget = morphTargetManager.getTarget(index); promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget)); } return Promise.all(promises).then(function () { }); }; GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) { var _this = this; var promises = new Array(); var loadAttribute = function (attribute, kind, setData) { if (attributes[attribute] == undefined) { return; } var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind); if (!babylonVertexBuffer) { return; } var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]); promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) { setData(babylonVertexBuffer, data); })); }; loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) { babylonVertexBuffer.forEach(data.length, function (value, index) { data[index] += value; }); babylonMorphTarget.setPositions(data); }); loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) { babylonVertexBuffer.forEach(data.length, function (value, index) { data[index] += value; }); babylonMorphTarget.setNormals(data); }); loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) { var dataIndex = 0; babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) { // Tangent data for morph targets is stored as xyz delta. // The vertexData.tangent is stored as xyzw. // So we need to skip every fourth vertexData.tangent. if (((index + 1) % 4) !== 0) { data[dataIndex++] += value; } }); babylonMorphTarget.setTangents(data); }); return Promise.all(promises).then(function () { }); }; GLTFLoader._LoadTransform = function (node, babylonNode) { var position = BABYLON.Vector3.Zero(); var rotation = BABYLON.Quaternion.Identity(); var scaling = BABYLON.Vector3.One(); if (node.matrix) { var matrix = BABYLON.Matrix.FromArray(node.matrix); matrix.decompose(scaling, rotation, position); } else { if (node.translation) position = BABYLON.Vector3.FromArray(node.translation); if (node.rotation) rotation = BABYLON.Quaternion.FromArray(node.rotation); if (node.scale) scaling = BABYLON.Vector3.FromArray(node.scale); } babylonNode.position = position; babylonNode.rotationQuaternion = rotation; babylonNode.scaling = scaling; }; GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) { var _this = this; var assignSkeleton = function (skeleton) { _this._forEachPrimitive(node, function (babylonMesh) { babylonMesh.skeleton = skeleton; }); // Ignore the TRS of skinned nodes. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note) node._babylonMesh.parent = _this._rootBabylonMesh; node._babylonMesh.position = BABYLON.Vector3.Zero(); node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity(); node._babylonMesh.scaling = BABYLON.Vector3.One(); }; if (skin._loaded) { return skin._loaded.then(function () { assignSkeleton(skin._babylonSkeleton); }); } var skeletonId = "skeleton" + skin._index; var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene); skin._babylonSkeleton = babylonSkeleton; this._loadBones(context, skin); assignSkeleton(babylonSkeleton); return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) { _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData); })); }; GLTFLoader.prototype._loadBones = function (context, skin) { var babylonBones = {}; for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) { var index = _a[_i]; var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index); this._loadBone(node, skin, babylonBones); } }; GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) { var babylonBone = babylonBones[node._index]; if (babylonBone) { return babylonBone; } var babylonParentBone = null; if (node._parent && node._parent._babylonMesh !== this._rootBabylonMesh) { babylonParentBone = this._loadBone(node._parent, skin, babylonBones); } var boneIndex = skin.joints.indexOf(node._index); babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex); babylonBones[node._index] = babylonBone; node._babylonBones = node._babylonBones || []; node._babylonBones.push(babylonBone); return babylonBone; }; GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) { if (skin.inverseBindMatrices == undefined) { return Promise.resolve(null); } var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices); return this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor); }; GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) { for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) { var babylonBone = _a[_i]; var baseMatrix = BABYLON.Matrix.Identity(); var boneIndex = babylonBone._index; if (inverseBindMatricesData && boneIndex !== -1) { BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix); baseMatrix.invertToRef(baseMatrix); } var babylonParentBone = babylonBone.getParent(); if (babylonParentBone) { baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix); } babylonBone.updateMatrix(baseMatrix, false, false); babylonBone._updateDifferenceMatrix(undefined, false); } }; GLTFLoader.prototype._getNodeMatrix = function (node) { return node.matrix ? BABYLON.Matrix.FromArray(node.matrix) : BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero()); }; GLTFLoader.prototype._loadCamera = function (context, camera, babylonMesh) { var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera._index, BABYLON.Vector3.Zero(), this._babylonScene, false); babylonCamera.parent = babylonMesh; babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0); switch (camera.type) { case "perspective" /* PERSPECTIVE */: { var perspective = camera.perspective; if (!perspective) { throw new Error(context + ": Camera perspective properties are missing"); } babylonCamera.fov = perspective.yfov; babylonCamera.minZ = perspective.znear; babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE; break; } case "orthographic" /* ORTHOGRAPHIC */: { if (!camera.orthographic) { throw new Error(context + ": Camera orthographic properties are missing"); } babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA; babylonCamera.orthoLeft = -camera.orthographic.xmag; babylonCamera.orthoRight = camera.orthographic.xmag; babylonCamera.orthoBottom = -camera.orthographic.ymag; babylonCamera.orthoTop = camera.orthographic.ymag; babylonCamera.minZ = camera.orthographic.znear; babylonCamera.maxZ = camera.orthographic.zfar; break; } default: { throw new Error(context + ": Invalid camera type (" + camera.type + ")"); } } this.onCameraLoadedObservable.notifyObservers(babylonCamera); }; GLTFLoader.prototype._loadAnimationsAsync = function () { var animations = this._gltf.animations; if (!animations) { return Promise.resolve(); } var promises = new Array(); for (var index = 0; index < animations.length; index++) { var animation = animations[index]; promises.push(this._loadAnimationAsync("#/animations/" + index, animation)); } return Promise.all(promises).then(function () { }); }; GLTFLoader.prototype._loadAnimationAsync = function (context, animation) { var _this = this; var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene); animation._babylonAnimationGroup = babylonAnimationGroup; var promises = new Array(); _ArrayItem.Assign(animation.channels); _ArrayItem.Assign(animation.samplers); for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) { var channel = _a[_i]; promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup)); } return Promise.all(promises).then(function () { babylonAnimationGroup.normalize(_this._normalizeAnimationGroupsToBeginAtZero ? 0 : null); }); }; GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) { var _this = this; var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node); // Ignore animations that have no animation targets. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) || (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) { return Promise.resolve(); } // Ignore animations targeting TRS of skinned nodes. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note) if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) { return Promise.resolve(); } var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler); return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) { var targetPath; var animationType; switch (channel.target.path) { case "translation" /* TRANSLATION */: { targetPath = "position"; animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3; break; } case "rotation" /* ROTATION */: { targetPath = "rotationQuaternion"; animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION; break; } case "scale" /* SCALE */: { targetPath = "scaling"; animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3; break; } case "weights" /* WEIGHTS */: { targetPath = "influence"; animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT; break; } default: { throw new Error(context + ": Invalid target path (" + channel.target.path + ")"); } } var outputBufferOffset = 0; var getNextOutputValue; switch (targetPath) { case "position": { getNextOutputValue = function () { var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset); outputBufferOffset += 3; return value; }; break; } case "rotationQuaternion": { getNextOutputValue = function () { var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset); outputBufferOffset += 4; return value; }; break; } case "scaling": { getNextOutputValue = function () { var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset); outputBufferOffset += 3; return value; }; break; } case "influence": { getNextOutputValue = function () { var value = new Array(targetNode._numMorphTargets); for (var i = 0; i < targetNode._numMorphTargets; i++) { value[i] = data.output[outputBufferOffset++]; } return value; }; break; } } var getNextKey; switch (data.interpolation) { case "STEP" /* STEP */: { getNextKey = function (frameIndex) { return ({ frame: data.input[frameIndex], value: getNextOutputValue(), interpolation: BABYLON.AnimationKeyInterpolation.STEP }); }; break; } case "LINEAR" /* LINEAR */: { getNextKey = function (frameIndex) { return ({ frame: data.input[frameIndex], value: getNextOutputValue() }); }; break; } case "CUBICSPLINE" /* CUBICSPLINE */: { getNextKey = function (frameIndex) { return ({ frame: data.input[frameIndex], inTangent: getNextOutputValue(), value: getNextOutputValue(), outTangent: getNextOutputValue() }); }; break; } } var keys = new Array(data.input.length); for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) { keys[frameIndex] = getNextKey(frameIndex); } if (targetPath === "influence") { var _loop_1 = function (targetIndex) { var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length; var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType); babylonAnimation.setKeys(keys.map(function (key) { return ({ frame: key.frame, inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined, value: key.value[targetIndex], outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined }); })); _this._forEachPrimitive(targetNode, function (babylonMesh) { var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex); var babylonAnimationClone = babylonAnimation.clone(); morphTarget.animations.push(babylonAnimationClone); babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget); }); }; for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) { _loop_1(targetIndex); } } else { var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length; var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType); babylonAnimation.setKeys(keys); if (targetNode._babylonBones) { var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones); for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) { var babylonAnimationTarget = babylonAnimationTargets_1[_i]; babylonAnimationTarget.animations.push(babylonAnimation); } babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets); } else { targetNode._babylonMesh.animations.push(babylonAnimation); babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh); } } }); }; GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) { if (sampler._data) { return sampler._data; } var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */; switch (interpolation) { case "STEP" /* STEP */: case "LINEAR" /* LINEAR */: case "CUBICSPLINE" /* CUBICSPLINE */: { break; } default: { throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")"); } } var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input); var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output); sampler._data = Promise.all([ this._loadFloatAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor), this._loadFloatAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor) ]).then(function (_a) { var inputData = _a[0], outputData = _a[1]; return { input: inputData, interpolation: interpolation, output: outputData, }; }); return sampler._data; }; GLTFLoader.prototype._loadBufferAsync = function (context, buffer) { if (buffer._data) { return buffer._data; } if (!buffer.uri) { throw new Error(context + ": Uri is missing"); } buffer._data = this._loadUriAsync(context, buffer.uri); return buffer._data; }; /** @hidden */ GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) { if (bufferView._data) { return bufferView._data; } var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer); bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) { try { return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength); } catch (e) { throw new Error(context + ": " + e.message); } }); return bufferView._data; }; GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) { if (accessor.type !== "SCALAR" /* SCALAR */) { throw new Error(context + ": Invalid type " + accessor.type); } if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ && accessor.componentType !== 5123 /* UNSIGNED_SHORT */ && accessor.componentType !== 5125 /* UNSIGNED_INT */) { throw new Error(context + ": Invalid component type " + accessor.componentType); } if (accessor._data) { return accessor._data; } var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView); accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) { return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count); }); return accessor._data; }; GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) { // TODO: support normalized and stride var _this = this; if (accessor.componentType !== 5126 /* FLOAT */) { throw new Error("Invalid component type " + accessor.componentType); } if (accessor._data) { return accessor._data; } var numComponents = GLTFLoader._GetNumComponents(context, accessor.type); var length = numComponents * accessor.count; if (accessor.bufferView == undefined) { accessor._data = Promise.resolve(new Float32Array(length)); } else { var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView); accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) { return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length); }); } if (accessor.sparse) { var sparse_1 = accessor.sparse; accessor._data = accessor._data.then(function (data) { var indicesBufferView = GLTFLoader._GetProperty(context + "/sparse/indices/bufferView", _this._gltf.bufferViews, sparse_1.indices.bufferView); var valuesBufferView = GLTFLoader._GetProperty(context + "/sparse/values/bufferView", _this._gltf.bufferViews, sparse_1.values.bufferView); return Promise.all([ _this._loadBufferViewAsync("#/bufferViews/" + indicesBufferView._index, indicesBufferView), _this._loadBufferViewAsync("#/bufferViews/" + valuesBufferView._index, valuesBufferView) ]).then(function (_a) { var indicesData = _a[0], valuesData = _a[1]; var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count); var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count); var valuesIndex = 0; for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) { var dataIndex = indices[indicesIndex] * numComponents; for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) { data[dataIndex++] = values[valuesIndex++]; } } return data; }); }); } return accessor._data; }; /** @hidden */ GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) { var _this = this; if (bufferView._babylonBuffer) { return bufferView._babylonBuffer; } bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) { return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false); }); return bufferView._babylonBuffer; }; GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) { var _this = this; if (accessor._babylonVertexBuffer) { return accessor._babylonVertexBuffer; } if (accessor.sparse) { accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(function (data) { return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), data, kind, false); }); } else { var bufferView_1 = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView); accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView_1._index, bufferView_1, kind).then(function (buffer) { var size = GLTFLoader._GetNumComponents(context, accessor.type); return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true); }); } return accessor._babylonVertexBuffer; }; GLTFLoader.prototype._getDefaultMaterial = function (drawMode) { var babylonMaterial = this._defaultBabylonMaterials[drawMode]; if (!babylonMaterial) { babylonMaterial = this._createMaterial("__gltf_default", drawMode); babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE; babylonMaterial.metallic = 1; babylonMaterial.roughness = 1; this.onMaterialLoadedObservable.notifyObservers(babylonMaterial); } return babylonMaterial; }; GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) { var promises = new Array(); // Ensure metallic workflow babylonMaterial.metallic = 1; babylonMaterial.roughness = 1; var properties = material.pbrMetallicRoughness; if (properties) { if (properties.baseColorFactor) { babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor); babylonMaterial.alpha = properties.baseColorFactor[3]; } else { babylonMaterial.albedoColor = BABYLON.Color3.White(); } babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor; babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor; if (properties.baseColorTexture) { promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) { babylonMaterial.albedoTexture = texture; })); } if (properties.metallicRoughnessTexture) { promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) { babylonMaterial.metallicTexture = texture; })); babylonMaterial.useMetallnessFromMetallicTextureBlue = true; babylonMaterial.useRoughnessFromMetallicTextureGreen = true; babylonMaterial.useRoughnessFromMetallicTextureAlpha = false; } } this._loadMaterialAlphaProperties(context, material, babylonMaterial); return Promise.all(promises).then(function () { }); }; /** @hidden */ GLTFLoader.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) { var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, mesh, babylonMesh, babylonDrawMode, assign); if (promise) { return promise; } material._babylonData = material._babylonData || {}; var babylonData = material._babylonData[babylonDrawMode]; if (!babylonData) { var promises = new Array(); var name_3 = material.name || "material_" + material._index; var babylonMaterial = this._createMaterial(name_3, babylonDrawMode); promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial)); promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial)); this.onMaterialLoadedObservable.notifyObservers(babylonMaterial); babylonData = { material: babylonMaterial, meshes: [], loaded: Promise.all(promises).then(function () { }) }; material._babylonData[babylonDrawMode] = babylonData; } babylonData.meshes.push(babylonMesh); assign(babylonData.material); return babylonData.loaded; }; /** @hidden */ GLTFLoader.prototype._createMaterial = function (name, drawMode) { var babylonMaterial = new BABYLON.PBRMaterial(name, this._babylonScene); babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation; babylonMaterial.fillMode = drawMode; babylonMaterial.enableSpecularAntiAliasing = true; babylonMaterial.useRadianceOverAlpha = !this.transparencyAsCoverage; babylonMaterial.useSpecularOverAlpha = !this.transparencyAsCoverage; return babylonMaterial; }; /** @hidden */ GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) { var promises = new Array(); babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0); if (material.doubleSided) { babylonMaterial.backFaceCulling = false; babylonMaterial.twoSidedLighting = true; } if (material.normalTexture) { promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) { babylonMaterial.bumpTexture = texture; })); babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem; babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem; if (material.normalTexture.scale != undefined) { babylonMaterial.bumpTexture.level = material.normalTexture.scale; } } if (material.occlusionTexture) { promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) { babylonMaterial.ambientTexture = texture; })); babylonMaterial.useAmbientInGrayScale = true; if (material.occlusionTexture.strength != undefined) { babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength; } } if (material.emissiveTexture) { promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) { babylonMaterial.emissiveTexture = texture; })); } return Promise.all(promises).then(function () { }); }; /** @hidden */ GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) { var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */; switch (alphaMode) { case "OPAQUE" /* OPAQUE */: { babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE; break; } case "MASK" /* MASK */: { babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST; babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff); if (babylonMaterial.albedoTexture) { babylonMaterial.albedoTexture.hasAlpha = true; } break; } case "BLEND" /* BLEND */: { babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND; if (babylonMaterial.albedoTexture) { babylonMaterial.albedoTexture.hasAlpha = true; babylonMaterial.useAlphaFromAlbedoTexture = true; } break; } default: { throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")"); } } }; /** @hidden */ GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) { var _this = this; var promise = GLTF2.GLTFLoaderExtension._LoadTextureAsync(this, context, textureInfo, assign); if (promise) { return promise; } var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index); context = "#/textures/" + textureInfo.index; var promises = new Array(); var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler)); var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler); var deferred = new BABYLON.Deferred(); var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () { if (!_this._disposed) { deferred.resolve(); } }, function (message, exception) { if (!_this._disposed) { deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture"))); } }); promises.push(deferred.promise); babylonTexture.name = texture.name || "texture" + texture._index; babylonTexture.wrapU = samplerData.wrapU; babylonTexture.wrapV = samplerData.wrapV; babylonTexture.coordinatesIndex = textureInfo.texCoord || 0; var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source); promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (blob) { var dataUrl = "data:" + _this._rootUrl + (image.uri || "image" + image._index); babylonTexture.updateURL(dataUrl, blob); })); assign(babylonTexture); this.onTextureLoadedObservable.notifyObservers(babylonTexture); return Promise.all(promises).then(function () { }); }; GLTFLoader.prototype._loadSampler = function (context, sampler) { if (!sampler._data) { sampler._data = { noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */), samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter), wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS), wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT) }; } ; return sampler._data; }; GLTFLoader.prototype._loadImageAsync = function (context, image) { if (image._blob) { return image._blob; } var promise; if (image.uri) { promise = this._loadUriAsync(context, image.uri); } else { var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView); promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView); } image._blob = promise.then(function (data) { return new Blob([data], { type: image.mimeType }); }); return image._blob; }; /** @hidden */ GLTFLoader.prototype._loadUriAsync = function (context, uri) { var _this = this; var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri); if (promise) { return promise; } if (!GLTFLoader._ValidateUri(uri)) { throw new Error(context + ": Uri '" + uri + "' is invalid"); } if (BABYLON.Tools.IsBase64(uri)) { return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri))); } return this.preprocessUrlAsync(this._rootUrl + uri).then(function (url) { return new Promise(function (resolve, reject) { if (!_this._disposed) { var request_1 = BABYLON.Tools.LoadFile(url, function (data) { if (!_this._disposed) { resolve(new Uint8Array(data)); } }, function (event) { if (!_this._disposed) { try { if (request_1 && _this._state === BABYLON.GLTFLoaderState.LOADING) { request_1._lengthComputable = event.lengthComputable; request_1._loaded = event.loaded; request_1._total = event.total; _this._onProgress(); } } catch (e) { reject(e); } } }, _this._babylonScene.database, true, function (request, exception) { if (!_this._disposed) { reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request)); } }); _this._requests.push(request_1); } }); }); }; GLTFLoader.prototype._onProgress = function () { if (!this._progressCallback) { return; } var lengthComputable = true; var loaded = 0; var total = 0; for (var _i = 0, _a = this._requests; _i < _a.length; _i++) { var request = _a[_i]; if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) { return; } lengthComputable = lengthComputable && request._lengthComputable; loaded += request._loaded; total += request._total; } this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0)); }; /** @hidden */ GLTFLoader._GetProperty = function (context, array, index) { if (!array || index == undefined || !array[index]) { throw new Error(context + ": Failed to find index (" + index + ")"); } return array[index]; }; GLTFLoader._GetTextureWrapMode = function (context, mode) { // Set defaults if undefined mode = mode == undefined ? 10497 /* REPEAT */ : mode; switch (mode) { case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE; case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE; case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE; default: BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")"); return BABYLON.Texture.WRAP_ADDRESSMODE; } }; GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) { // Set defaults if undefined magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter; minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter; if (magFilter === 9729 /* LINEAR */) { switch (minFilter) { case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST; case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR; case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST; case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST; case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR; case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR; default: BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")"); return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR; } } else { if (magFilter !== 9728 /* NEAREST */) { BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")"); } switch (minFilter) { case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST; case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR; case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST; case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST; case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR; case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR; default: BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")"); return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST; } } }; GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) { var buffer = bufferView.buffer; byteOffset = bufferView.byteOffset + (byteOffset || 0); try { switch (componentType) { case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length); case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length); case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length); case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length); case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length); case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length); default: throw new Error("Invalid component type " + componentType); } } catch (e) { throw new Error(context + ": " + e); } }; GLTFLoader._GetNumComponents = function (context, type) { switch (type) { case "SCALAR": return 1; case "VEC2": return 2; case "VEC3": return 3; case "VEC4": return 4; case "MAT2": return 4; case "MAT3": return 9; case "MAT4": return 16; } throw new Error(context + ": Invalid type (" + type + ")"); }; GLTFLoader._ValidateUri = function (uri) { return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1); }; GLTFLoader._GetDrawMode = function (context, mode) { if (mode == undefined) { mode = 4 /* TRIANGLES */; } switch (mode) { case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode; case 1 /* LINES */: return BABYLON.Material.LineListDrawMode; case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode; case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode; case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode; case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode; case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode; } throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")"); }; GLTFLoader.prototype._compileMaterialsAsync = function () { var promises = new Array(); if (this._gltf.materials) { for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) { var material = _a[_i]; if (material._babylonData) { for (var babylonDrawMode in material._babylonData) { var babylonData = material._babylonData[babylonDrawMode]; for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) { var babylonMesh = _c[_b]; // Ensure nonUniformScaling is set if necessary. babylonMesh.computeWorldMatrix(true); var babylonMaterial = babylonData.material; promises.push(babylonMaterial.forceCompilationAsync(babylonMesh)); if (this.useClipPlane) { promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true })); } } } } } } return Promise.all(promises).then(function () { }); }; GLTFLoader.prototype._compileShadowGeneratorsAsync = function () { var promises = new Array(); var lights = this._babylonScene.lights; for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) { var light = lights_1[_i]; var generator = light.getShadowGenerator(); if (generator) { promises.push(generator.forceCompilationAsync()); } } return Promise.all(promises).then(function () { }); }; GLTFLoader.prototype._clear = function () { for (var _i = 0, _a = this._requests; _i < _a.length; _i++) { var request = _a[_i]; request.abort(); } this._requests.length = 0; delete this._gltf; delete this._babylonScene; this._completePromises.length = 0; this._onReadyObservable.clear(); for (var name_4 in this._extensions) { this._extensions[name_4].dispose(); } this._extensions = {}; delete this._rootBabylonMesh; delete this._progressCallback; this.onMeshLoadedObservable.clear(); this.onTextureLoadedObservable.clear(); this.onMaterialLoadedObservable.clear(); this.onCameraLoadedObservable.clear(); }; /** @hidden */ GLTFLoader.prototype._applyExtensions = function (actionAsync) { for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) { var name_5 = _a[_i]; var extension = this._extensions[name_5]; if (extension.enabled) { var promise = actionAsync(extension); if (promise) { return promise; } } } return null; }; GLTFLoader._ExtensionNames = new Array(); GLTFLoader._ExtensionFactories = {}; return GLTFLoader; }()); GLTF2.GLTFLoader = GLTFLoader; BABYLON.GLTFFileLoader._CreateGLTFLoaderV2 = function () { return new GLTFLoader(); }; })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.glTFLoader.js.map var BABYLON; (function (BABYLON) { var GLTF2; (function (GLTF2) { /** * Abstract class that can be implemented to extend existing glTF loader behavior. */ var GLTFLoaderExtension = /** @class */ (function () { /** * Creates new GLTFLoaderExtension * @param loader defines the GLTFLoader to use */ function GLTFLoaderExtension(loader) { /** * Gets or sets a boolean indicating if the extension is enabled */ this.enabled = true; this._loader = loader; } /** * Release all resources */ GLTFLoaderExtension.prototype.dispose = function () { delete this._loader; }; // #region Overridable Methods /** * Override this method to modify the default behavior for loading scenes. * @hidden */ GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; }; /** * Override this method to modify the default behavior for loading nodes. * @hidden */ GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; }; /** * Override this method to modify the default behavior for loading mesh primitive vertex data. * @hidden */ GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; }; /** * Override this method to modify the default behavior for loading materials. * @hidden */ GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) { return null; }; /** * Override this method to modify the default behavior for loading textures. * @hidden */ GLTFLoaderExtension.prototype._loadTextureAsync = function (context, textureInfo, assign) { return null; }; /** * Override this method to modify the default behavior for loading uris. * @hidden */ GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; }; // #endregion /** * Helper method called by a loader extension to load an glTF extension. * @hidden */ GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) { if (!property.extensions) { return null; } var extensions = property.extensions; var extension = extensions[this.name]; if (!extension) { return null; } // Clear out the extension before executing the action to avoid infinite recursion. delete extensions[this.name]; try { return actionAsync(context + "/extensions/" + this.name, extension); } finally { // Restore the extension after executing the action. extensions[this.name] = extension; } }; /** * Helper method called by the loader to allow extensions to override loading scenes. * @hidden */ GLTFLoaderExtension.prototype._loadExtrasValueAsync = function (context, property, actionAsync) { if (!property.extras) { return null; } var extras = property.extras; var value = extras[this.name]; if (value === undefined) { return null; } // Clear out the extras value before executing the action to avoid infinite recursion. delete extras[this.name]; try { return actionAsync(context + "/extras/" + this.name, value); } finally { // Restore the extras value after executing the action. extras[this.name] = value; } }; /** * Helper method called by the loader to allow extensions to override loading scenes. * @hidden */ GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) { return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); }); }; /** * Helper method called by the loader to allow extensions to override loading nodes. * @hidden */ GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) { return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); }); }; /** * Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. * @hidden */ GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) { return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); }); }; /** * Helper method called by the loader to allow extensions to override loading materials. * @hidden */ GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, mesh, babylonMesh, babylonDrawMode, assign) { return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, assign); }); }; /** * Helper method called by the loader to allow extensions to override loading textures. * @hidden */ GLTFLoaderExtension._LoadTextureAsync = function (loader, context, textureInfo, assign) { return loader._applyExtensions(function (extension) { return extension._loadTextureAsync(context, textureInfo, assign); }); }; /** * Helper method called by the loader to allow extensions to override loading uris. * @hidden */ GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) { return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); }); }; return GLTFLoaderExtension; }()); GLTF2.GLTFLoaderExtension = GLTFLoaderExtension; })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.glTFLoaderExtension.js.map var BABYLON; (function (BABYLON) { var GLTF2; (function (GLTF2) { var Extensions; (function (Extensions) { var NAME = "MSFT_lod"; /** * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod) */ var MSFT_lod = /** @class */ (function (_super) { __extends(MSFT_lod, _super); function MSFT_lod(loader) { var _this = _super.call(this, loader) || this; _this.name = NAME; /** * Maximum number of LODs to load, starting from the lowest LOD. */ _this.maxLODsToLoad = Number.MAX_VALUE; /** * Observable raised when all node LODs of one level are loaded. * The event data is the index of the loaded LOD starting from zero. * Dispose the loader to cancel the loading of the next level of LODs. */ _this.onNodeLODsLoadedObservable = new BABYLON.Observable(); /** * Observable raised when all material LODs of one level are loaded. * The event data is the index of the loaded LOD starting from zero. * Dispose the loader to cancel the loading of the next level of LODs. */ _this.onMaterialLODsLoadedObservable = new BABYLON.Observable(); _this._loadingNodeLOD = null; _this._loadNodeSignals = {}; _this._loadNodePromises = new Array(); _this._loadingMaterialLOD = null; _this._loadMaterialSignals = {}; _this._loadMaterialPromises = new Array(); _this._loader._onReadyObservable.addOnce(function () { var _loop_1 = function (indexLOD) { Promise.all(_this._loadNodePromises[indexLOD]).then(function () { _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD); }); }; for (var indexLOD = 0; indexLOD < _this._loadNodePromises.length; indexLOD++) { _loop_1(indexLOD); } var _loop_2 = function (indexLOD) { Promise.all(_this._loadMaterialPromises[indexLOD]).then(function () { _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD); }); }; for (var indexLOD = 0; indexLOD < _this._loadMaterialPromises.length; indexLOD++) { _loop_2(indexLOD); } }); return _this; } MSFT_lod.prototype.dispose = function () { _super.prototype.dispose.call(this); this._loadingNodeLOD = null; this._loadNodeSignals = {}; this._loadingMaterialLOD = null; this._loadMaterialSignals = {}; this.onMaterialLODsLoadedObservable.clear(); this.onNodeLODsLoadedObservable.clear(); }; MSFT_lod.prototype._loadNodeAsync = function (context, node) { var _this = this; return this._loadExtensionAsync(context, node, function (extensionContext, extension) { var firstPromise; var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids); var _loop_3 = function (indexLOD) { var nodeLOD = nodeLODs[indexLOD]; if (indexLOD !== 0) { _this._loadingNodeLOD = nodeLOD; if (!_this._loadNodeSignals[nodeLOD._index]) { _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred(); } } var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () { if (indexLOD !== 0) { var previousNodeLOD = nodeLODs[indexLOD - 1]; if (previousNodeLOD._babylonMesh) { previousNodeLOD._babylonMesh.dispose(false, true); delete previousNodeLOD._babylonMesh; } } if (indexLOD !== nodeLODs.length - 1) { var nodeIndex = nodeLODs[indexLOD + 1]._index; if (_this._loadNodeSignals[nodeIndex]) { _this._loadNodeSignals[nodeIndex].resolve(); delete _this._loadNodeSignals[nodeIndex]; } } }); if (indexLOD === 0) { firstPromise = promise; } else { _this._loader._completePromises.push(promise); _this._loadingNodeLOD = null; } _this._loadNodePromises[indexLOD] = _this._loadNodePromises[indexLOD] || []; _this._loadNodePromises[indexLOD].push(promise); }; for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) { _loop_3(indexLOD); } return firstPromise; }); }; MSFT_lod.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) { var _this = this; // Don't load material LODs if already loading a node LOD. if (this._loadingNodeLOD) { return null; } return this._loadExtensionAsync(context, material, function (extensionContext, extension) { var firstPromise; var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids); var _loop_4 = function (indexLOD) { var materialLOD = materialLODs[indexLOD]; if (indexLOD !== 0) { _this._loadingMaterialLOD = materialLOD; if (!_this._loadMaterialSignals[materialLOD._index]) { _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred(); } } var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, mesh, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () { if (indexLOD !== 0) { var babylonDataLOD = materialLOD._babylonData; assign(babylonDataLOD[babylonDrawMode].material); var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData; if (previousBabylonDataLOD[babylonDrawMode]) { previousBabylonDataLOD[babylonDrawMode].material.dispose(); delete previousBabylonDataLOD[babylonDrawMode]; } } if (indexLOD !== materialLODs.length - 1) { var materialIndex = materialLODs[indexLOD + 1]._index; if (_this._loadMaterialSignals[materialIndex]) { _this._loadMaterialSignals[materialIndex].resolve(); delete _this._loadMaterialSignals[materialIndex]; } } }); if (indexLOD === 0) { firstPromise = promise; } else { _this._loader._completePromises.push(promise); _this._loadingMaterialLOD = null; } _this._loadMaterialPromises[indexLOD] = _this._loadMaterialPromises[indexLOD] || []; _this._loadMaterialPromises[indexLOD].push(promise); }; for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) { _loop_4(indexLOD); } return firstPromise; }); }; MSFT_lod.prototype._loadUriAsync = function (context, uri) { var _this = this; // Defer the loading of uris if loading a material or node LOD. if (this._loadingMaterialLOD) { var index = this._loadingMaterialLOD._index; return this._loadMaterialSignals[index].promise.then(function () { return _this._loader._loadUriAsync(context, uri); }); } else if (this._loadingNodeLOD) { var index = this._loadingNodeLOD._index; return this._loadNodeSignals[index].promise.then(function () { return _this._loader._loadUriAsync(context, uri); }); } return null; }; /** * Gets an array of LOD properties from lowest to highest. */ MSFT_lod.prototype._getLODs = function (context, property, array, ids) { if (this.maxLODsToLoad <= 0) { throw new Error("maxLODsToLoad must be greater than zero"); } var properties = new Array(); for (var i = ids.length - 1; i >= 0; i--) { properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i])); if (properties.length === this.maxLODsToLoad) { return properties; } } properties.push(property); return properties; }; return MSFT_lod; }(GLTF2.GLTFLoaderExtension)); Extensions.MSFT_lod = MSFT_lod; GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); }); })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {})); })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=MSFT_lod.js.map var BABYLON; (function (BABYLON) { var GLTF2; (function (GLTF2) { var Extensions; (function (Extensions) { var NAME = "MSFT_minecraftMesh"; /** @hidden */ var MSFT_minecraftMesh = /** @class */ (function (_super) { __extends(MSFT_minecraftMesh, _super); function MSFT_minecraftMesh() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.name = NAME; return _this; } MSFT_minecraftMesh.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) { var _this = this; return this._loadExtrasValueAsync(context, mesh, function (extensionContext, value) { if (value) { return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) { if (babylonMaterial.needAlphaBlending()) { babylonMaterial.forceDepthWrite = true; babylonMaterial.separateCullingPass = true; } babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite; babylonMaterial.twoSidedLighting = true; assign(babylonMaterial); }); } return null; }); }; return MSFT_minecraftMesh; }(GLTF2.GLTFLoaderExtension)); Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh; GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_minecraftMesh(loader); }); })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {})); })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=MSFT_minecraftMesh.js.map var BABYLON; (function (BABYLON) { var GLTF2; (function (GLTF2) { var Extensions; (function (Extensions) { var NAME = "MSFT_sRGBFactors"; /** @hidden */ var MSFT_sRGBFactors = /** @class */ (function (_super) { __extends(MSFT_sRGBFactors, _super); function MSFT_sRGBFactors() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.name = NAME; return _this; } MSFT_sRGBFactors.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) { var _this = this; return this._loadExtrasValueAsync(context, material, function (extensionContext, value) { if (value) { return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) { if (!babylonMaterial.albedoTexture) { babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor); } if (!babylonMaterial.reflectivityTexture) { babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor); } assign(babylonMaterial); }); } return null; }); }; return MSFT_sRGBFactors; }(GLTF2.GLTFLoaderExtension)); Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors; GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_sRGBFactors(loader); }); })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {})); })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=MSFT_sRGBFactors.js.map var BABYLON; (function (BABYLON) { var GLTF2; (function (GLTF2) { var Extensions; (function (Extensions) { var NAME = "KHR_draco_mesh_compression"; /** * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression) */ var KHR_draco_mesh_compression = /** @class */ (function (_super) { __extends(KHR_draco_mesh_compression, _super); function KHR_draco_mesh_compression(loader) { var _this = _super.call(this, loader) || this; _this.name = NAME; _this._dracoCompression = null; // Disable extension if decoder is not available. if (!BABYLON.DracoCompression.DecoderAvailable) { _this.enabled = false; } return _this; } KHR_draco_mesh_compression.prototype.dispose = function () { if (this._dracoCompression) { this._dracoCompression.dispose(); } _super.prototype.dispose.call(this); }; KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { var _this = this; return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) { if (primitive.mode != undefined) { if (primitive.mode !== 5 /* TRIANGLE_STRIP */ && primitive.mode !== 4 /* TRIANGLES */) { throw new Error(context + ": Unsupported mode " + primitive.mode); } // TODO: handle triangle strips if (primitive.mode === 5 /* TRIANGLE_STRIP */) { throw new Error(context + ": Mode " + primitive.mode + " is not currently supported"); } } var attributes = {}; var loadAttribute = function (name, kind) { var uniqueId = extension.attributes[name]; if (uniqueId == undefined) { return; } babylonMesh._delayInfo = babylonMesh._delayInfo || []; if (babylonMesh._delayInfo.indexOf(kind) === -1) { babylonMesh._delayInfo.push(kind); } attributes[kind] = uniqueId; }; loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind); loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind); loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind); loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind); loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind); loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind); loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind); loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind); var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView); if (!bufferView._dracoBabylonGeometry) { bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) { if (!_this._dracoCompression) { _this._dracoCompression = new BABYLON.DracoCompression(); } return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) { var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene); babylonVertexData.applyToGeometry(babylonGeometry); return babylonGeometry; }).catch(function (error) { throw new Error(context + ": " + error.message); }); }); } return bufferView._dracoBabylonGeometry; }); }; return KHR_draco_mesh_compression; }(GLTF2.GLTFLoaderExtension)); Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression; GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); }); })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {})); })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=KHR_draco_mesh_compression.js.map var BABYLON; (function (BABYLON) { var GLTF2; (function (GLTF2) { var Extensions; (function (Extensions) { var NAME = "KHR_materials_pbrSpecularGlossiness"; /** * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness) */ var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) { __extends(KHR_materials_pbrSpecularGlossiness, _super); function KHR_materials_pbrSpecularGlossiness() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.name = NAME; return _this; } KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) { var _this = this; return this._loadExtensionAsync(context, material, function (extensionContext, extension) { material._babylonData = material._babylonData || {}; var babylonData = material._babylonData[babylonDrawMode]; if (!babylonData) { var promises = new Array(); var name_1 = material.name || "materialSG_" + material._index; var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode); promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial)); promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial)); _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial); babylonData = { material: babylonMaterial, meshes: [], loaded: Promise.all(promises).then(function () { }) }; material._babylonData[babylonDrawMode] = babylonData; } babylonData.meshes.push(babylonMesh); assign(babylonData.material); return babylonData.loaded; }); }; KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) { var promises = new Array(); if (properties.diffuseFactor) { babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor); babylonMaterial.alpha = properties.diffuseFactor[3]; } else { babylonMaterial.albedoColor = BABYLON.Color3.White(); } babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White(); babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor; if (properties.diffuseTexture) { promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) { babylonMaterial.albedoTexture = texture; })); } if (properties.specularGlossinessTexture) { promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) { babylonMaterial.reflectivityTexture = texture; })); babylonMaterial.reflectivityTexture.hasAlpha = true; babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true; } this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial); return Promise.all(promises).then(function () { }); }; return KHR_materials_pbrSpecularGlossiness; }(GLTF2.GLTFLoaderExtension)); Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness; GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); }); })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {})); })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map var BABYLON; (function (BABYLON) { var GLTF2; (function (GLTF2) { var Extensions; (function (Extensions) { var NAME = "KHR_materials_unlit"; /** * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit) */ var KHR_materials_unlit = /** @class */ (function (_super) { __extends(KHR_materials_unlit, _super); function KHR_materials_unlit() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.name = NAME; return _this; } KHR_materials_unlit.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) { var _this = this; return this._loadExtensionAsync(context, material, function () { material._babylonData = material._babylonData || {}; var babylonData = material._babylonData[babylonDrawMode]; if (!babylonData) { var name_1 = material.name || "materialUnlit_" + material._index; var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode); babylonMaterial.unlit = true; var promise = _this._loadUnlitPropertiesAsync(context, material, babylonMaterial); _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial); babylonData = { material: babylonMaterial, meshes: [], loaded: promise }; material._babylonData[babylonDrawMode] = babylonData; } babylonData.meshes.push(babylonMesh); assign(babylonData.material); return babylonData.loaded; }); }; KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) { var promises = new Array(); // Ensure metallic workflow babylonMaterial.metallic = 1; babylonMaterial.roughness = 1; var properties = material.pbrMetallicRoughness; if (properties) { if (properties.baseColorFactor) { babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor); babylonMaterial.alpha = properties.baseColorFactor[3]; } else { babylonMaterial.albedoColor = BABYLON.Color3.White(); } if (properties.baseColorTexture) { promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) { babylonMaterial.albedoTexture = texture; })); } } if (material.doubleSided) { babylonMaterial.backFaceCulling = false; babylonMaterial.twoSidedLighting = true; } this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial); return Promise.all(promises).then(function () { }); }; return KHR_materials_unlit; }(GLTF2.GLTFLoaderExtension)); Extensions.KHR_materials_unlit = KHR_materials_unlit; GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); }); })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {})); })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {})); })(BABYLON || (BABYLON = {})); //# sourceMappingURL=KHR_materials_unlit.js.map var BABYLON; (function (BABYLON) { var GLTF2; (function (GLTF2) { var Extensions; (function (Extensions) { var NAME = "KHR_lights"; var LightType; (function (LightType) { LightType["AMBIENT"] = "ambient"; LightType["DIRECTIONAL"] = "directional"; LightType["POINT"] = "point"; LightType["SPOT"] = "spot"; })(LightType || (LightType = {})); /** * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental) */ var KHR_lights = /** @class */ (function (_super) { __extends(KHR_lights, _super); function KHR_lights() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.name = NAME; return _this; } KHR_lights.prototype._loadSceneAsync = function (context, scene) { var _this = this; return this._loadExtensionAsync(context, scene, function (extensionContext, extension) { var promise = _this._loader._loadSceneAsync(extensionContext, scene); var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light); if (light.type !== LightType.AMBIENT) { throw new Error(extensionContext + ": Only ambient lights are allowed on a scene"); } _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black(); return promise; }); }; KHR_lights.prototype._loadNodeAsync = function (context, node) { var _this = this; return this._loadExtensionAsync(context, node, function (extensionContext, extension) { var promise = _this._loader._loadNodeAsync(extensionContext, node); var babylonLight; var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light); var name = node._babylonMesh.name; switch (light.type) { case LightType.AMBIENT: { throw new Error(extensionContext + ": Ambient lights are not allowed on a node"); } case LightType.DIRECTIONAL: { babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene); break; } case LightType.POINT: { babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene); break; } case LightType.SPOT: { var spotLight = light; // TODO: support inner and outer cone angles //const innerConeAngle = spotLight.innerConeAngle || 0; var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4; babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene); break; } default: { throw new Error(extensionContext + ": Invalid light type (" + light.type + ")"); } } babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White(); babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity; babylonLight.parent = node._babylonMesh; return promise; }); }; Object.defineProperty(KHR_lights.prototype, "_lights", { get: function () { var extensions = this._loader._gltf.extensions; if (!extensions || !extensions[this.name]) { throw new Error("#/extensions: '" + this.name + "' not found"); } var extension = extensions[this.name]; return extension.lights; }, enumerable: true, configurable: true }); return KHR_lights; }(GLTF2.GLTFLoaderExtension)); Extensions.KHR_lights = KHR_lights; GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); }); })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {})); })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {})); })(BABYLON || (BABYLON = {})); var BABYLON; (function (BABYLON) { var GLTF2; (function (GLTF2) { var Extensions; (function (Extensions) { var NAME = "KHR_texture_transform"; /** * [Specification](https://github.com/AltspaceVR/glTF/blob/avr-sampler-offset-tile/extensions/2.0/Khronos/KHR_texture_transform/README.md) (Experimental) */ var KHR_texture_transform = /** @class */ (function (_super) { __extends(KHR_texture_transform, _super); function KHR_texture_transform() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.name = NAME; return _this; } KHR_texture_transform.prototype._loadTextureAsync = function (context, textureInfo, assign) { var _this = this; return this._loadExtensionAsync(context, textureInfo, function (extensionContext, extension) { return _this._loader._loadTextureAsync(context, textureInfo, function (babylonTexture) { if (extension.offset) { babylonTexture.uOffset = extension.offset[0]; babylonTexture.vOffset = extension.offset[1]; } // Always rotate around the origin. babylonTexture.uRotationCenter = 0; babylonTexture.vRotationCenter = 0; if (extension.rotation) { babylonTexture.wAng = -extension.rotation; } if (extension.scale) { babylonTexture.uScale = extension.scale[0]; babylonTexture.vScale = extension.scale[1]; } if (extension.texCoord != undefined) { babylonTexture.coordinatesIndex = extension.texCoord; } assign(babylonTexture); }); }); }; return KHR_texture_transform; }(GLTF2.GLTFLoaderExtension)); Extensions.KHR_texture_transform = KHR_texture_transform; GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_texture_transform(loader); }); })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {})); })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {})); })(BABYLON || (BABYLON = {})); return BABYLON; }); /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(16); /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); var mappers_1 = __webpack_require__(3); exports.mapperManager = mappers_1.mapperManager; var globals_1 = __webpack_require__(4); exports.viewerGlobals = globals_1.viewerGlobals; var viewerManager_1 = __webpack_require__(7); exports.viewerManager = viewerManager_1.viewerManager; var defaultViewer_1 = __webpack_require__(8); exports.DefaultViewer = defaultViewer_1.DefaultViewer; var viewer_1 = __webpack_require__(9); exports.AbstractViewer = viewer_1.AbstractViewer; var telemetryManager_1 = __webpack_require__(6); exports.telemetryManager = telemetryManager_1.telemetryManager; var modelLoader_1 = __webpack_require__(13); exports.ModelLoader = modelLoader_1.ModelLoader; var viewerModel_1 = __webpack_require__(5); exports.ViewerModel = viewerModel_1.ViewerModel; exports.ModelState = viewerModel_1.ModelState; /** * BabylonJS Viewer * * An HTML-Based viewer for 3D models, based on BabylonJS and its extensions. */ var BABYLON = __webpack_require__(0); exports.BABYLON = BABYLON; // load needed modules. __webpack_require__(14); __webpack_require__(64); var initializer_1 = __webpack_require__(65); exports.InitTags = initializer_1.InitTags; // promise polyfill, if needed! BABYLON.PromisePolyfill.Apply(); initializer_1.initListeners(); //deprectaed, here for backwards compatibility var disableInit = globals_1.viewerGlobals.disableInit; exports.disableInit = disableInit; /** * Dispose all viewers currently registered */ function disposeAll() { viewerManager_1.viewerManager.dispose(); mappers_1.mapperManager.dispose(); telemetryManager_1.telemetryManager.dispose(); } exports.disposeAll = disposeAll; var Version = globals_1.viewerGlobals.version; exports.Version = Version; console.log("Babylon.js viewer (v" + Version + ")"); // export publicliy all configuration interfaces __export(__webpack_require__(10)); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7QUFBQSxtREFBd0Q7QUE4Q3lFLHdCQTlDeEgsdUJBQWEsQ0E4Q3dIO0FBN0M5SSxtREFBd0Q7QUE2Q1ksd0JBN0MzRCx1QkFBYSxDQTZDMkQ7QUE1Q2pGLHdEQUF1RDtBQTRDMkQsd0JBNUN6Ryw2QkFBYSxDQTRDeUc7QUEzQy9ILHdEQUF1RDtBQTJDbEIsd0JBM0M1Qiw2QkFBYSxDQTJDNEI7QUExQ2xELDBDQUFpRDtBQTBDRyx5QkExQzNDLHVCQUFjLENBMEMyQztBQXpDbEUsZ0VBQStEO0FBeUNvQiwyQkF6QzFFLG1DQUFnQixDQXlDMEU7QUF4Q25HLG9EQUFtRDtBQXdDeUcsc0JBeENuSix5QkFBVyxDQXdDbUo7QUF2Q3ZLLG1EQUE4RDtBQXVDMkcsc0JBdkNoSyx5QkFBVyxDQXVDZ0s7QUFBcUMscUJBdkNuTSx3QkFBVSxDQXVDbU07QUFuQ25POzs7O0dBSUc7QUFFSCxtQ0FBcUM7QUE2QjVCLDBCQUFPO0FBM0JoQix1QkFBdUI7QUFDdkIsNkJBQTJCO0FBQzNCLGlCQUFlO0FBRWYsNkNBQXdEO0FBdUI3QixtQkF2Qkgsc0JBQVEsQ0F1Qkc7QUFyQm5DLCtCQUErQjtBQUMvQixPQUFPLENBQUMsZUFBZSxDQUFDLEtBQUssRUFBRSxDQUFDO0FBQ2hDLDJCQUFhLEVBQUUsQ0FBQztBQUVoQiw4Q0FBOEM7QUFDOUMsSUFBSSxXQUFXLEdBQVksdUJBQWEsQ0FBQyxXQUFXLENBQUM7QUFnQmdELGtDQUFXO0FBZGhIOztHQUVHO0FBQ0g7SUFDSSw2QkFBYSxDQUFDLE9BQU8sRUFBRSxDQUFDO0lBQ3hCLHVCQUFhLENBQUMsT0FBTyxFQUFFLENBQUM7SUFDeEIsbUNBQWdCLENBQUMsT0FBTyxFQUFFLENBQUM7QUFDL0IsQ0FBQztBQU8rSSxnQ0FBVTtBQUwxSixJQUFNLE9BQU8sR0FBRyx1QkFBYSxDQUFDLE9BQU8sQ0FBQztBQUtwQiwwQkFBTztBQUh6QixPQUFPLENBQUMsR0FBRyxDQUFDLHNCQUFzQixHQUFHLE9BQU8sR0FBRyxHQUFHLENBQUMsQ0FBQztBQUlwRCxnREFBZ0Q7QUFDaEQscUNBQWdDIn0= /***/ }), /* 17 */ /***/ (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 || Function("return this")() || (1,eval)("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; /***/ }), /* 18 */ /***/ (function(module, exports) { if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;} module.exports = CANNON; /***/ }), /* 19 */ /***/ (function(module, exports) { if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;} module.exports = OIMO; /***/ }), /* 20 */ /***/ (function(module, exports) { if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;} module.exports = earcut; /***/ }), /* 21 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); var isMergeableObject = function isMergeableObject(value) { return isNonNullObject(value) && !isSpecial(value) }; function isNonNullObject(value) { return !!value && typeof value === 'object' } function isSpecial(value) { var stringValue = Object.prototype.toString.call(value); return stringValue === '[object RegExp]' || stringValue === '[object Date]' || isReactElement(value) } // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25 var canUseSymbol = typeof Symbol === 'function' && Symbol.for; var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7; function isReactElement(value) { return value.$$typeof === REACT_ELEMENT_TYPE } function emptyTarget(val) { return Array.isArray(val) ? [] : {} } function cloneUnlessOtherwiseSpecified(value, options) { return (options.clone !== false && options.isMergeableObject(value)) ? deepmerge(emptyTarget(value), value, options) : value } function defaultArrayMerge(target, source, options) { return target.concat(source).map(function(element) { return cloneUnlessOtherwiseSpecified(element, options) }) } function mergeObject(target, source, options) { var destination = {}; if (options.isMergeableObject(target)) { Object.keys(target).forEach(function(key) { destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); }); } Object.keys(source).forEach(function(key) { if (!options.isMergeableObject(source[key]) || !target[key]) { destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); } else { destination[key] = deepmerge(target[key], source[key], options); } }); return destination } function deepmerge(target, source, options) { options = options || {}; options.arrayMerge = options.arrayMerge || defaultArrayMerge; options.isMergeableObject = options.isMergeableObject || isMergeableObject; var sourceIsArray = Array.isArray(source); var targetIsArray = Array.isArray(target); var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; if (!sourceAndTargetTypesMatch) { return cloneUnlessOtherwiseSpecified(source, options) } else if (sourceIsArray) { return options.arrayMerge(target, source, options) } else { return mergeObject(target, source, options) } } deepmerge.all = function deepmergeAll(array, options) { if (!Array.isArray(array)) { throw new Error('first argument should be an array') } return array.reduce(function(prev, next) { return deepmerge(prev, next, options) }, {}) }; var deepmerge_1 = deepmerge; /* harmony default export */ __webpack_exports__["default"] = (deepmerge_1); /***/ }), /* 22 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var babylonjs_1 = __webpack_require__(0); var configuration_1 = __webpack_require__(10); var viewerModel_1 = __webpack_require__(5); var helper_1 = __webpack_require__(1); var viewerLabs_1 = __webpack_require__(24); var _1 = __webpack_require__(26); var SceneManager = /** @class */ (function () { function SceneManager(_engine, _configurationContainer, _observablesManager) { var _this = this; this._engine = _engine; this._configurationContainer = _configurationContainer; this._observablesManager = _observablesManager; this._animationBlendingEnabled = true; this._white = babylonjs_1.Color3.White(); this._forceShadowUpdate = false; this._processShadows = true; this._groundEnabled = true; this._groundMirrorEnabled = true; this._defaultRenderingPipelineEnabled = false; this._globalConfiguration = {}; this._defaultRenderingPipelineShouldBuild = true; // default from rendering pipeline this._bloomEnabled = false; // default from rendering pipeline this._fxaaEnabled = false; this._focusOnModel = function (model) { var boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true); var sizeVec = boundingInfo.max.subtract(boundingInfo.min); var halfSizeVec = sizeVec.scale(0.5); var center = boundingInfo.min.add(halfSizeVec); _this.camera.setTarget(center); _this.camera.alpha = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.alpha) || _this.camera.alpha; _this.camera.beta = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.beta) || _this.camera.beta; _this.camera.radius = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.radius) || _this.camera.radius; /*this.scene.lights.filter(light => light instanceof ShadowLight).forEach(light => { // casting ais safe, due to the constraints tested before (light).setDirectionToTarget(center); });*/ }; this._cameraBehaviorMapping = {}; this.models = []; this.onCameraConfiguredObservable = new babylonjs_1.Observable(); this.onLightsConfiguredObservable = new babylonjs_1.Observable(); this.onModelsConfiguredObservable = new babylonjs_1.Observable(); this.onSceneConfiguredObservable = new babylonjs_1.Observable(); this.onSceneInitObservable = new babylonjs_1.Observable(); this.onSceneOptimizerConfiguredObservable = new babylonjs_1.Observable(); this.onEnvironmentConfiguredObservable = new babylonjs_1.Observable(); //this._viewer.onEngineInitObservable.add(() => { this._handleHardwareLimitations(); //}); this.onSceneInitObservable.add(function (scene) { _this.scene.animationPropertiesOverride = _this.scene.animationPropertiesOverride || new babylonjs_1.AnimationPropertiesOverride(); _this.labs = new viewerLabs_1.ViewerLabs(scene); var updateShadows = function () { for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) { var light = _a[_i]; var generator = light.getShadowGenerator(); if (generator) { // Processing shadows if animates var shadowMap = generator.getShadowMap(); if (shadowMap) { shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE; } } } }; scene.registerBeforeRender(function () { if (_this._forceShadowUpdate || (scene.animatables && scene.animatables.length > 0)) { // make sure all models are loaded updateShadows(); _this._forceShadowUpdate = false; } else if (!(_this.models.every(function (model) { if (!model.shadowsRenderedAfterLoad) { model.shadowsRenderedAfterLoad = true; return false; } return model.state === viewerModel_1.ModelState.COMPLETE && !model.currentAnimation; }))) { updateShadows(); } }); return _this._observablesManager && _this._observablesManager.onSceneInitObservable.notifyObserversWithPromise(_this.scene); }); if (this._observablesManager) { this._observablesManager.onModelLoadedObservable.add(function (model) { for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) { var light = _a[_i]; var generator = light.getShadowGenerator(); if (generator) { // Processing shadows if animates var shadowMap = generator.getShadowMap(); if (shadowMap) { shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE; } } } _this._focusOnModel(model); }); this._observablesManager.onModelAddedObservable.add(function (model) { _this.models.push(model); }); this._observablesManager.onModelRemovedObservable.add(function (model) { _this.models.splice(_this.models.indexOf(model), 1); }); } } Object.defineProperty(SceneManager.prototype, "defaultRenderingPipeline", { get: function () { return this._defaultRenderingPipeline; }, enumerable: true, configurable: true }); Object.defineProperty(SceneManager.prototype, "isHdrSupported", { /** * Returns a boolean representing HDR support */ get: function () { return this._hdrSupport; }, enumerable: true, configurable: true }); Object.defineProperty(SceneManager.prototype, "mainColor", { /** * Return the main color defined in the configuration. */ get: function () { return this._configurationContainer.mainColor; }, enumerable: true, configurable: true }); Object.defineProperty(SceneManager.prototype, "reflectionColor", { get: function () { return this._configurationContainer.reflectionColor; }, enumerable: true, configurable: true }); Object.defineProperty(SceneManager.prototype, "animationBlendingEnabled", { get: function () { return this.scene && this.scene.animationPropertiesOverride.enableBlending; }, set: function (value) { this.scene.animationPropertiesOverride.enableBlending = value; }, enumerable: true, configurable: true }); Object.defineProperty(SceneManager.prototype, "observablesManager", { get: function () { return this._observablesManager; }, enumerable: true, configurable: true }); Object.defineProperty(SceneManager.prototype, "processShadows", { /** * The flag defining whether shadows are rendered constantly or once. */ get: function () { return this._processShadows; }, /** * Should shadows be rendered every frame, or only once and stop. * This can be used to optimize a scene. * * Not that the shadows will NOT disapear but will remain in place. * @param process if true shadows will be updated once every frame. if false they will stop being updated. */ set: function (process) { var refreshType = process ? babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME : babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE; for (var _i = 0, _a = this.scene.lights; _i < _a.length; _i++) { var light = _a[_i]; var generator = light.getShadowGenerator(); if (generator) { var shadowMap = generator.getShadowMap(); if (shadowMap) { shadowMap.refreshRate = refreshType; } } } this._processShadows = process; }, enumerable: true, configurable: true }); Object.defineProperty(SceneManager.prototype, "groundEnabled", { get: function () { return this._groundEnabled; }, set: function (newValue) { if (newValue === this._groundEnabled) return; this._groundEnabled = newValue; if (this.environmentHelper && this.environmentHelper.ground) { this.environmentHelper.ground.setEnabled(this._groundEnabled); } }, enumerable: true, configurable: true }); Object.defineProperty(SceneManager.prototype, "groundMirrorEnabled", { /** * gets wether the reflection is disabled. */ get: function () { return this._groundMirrorEnabled; }, /** * sets wether the reflection is disabled. */ set: function (value) { if (this._groundMirrorEnabled === value) { return; } this._groundMirrorEnabled = value; if (this.environmentHelper && this.environmentHelper.groundMaterial && this.environmentHelper.groundMirror) { if (!value) { this.environmentHelper.groundMaterial.reflectionTexture = null; } else { this.environmentHelper.groundMaterial.reflectionTexture = this.environmentHelper.groundMirror; } } }, enumerable: true, configurable: true }); Object.defineProperty(SceneManager.prototype, "defaultRenderingPipelineEnabled", { get: function () { return this._defaultRenderingPipelineEnabled; }, set: function (value) { if (value === this._defaultRenderingPipelineEnabled) { return; } this._defaultRenderingPipelineEnabled = value; this._rebuildPostprocesses(); if (this._defaultRenderingPipeline) { this._defaultRenderingPipelineShouldBuild = false; this._defaultRenderingPipeline.prepare(); this.scene.imageProcessingConfiguration.applyByPostProcess = true; } }, enumerable: true, configurable: true }); /** * Sets the engine flags to unlock all babylon features. * Can also be configured using the scene.flags configuration object */ SceneManager.prototype.unlockBabylonFeatures = function () { this.scene.shadowsEnabled = true; this.scene.particlesEnabled = true; this.scene.postProcessesEnabled = true; this.scene.collisionsEnabled = true; this.scene.lightsEnabled = true; this.scene.texturesEnabled = true; this.scene.lensFlaresEnabled = true; this.scene.proceduralTexturesEnabled = true; this.scene.renderTargetsEnabled = true; this.scene.spritesEnabled = true; this.scene.skeletonsEnabled = true; this.scene.audioEnabled = true; }; /** * initialize the scene. Calling this function again will dispose the old scene, if exists. */ SceneManager.prototype.initScene = function (sceneConfiguration, optimizerConfiguration) { if (sceneConfiguration === void 0) { sceneConfiguration = {}; } // if the scen exists, dispose it. if (this.scene) { this.scene.dispose(); } // create a new scene this.scene = new babylonjs_1.Scene(this._engine); // set a default PBR material if (!sceneConfiguration.defaultMaterial) { var defaultMaterial = new BABYLON.PBRMaterial('defaultMaterial', this.scene); defaultMaterial.reflectivityColor = new BABYLON.Color3(0.1, 0.1, 0.1); defaultMaterial.microSurface = 0.6; if (this.scene.defaultMaterial) { this.scene.defaultMaterial.dispose(); } this.scene.defaultMaterial = defaultMaterial; } this.scene.animationPropertiesOverride = new babylonjs_1.AnimationPropertiesOverride(); babylonjs_1.Animation.AllowMatricesInterpolation = true; /*if (sceneConfiguration.glow) { let options: Partial = { mainTextureFixedSize: 512 }; if (typeof sceneConfiguration.glow === 'object') { options = sceneConfiguration.glow } var gl = new BABYLON.GlowLayer("glow", this.scene, options); }*/ return this.onSceneInitObservable.notifyObserversWithPromise(this.scene); }; SceneManager.prototype.clearScene = function (clearModels, clearLights) { if (clearModels === void 0) { clearModels = true; } if (clearLights === void 0) { clearLights = false; } if (clearModels) { this.models.forEach(function (m) { return m.dispose(); }); this.models.length = 0; } if (clearLights) { this.scene.lights.forEach(function (l) { return l.dispose(); }); } }; /** * This will update the scene's configuration, including camera, lights, environment. * @param newConfiguration the delta that should be configured. This includes only the changes * @param globalConfiguration The global configuration object, after the new configuration was merged into it */ SceneManager.prototype.updateConfiguration = function (newConfiguration) { var _this = this; if (this._configurationContainer) { this._globalConfiguration = this._configurationContainer.configuration; } else { this._globalConfiguration = newConfiguration; } if (newConfiguration.lab) { if (newConfiguration.lab.assetsRootURL) { this.labs.assetsRootURL = newConfiguration.lab.assetsRootURL; } } // update scene configuration if (newConfiguration.scene) { this._configureScene(newConfiguration.scene); } // optimizer if (newConfiguration.optimizer !== undefined) { this._configureOptimizer(newConfiguration.optimizer); } // configure model /*if (newConfiguration.model && typeof newConfiguration.model === 'object') { this._configureModel(newConfiguration.model); }*/ // lights this._configureLights(newConfiguration.lights); // environment if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) { this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground); } // camera this._configureCamera(newConfiguration.camera); if (newConfiguration.lab) { if (newConfiguration.lab.environmentMap) { var rot_1 = newConfiguration.lab.environmentMap.rotationY; this.labs.loadEnvironment(newConfiguration.lab.environmentMap.texture, function () { _this.labs.applyEnvironmentMapConfiguration(rot_1); }); if (!newConfiguration.lab.environmentMap.texture && newConfiguration.lab.environmentMap.rotationY) { this.labs.applyEnvironmentMapConfiguration(newConfiguration.lab.environmentMap.rotationY); } } // rendering piplines if (newConfiguration.lab.defaultRenderingPipelines) { var pipelineConfig = newConfiguration.lab.defaultRenderingPipelines; if (typeof pipelineConfig === 'boolean') { this.defaultRenderingPipelineEnabled = pipelineConfig; } else { this.defaultRenderingPipelineEnabled = true; } } if (newConfiguration.lab.environmentMainColor) { var mainColor = new babylonjs_1.Color3().copyFrom(newConfiguration.lab.environmentMainColor); this.environmentHelper.setMainColor(mainColor); } if (newConfiguration.lab.globalLightRotation !== undefined) { // rotate all lights that are shadow lights this.scene.lights.filter(function (light) { return light instanceof babylonjs_1.ShadowLight; }).forEach(function (light) { // casting and '!' are safe, due to the constraints tested before _this.labs.rotateShadowLight(light, newConfiguration.lab.globalLightRotation); }); this._forceShadowUpdate = true; } } if (this._defaultRenderingPipeline && this._defaultRenderingPipeline.imageProcessing) { this._defaultRenderingPipeline.imageProcessing.fromLinearSpace = true; } if (this._defaultRenderingPipelineShouldBuild && this._defaultRenderingPipeline) { this._defaultRenderingPipelineShouldBuild = false; this._defaultRenderingPipeline.prepare(); } }; SceneManager.prototype._rebuildPostprocesses = function (configuration) { if (!this._defaultRenderingPipelineEnabled || !configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", this._globalConfiguration)) { if (this._defaultRenderingPipeline) { this._defaultRenderingPipeline.dispose(); this._defaultRenderingPipeline = null; this.scene.autoClearDepthAndStencil = true; this.scene.autoClear = true; this.scene.imageProcessingConfiguration.applyByPostProcess = false; } return; } var pipelineConfig = configuration || (this._globalConfiguration.lab && this._globalConfiguration.lab.defaultRenderingPipelines); if (pipelineConfig) { if (!this._defaultRenderingPipeline) { // Create pipeline in manual mode to avoid triggering multiple shader compilations this._defaultRenderingPipeline = new babylonjs_1.DefaultRenderingPipeline("default rendering pipeline", this._hdrSupport, this.scene, [this.camera], false); } this.scene.autoClear = false; this.scene.autoClearDepthAndStencil = false; this._defaultRenderingPipelineShouldBuild = true; var bloomEnabled = this._bloomEnabled; if (typeof pipelineConfig !== 'boolean') { helper_1.extendClassWithConfig(this._defaultRenderingPipeline, pipelineConfig); this._bloomEnabled = !!pipelineConfig.bloomEnabled; this._fxaaEnabled = !!pipelineConfig.fxaaEnabled; bloomEnabled = this._bloomEnabled && pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight > 0; this._defaultRenderingPipeline.bloomWeight = (pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight) || (this._defaultRenderingPipeline.bloomWeight); } this._defaultRenderingPipeline.bloomEnabled = bloomEnabled; this._defaultRenderingPipeline.fxaaEnabled = this.fxaaEnabled; } }; Object.defineProperty(SceneManager.prototype, "bloomEnabled", { get: function () { return this._bloomEnabled; }, set: function (value) { if (this._bloomEnabled === value) { return; } this._bloomEnabled = value; this._rebuildPostprocesses(); if (this._defaultRenderingPipeline) { this._defaultRenderingPipelineShouldBuild = false; this._defaultRenderingPipeline.prepare(); this.scene.imageProcessingConfiguration.applyByPostProcess = true; } }, enumerable: true, configurable: true }); Object.defineProperty(SceneManager.prototype, "fxaaEnabled", { get: function () { return this._fxaaEnabled; }, set: function (value) { if (this._fxaaEnabled === value) { return; } this._fxaaEnabled = value; this._rebuildPostprocesses(); if (this._defaultRenderingPipeline) { this._defaultRenderingPipelineShouldBuild = false; this._defaultRenderingPipeline.prepare(); this.scene.imageProcessingConfiguration.applyByPostProcess = true; } }, enumerable: true, configurable: true }); /** * internally configure the scene using the provided configuration. * The scene will not be recreated, but just updated. * @param sceneConfig the (new) scene configuration */ SceneManager.prototype._configureScene = function (sceneConfig) { // sanity check! if (!this.scene) { return; } var cc = sceneConfig.clearColor; var oldcc = this.scene.clearColor; if (cc) { if (cc.r !== undefined) { oldcc.r = cc.r; } if (cc.g !== undefined) { oldcc.g = cc.g; } if (cc.b !== undefined) { oldcc.b = cc.b; } if (cc.a !== undefined) { oldcc.a = cc.a; } } // image processing configuration - optional. if (sceneConfig.imageProcessingConfiguration) { helper_1.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration); } //animation properties override if (sceneConfig.animationPropertiesOverride) { helper_1.extendClassWithConfig(this.scene.animationPropertiesOverride, sceneConfig.animationPropertiesOverride); } if (sceneConfig.environmentTexture) { if (!(this.scene.environmentTexture && this.scene.environmentTexture.url === sceneConfig.environmentTexture)) { if (this.scene.environmentTexture && this.scene.environmentTexture.dispose) { this.scene.environmentTexture.dispose(); } var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene); this.scene.environmentTexture = environmentTexture; } } if (sceneConfig.debug === true) { this.scene.debugLayer.show(); } else if (sceneConfig.debug === false) { if (this.scene.debugLayer.isVisible()) { this.scene.debugLayer.hide(); } } if (sceneConfig.disableHdr) { this._handleHardwareLimitations(false); } else { this._handleHardwareLimitations(true); } if (sceneConfig.renderInBackground !== undefined) { this._engine.renderEvenInBackground = !!sceneConfig.renderInBackground; } var canvas = this._engine.getRenderingCanvas(); if (canvas) { if (this.camera && sceneConfig.disableCameraControl) { this.camera.detachControl(canvas); } else if (this.camera && sceneConfig.disableCameraControl === false) { this.camera.attachControl(canvas); } } // process mainColor changes: if (sceneConfig.mainColor) { this._configurationContainer.mainColor = this.mainColor || babylonjs_1.Color3.White(); var mc = sceneConfig.mainColor; if (mc.r !== undefined) { this.mainColor.r = mc.r; } if (mc.g !== undefined) { this.mainColor.g = mc.g; } if (mc.b !== undefined) { this.mainColor.b = mc.b; } this.reflectionColor.copyFrom(this.mainColor); var environmentTint = configuration_1.getConfigurationKey("lab.environmentMap.tintLevel", this._globalConfiguration) || 0; // reflection color this.reflectionColor.toLinearSpaceToRef(this.reflectionColor); this.reflectionColor.scaleToRef(1 / this.scene.imageProcessingConfiguration.exposure, this.reflectionColor); var tmpColor3 = babylonjs_1.Color3.Lerp(this._white, this.reflectionColor, environmentTint); this.reflectionColor.copyFrom(tmpColor3); //update the environment, if exists if (this.environmentHelper) { if (this.environmentHelper.groundMaterial) { this.environmentHelper.groundMaterial._perceptualColor = this.mainColor; } if (this.environmentHelper.skyboxMaterial) { this.environmentHelper.skyboxMaterial._perceptualColor = this.mainColor; } } } if (sceneConfig.defaultMaterial) { var conf = sceneConfig.defaultMaterial; if ((conf.materialType === 'standard' && this.scene.defaultMaterial.getClassName() !== 'StandardMaterial') || (conf.materialType === 'pbr' && this.scene.defaultMaterial.getClassName() !== 'PBRMaterial')) { this.scene.defaultMaterial.dispose(); if (conf.materialType === 'standard') { this.scene.defaultMaterial = new babylonjs_1.StandardMaterial("defaultMaterial", this.scene); } else { this.scene.defaultMaterial = new babylonjs_1.PBRMaterial("defaultMaterial", this.scene); } } helper_1.extendClassWithConfig(this.scene.defaultMaterial, conf); } if (sceneConfig.flags) { helper_1.extendClassWithConfig(this.scene, sceneConfig.flags); } this.onSceneConfiguredObservable.notifyObservers({ sceneManager: this, object: this.scene, newConfiguration: sceneConfig }); }; /** * Configure the scene optimizer. * The existing scene optimizer will be disposed and a new one will be created. * @param optimizerConfig the (new) optimizer configuration */ SceneManager.prototype._configureOptimizer = function (optimizerConfig) { var _this = this; if (typeof optimizerConfig === 'boolean') { if (this.sceneOptimizer) { this.sceneOptimizer.stop(); this.sceneOptimizer.dispose(); delete this.sceneOptimizer; } if (optimizerConfig) { this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene); this.sceneOptimizer.start(); } } else { var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration); // check for degradation if (optimizerConfig.degradation) { switch (optimizerConfig.degradation) { case "low": optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate); break; case "moderate": optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate); break; case "hight": optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate); break; } } if (this.sceneOptimizer) { this.sceneOptimizer.stop(); this.sceneOptimizer.dispose(); } if (optimizerConfig.custom) { var customOptimizer_1 = _1.getCustomOptimizerByName(optimizerConfig.custom, optimizerConfig.improvementMode); if (customOptimizer_1) { optimizerOptions.addCustomOptimization(function () { return customOptimizer_1(_this); }, function () { return "Babylon Viewer " + optimizerConfig.custom + " custom optimization"; }); } } this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode); this.sceneOptimizer.start(); } this.onSceneOptimizerConfiguredObservable.notifyObservers({ sceneManager: this, object: this.sceneOptimizer, newConfiguration: optimizerConfig }); }; /** * configure all models using the configuration. * @param modelConfiguration the configuration to use to reconfigure the models */ /*protected _configureModel(modelConfiguration: Partial) { this.models.forEach(model => { model.updateConfiguration(modelConfiguration); }); this.onModelsConfiguredObservable.notifyObservers({ sceneManager: this, object: this.models, newConfiguration: modelConfiguration }); }*/ /** * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured. * @param cameraConfig the new camera configuration * @param model optionally use the model to configure the camera. */ SceneManager.prototype._configureCamera = function (cameraConfig) { var _this = this; if (cameraConfig === void 0) { cameraConfig = {}; } if (!this.scene.activeCamera) { var attachControl = true; if (this._globalConfiguration.scene && this._globalConfiguration.scene.disableCameraControl) { attachControl = false; } this.scene.createDefaultCamera(true, true, attachControl); this.camera = this.scene.activeCamera; this.camera.setTarget(babylonjs_1.Vector3.Zero()); } if (cameraConfig.position) { var newPosition = this.camera.position.clone(); helper_1.extendClassWithConfig(newPosition, cameraConfig.position); this.camera.setPosition(newPosition); } if (cameraConfig.target) { var newTarget = this.camera.target.clone(); helper_1.extendClassWithConfig(newTarget, cameraConfig.target); this.camera.setTarget(newTarget); } /*else if (this.models.length && !cameraConfig.disableAutoFocus) { this._focusOnModel(this.models[0]); }*/ if (cameraConfig.rotation) { this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0); } if (cameraConfig.behaviors) { for (var name_1 in cameraConfig.behaviors) { if (cameraConfig.behaviors[name_1] !== undefined) { this._setCameraBehavior(name_1, cameraConfig.behaviors[name_1]); } } } ; var sceneExtends = this.scene.getWorldExtends(function (mesh) { return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox); }); var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min); var sceneDiagonalLenght = sceneDiagonal.length(); if (isFinite(sceneDiagonalLenght)) this.camera.upperRadiusLimit = sceneDiagonalLenght * 4; else { this.camera.upperRadiusLimit = 10; } // sanity check! if (this.scene.imageProcessingConfiguration) { this.scene.imageProcessingConfiguration.colorCurvesEnabled = true; this.scene.imageProcessingConfiguration.vignetteEnabled = true; this.scene.imageProcessingConfiguration.toneMappingEnabled = !!configuration_1.getConfigurationKey("camera.toneMappingEnabled", this._globalConfiguration); } helper_1.extendClassWithConfig(this.camera, cameraConfig); this.onCameraConfiguredObservable.notifyObservers({ sceneManager: this, object: this.camera, newConfiguration: cameraConfig }); }; SceneManager.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration) { var _this = this; if (!skyboxConifguration && !groundConfiguration) { if (this.environmentHelper) { this.environmentHelper.dispose(); delete this.environmentHelper; } ; } else { var options = { createGround: !!groundConfiguration && this._groundEnabled, createSkybox: !!skyboxConifguration, setupImageProcessing: false, }; // will that cause problems with model ground configuration? /*if (model) { const boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true); const sizeVec = boundingInfo.max.subtract(boundingInfo.min); const halfSizeVec = sizeVec.scale(0.5); const center = boundingInfo.min.add(halfSizeVec); options.groundYBias = -center.y; }*/ if (groundConfiguration) { var groundConfig_1 = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration; var groundSize = groundConfig_1.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale); if (groundSize) { options.groundSize = groundSize; } options.enableGroundShadow = groundConfig_1 === true || groundConfig_1.receiveShadows; if (groundConfig_1.shadowLevel !== undefined) { options.groundShadowLevel = groundConfig_1.shadowLevel; } options.enableGroundMirror = !!groundConfig_1.mirror && this.groundMirrorEnabled; if (groundConfig_1.texture) { options.groundTexture = this.labs.getAssetUrl(groundConfig_1.texture); } if (groundConfig_1.color) { options.groundColor = new babylonjs_1.Color3(groundConfig_1.color.r, groundConfig_1.color.g, groundConfig_1.color.b); } if (groundConfig_1.opacity !== undefined) { options.groundOpacity = groundConfig_1.opacity; } if (groundConfig_1.mirror) { options.enableGroundMirror = true; // to prevent undefines if (typeof groundConfig_1.mirror === "object") { if (groundConfig_1.mirror.amount !== undefined) options.groundMirrorAmount = groundConfig_1.mirror.amount; if (groundConfig_1.mirror.sizeRatio !== undefined) options.groundMirrorSizeRatio = groundConfig_1.mirror.sizeRatio; if (groundConfig_1.mirror.blurKernel !== undefined) options.groundMirrorBlurKernel = groundConfig_1.mirror.blurKernel; if (groundConfig_1.mirror.fresnelWeight !== undefined) options.groundMirrorFresnelWeight = groundConfig_1.mirror.fresnelWeight; if (groundConfig_1.mirror.fallOffDistance !== undefined) options.groundMirrorFallOffDistance = groundConfig_1.mirror.fallOffDistance; if (this._defaultPipelineTextureType !== undefined) options.groundMirrorTextureType = this._defaultPipelineTextureType; } } } var postInitSkyboxMaterial = false; if (skyboxConifguration) { var conf = skyboxConifguration === true ? {} : skyboxConifguration; if (conf.material && conf.material.imageProcessingConfiguration) { options.setupImageProcessing = false; // will be configured later manually. } var skyboxSize = conf.scale; if (skyboxSize) { options.skyboxSize = skyboxSize; } options.sizeAuto = !options.skyboxSize; if (conf.color) { options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b); } if (conf.cubeTexture && conf.cubeTexture.url) { if (typeof conf.cubeTexture.url === "string") { options.skyboxTexture = this.labs.getAssetUrl(conf.cubeTexture.url); } else { // init later! postInitSkyboxMaterial = true; } } if (conf.material) { postInitSkyboxMaterial = true; } } options.setupImageProcessing = false; // TMP if (!this.environmentHelper) { this.environmentHelper = this.scene.createDefaultEnvironment(options); } else { // unlikely, but there might be a new scene! we need to dispose. // get the scene used by the envHelper var scene = this.environmentHelper.rootMesh.getScene(); // is it a different scene? Oh no! if (scene !== this.scene) { this.environmentHelper.dispose(); this.environmentHelper = this.scene.createDefaultEnvironment(options); } else { this.environmentHelper.updateOptions(options); } } if (this.environmentHelper.rootMesh && this._globalConfiguration.scene && this._globalConfiguration.scene.environmentRotationY !== undefined) { this.environmentHelper.rootMesh.rotation.y = this._globalConfiguration.scene.environmentRotationY; } var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration; if (this.environmentHelper.groundMaterial && groundConfig) { this.environmentHelper.groundMaterial._perceptualColor = this.mainColor; if (groundConfig.material) { helper_1.extendClassWithConfig(this.environmentHelper.groundMaterial, groundConfig.material); } if (this.environmentHelper.groundMirror) { var mirrorClearColor = this.environmentHelper.groundMaterial._perceptualColor.toLinearSpace(); // TODO user camera exposure value to set the mirror clear color var exposure = Math.pow(2.0, -this.scene.imageProcessingConfiguration.exposure) * Math.PI; mirrorClearColor.scaleToRef(1 / exposure, mirrorClearColor); this.environmentHelper.groundMirror.clearColor.r = babylonjs_1.Scalar.Clamp(mirrorClearColor.r); this.environmentHelper.groundMirror.clearColor.g = babylonjs_1.Scalar.Clamp(mirrorClearColor.g); this.environmentHelper.groundMirror.clearColor.b = babylonjs_1.Scalar.Clamp(mirrorClearColor.b); this.environmentHelper.groundMirror.clearColor.a = 1; if (!this.groundMirrorEnabled) { this.environmentHelper.groundMaterial.reflectionTexture = null; } } } var skyboxMaterial = this.environmentHelper.skyboxMaterial; if (skyboxMaterial) { skyboxMaterial._perceptualColor = this.mainColor; if (postInitSkyboxMaterial) { if (typeof skyboxConifguration === 'object' && skyboxConifguration.material) { helper_1.extendClassWithConfig(skyboxMaterial, skyboxConifguration.material); } } } } this._observablesManager && this._observablesManager.onModelLoadedObservable.add(function (model) { _this._updateGroundMirrorRenderList(model); }); this.onEnvironmentConfiguredObservable.notifyObservers({ sceneManager: this, object: this.environmentHelper, newConfiguration: { skybox: skyboxConifguration, ground: groundConfiguration } }); }; /** * configure the lights. * * @param lightsConfiguration the (new) light(s) configuration * @param model optionally use the model to configure the camera. */ SceneManager.prototype._configureLights = function (lightsConfiguration) { var _this = this; if (lightsConfiguration === void 0) { lightsConfiguration = {}; } // sanity check! var lightKeys = Object.keys(lightsConfiguration).filter(function (name) { return name !== 'globalRotation'; }); if (!lightKeys.length) { if (!this.scene.lights.length) this.scene.createDefaultLight(true); } else { var lightsAvailable_1 = this.scene.lights.map(function (light) { return light.name; }); // compare to the global (!) configuration object and dispose unneeded: var lightsToConfigure_1 = Object.keys(this._globalConfiguration.lights || []); if (Object.keys(lightsToConfigure_1).length !== lightsAvailable_1.length) { lightsAvailable_1.forEach(function (lName) { if (lightsToConfigure_1.indexOf(lName) === -1) { _this.scene.getLightByName(lName).dispose(); } }); } lightKeys.forEach(function (name, idx) { var lightConfig = { type: 0 }; if (typeof lightsConfiguration[name] === 'object') { lightConfig = lightsConfiguration[name]; } if (typeof lightsConfiguration[name] === 'number') { lightConfig.type = lightsConfiguration[name]; } lightConfig.name = name; var light; // light is not already available if (lightsAvailable_1.indexOf(name) === -1) { var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene); if (!constructor) return; light = constructor(); } else { // available? get it from the scene light = _this.scene.getLightByName(name); if (typeof lightsConfiguration[name] === 'boolean') { lightConfig.type = light.getTypeID(); } lightsAvailable_1 = lightsAvailable_1.filter(function (ln) { return ln !== name; }); if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) { light.dispose(); var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene); if (!constructor) return; light = constructor(); } } // if config set the light to false, dispose it. if (lightsConfiguration[name] === false) { light.dispose(); return; } //enabled var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled; light.setEnabled(enabled); helper_1.extendClassWithConfig(light, lightConfig); //position. Some lights don't support shadows if (light instanceof babylonjs_1.ShadowLight) { // set default values light.shadowMinZ = light.shadowMinZ || 0.2; light.shadowMaxZ = Math.min(10, light.shadowMaxZ || 10); //large far clips reduce shadow depth precision if (lightConfig.target) { if (light.setDirectionToTarget) { var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target); light.setDirectionToTarget(target); } } else if (lightConfig.direction) { var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction); light.direction = direction; } var isShadowEnabled = false; if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) { light.shadowFrustumSize = lightConfig.shadowFrustumSize || 2; isShadowEnabled = true; } else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) { var spotLight = light; if (lightConfig.spotAngle !== undefined) { spotLight.angle = lightConfig.spotAngle * Math.PI / 180; } if (spotLight.angle && lightConfig.shadowFieldOfView) { spotLight.shadowAngleScale = lightConfig.shadowFieldOfView / spotLight.angle; } isShadowEnabled = true; } else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) { if (lightConfig.shadowFieldOfView) { light.shadowAngle = lightConfig.shadowFieldOfView * Math.PI / 180; } isShadowEnabled = true; } var shadowGenerator_1 = light.getShadowGenerator(); if (isShadowEnabled && lightConfig.shadowEnabled && _this._maxShadows) { var bufferSize = lightConfig.shadowBufferSize || 256; if (!shadowGenerator_1) { shadowGenerator_1 = new babylonjs_1.ShadowGenerator(bufferSize, light); } var blurKernel = _this.getBlurKernel(light, bufferSize); shadowGenerator_1.bias = _this._shadowGeneratorBias; shadowGenerator_1.blurKernel = blurKernel; //override defaults helper_1.extendClassWithConfig(shadowGenerator_1, lightConfig.shadowConfig || {}); // add the focues meshes to the shadow list _this._observablesManager && _this._observablesManager.onModelLoadedObservable.add(function (model) { _this._updateShadowRenderList(shadowGenerator_1, model); }); //if (model) { _this._updateShadowRenderList(shadowGenerator_1); //} } else if (shadowGenerator_1) { shadowGenerator_1.dispose(); } } }); // render priority var globalLightsConfiguration_1 = this._globalConfiguration.lights || {}; Object.keys(globalLightsConfiguration_1).sort().forEach(function (name, idx) { var configuration = globalLightsConfiguration_1[name]; var light = _this.scene.getLightByName(name); // sanity check if (!light) return; light.renderPriority = -idx; }); } this.onLightsConfiguredObservable.notifyObservers({ sceneManager: this, object: this.scene.lights, newConfiguration: lightsConfiguration }); }; SceneManager.prototype._updateShadowRenderList = function (shadowGenerator, model, resetList) { var focusMeshes = model ? model.meshes : this.scene.meshes; // add the focues meshes to the shadow list var shadownMap = shadowGenerator.getShadowMap(); if (!shadownMap) return; if (resetList && shadownMap.renderList) { shadownMap.renderList.length = 0; } else { shadownMap.renderList = shadownMap.renderList || []; } for (var index = 0; index < focusMeshes.length; index++) { var mesh = focusMeshes[index]; if (babylonjs_1.Tags.MatchesQuery(mesh, 'castShadow') && shadownMap.renderList.indexOf(mesh) === -1) { shadownMap.renderList.push(mesh); } } if (!this._shadowGroundPlane) { if (shadowGenerator.useBlurCloseExponentialShadowMap) { var shadowGroundPlane = babylonjs_1.Mesh.CreatePlane("shadowGroundPlane", 100, this.scene, false); shadowGroundPlane.useVertexColors = false; //material isn't ever used in rendering, just used to set back face culling shadowGroundPlane.material = new babylonjs_1.StandardMaterial('shadowGroundPlaneMaterial', this.scene); shadowGroundPlane.material.backFaceCulling = false; shadowGroundPlane.rotation.x = Math.PI * 0.5; shadowGroundPlane.freezeWorldMatrix(); this._shadowGroundPlane = shadowGroundPlane; this.scene.removeMesh(shadowGroundPlane); } } else { if (!shadowGenerator.useBlurCloseExponentialShadowMap) { this._shadowGroundPlane.dispose(); this._shadowGroundPlane = null; } } if (this._shadowGroundPlane && shadownMap.renderList.indexOf(this._shadowGroundPlane) === -1) { shadownMap.renderList.push(this._shadowGroundPlane); } }; SceneManager.prototype._updateGroundMirrorRenderList = function (model, resetList) { if (this.environmentHelper.groundMirror && this.environmentHelper.groundMirror.renderList) { var focusMeshes = model ? model.meshes : this.scene.meshes; var renderList = this.environmentHelper.groundMirror.renderList; if (resetList) { renderList.length = 0; } for (var index = 0; index < focusMeshes.length; index++) { var mesh = focusMeshes[index]; if (renderList.indexOf(mesh) === -1) { renderList.push(mesh); } } } }; /** * Gets the shadow map blur kernel according to the light configuration. * @param light The light used to generate the shadows * @param bufferSize The size of the shadow map * @return the kernel blur size */ SceneManager.prototype.getBlurKernel = function (light, bufferSize) { var normalizedBlurKernel = 0.05; // TODO Should come from the config. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) { normalizedBlurKernel = normalizedBlurKernel / light.shadowFrustumSize; } else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) { normalizedBlurKernel = normalizedBlurKernel / light.shadowAngle; } else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) { normalizedBlurKernel = normalizedBlurKernel / (light.angle * light.shadowAngleScale); } var minimumBlurKernel = 5 / (bufferSize / 256); //magic number that aims to keep away sawtooth shadows var blurKernel = Math.max(bufferSize * normalizedBlurKernel, minimumBlurKernel); return blurKernel; }; /** * Alters render settings to reduce features based on hardware feature limitations * @param enableHDR Allows the viewer to run in HDR mode. */ SceneManager.prototype._handleHardwareLimitations = function (enableHDR) { if (enableHDR === void 0) { enableHDR = true; } //flip rendering settings switches based on hardware support var maxVaryingRows = this._engine.getCaps().maxVaryingVectors; var maxFragmentSamplers = this._engine.getCaps().maxTexturesImageUnits; //shadows are disabled if there's not enough varyings for a single shadow if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) { this._maxShadows = 0; } else { this._maxShadows = 3; } //can we render to any >= 16-bit targets (required for HDR) var caps = this._engine.getCaps(); var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering; var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering; this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets); if (linearHalfFloatTargets) { this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT; this._shadowGeneratorBias = 0.002; } else if (linearFloatTargets) { this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT; this._shadowGeneratorBias = 0.001; } else { this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT; this._shadowGeneratorBias = 0.001; } this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT; }; /** * Dispoe the entire viewer including the scene and the engine */ SceneManager.prototype.dispose = function () { // this.onCameraConfiguredObservable.clear(); this.onEnvironmentConfiguredObservable.clear(); this.onLightsConfiguredObservable.clear(); this.onModelsConfiguredObservable.clear(); this.onSceneConfiguredObservable.clear(); this.onSceneInitObservable.clear(); this.onSceneOptimizerConfiguredObservable.clear(); if (this.sceneOptimizer) { this.sceneOptimizer.stop(); this.sceneOptimizer.dispose(); } if (this.environmentHelper) { this.environmentHelper.dispose(); } this.models.forEach(function (model) { model.dispose(); }); if (this._defaultRenderingPipeline) { this._defaultRenderingPipeline.dispose(); } this.models.length = 0; if (this.scene) { this.scene.dispose(); } }; SceneManager.prototype._setCameraBehavior = function (name, behaviorConfig, payload) { var behavior; var type; if (typeof behaviorConfig === 'object') { type = behaviorConfig.type; } else if (typeof behaviorConfig === 'number') { type = behaviorConfig; } else { type = this._cameraBehaviorMapping[name]; } if (type === undefined) return; var config = (typeof behaviorConfig === "object") ? behaviorConfig : {}; var enabled = true; if (typeof behaviorConfig === 'boolean') { enabled = behaviorConfig; } // constructing behavior switch (type) { case 0 /* AUTOROTATION */: this.camera.useAutoRotationBehavior = enabled; behavior = this.camera.autoRotationBehavior; break; case 1 /* BOUNCING */: this.camera.useBouncingBehavior = enabled; behavior = this.camera.bouncingBehavior; break; case 2 /* FRAMING */: this.camera.useFramingBehavior = enabled; behavior = this.camera.framingBehavior; break; default: behavior = null; break; } if (behavior) { this._cameraBehaviorMapping[name] = type; if (typeof behaviorConfig === "object") { helper_1.extendClassWithConfig(behavior, behaviorConfig); } } // post attach configuration. Some functionalities require the attached camera. switch (type) { case 0 /* AUTOROTATION */: break; case 1 /* BOUNCING */: break; case 2 /* FRAMING */: this._observablesManager && this._observablesManager.onModelLoadedObservable.add(function (model) { if (config.zoomOnBoundingInfo) { behavior.zoomOnMeshHierarchy(model.rootMesh); } }); break; } }; return SceneManager; }()); exports.SceneManager = SceneManager; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2NlbmVNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL21hbmFnZXJzL3NjZW5lTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUErakI7QUFDL2pCLGtEQUFtUjtBQUNuUixvREFBK0Q7QUFDL0Qsb0NBQWtEO0FBRWxELGlEQUFnRDtBQUNoRCx5Q0FBZ0U7QUFnQmhFO0lBc0ZJLHNCQUFvQixPQUFlLEVBQVUsdUJBQStDLEVBQVUsbUJBQXdDO1FBQTlJLGlCQXlFQztRQXpFbUIsWUFBTyxHQUFQLE9BQU8sQ0FBUTtRQUFVLDRCQUF1QixHQUF2Qix1QkFBdUIsQ0FBd0I7UUFBVSx3QkFBbUIsR0FBbkIsbUJBQW1CLENBQXFCO1FBakN0SSw4QkFBeUIsR0FBWSxJQUFJLENBQUM7UUFpQmpDLFdBQU0sR0FBRyxrQkFBTSxDQUF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FFO1lBQ1Y7Z0JBQ0ksTUFBTTtZQUNWO2dCQUNJLE1BQU07WUFDVjtnQkFDSSxJQUFJLENBQUMsbUJBQW1CLElBQUksSUFBSSxDQUFDLG1CQUFtQixDQUFDLHVCQUF1QixDQUFDLEdBQUcsQ0FBQyxVQUFDLEtBQUs7b0JBQ25GLElBQUksTUFBTSxDQUFDLGtCQUFrQixFQUFFO3dCQUNULFFBQVMsQ0FBQyxtQkFBbUIsQ0FBQyxLQUFLLENBQUMsUUFBUSxDQUFDLENBQUM7cUJBQ25FO2dCQUNMLENBQUMsQ0FBQyxDQUFDO2dCQUNILE1BQU07U0FDYjtJQUNMLENBQUM7SUFDTCxtQkFBQztBQUFELENBQUMsQUF4MkNELElBdzJDQztBQXgyQ1ksb0NBQVkifQ== /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * The GroupModelAnimation is an implementation of the IModelAnimation interface using BABYLON's * native GroupAnimation class. */ var GroupModelAnimation = /** @class */ (function () { /** * Create a new GroupModelAnimation object using an AnimationGroup object * @param _animationGroup The aniamtion group to base the class on */ function GroupModelAnimation(_animationGroup) { var _this = this; this._animationGroup = _animationGroup; this._state = 0 /* INIT */; this._playMode = 1 /* LOOP */; this._animationGroup.onAnimationEndObservable.add(function () { _this.stop(); _this._state = 4 /* ENDED */; }); } Object.defineProperty(GroupModelAnimation.prototype, "name", { /** * Get the animation's name */ get: function () { return this._animationGroup.name; }, enumerable: true, configurable: true }); Object.defineProperty(GroupModelAnimation.prototype, "state", { /** * Get the current animation's state */ get: function () { return this._state; }, enumerable: true, configurable: true }); Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", { /** * Gets the speed ratio to use for all animations */ get: function () { return this._animationGroup.speedRatio; }, /** * Sets the speed ratio to use for all animations */ set: function (value) { this._animationGroup.speedRatio = value; }, enumerable: true, configurable: true }); Object.defineProperty(GroupModelAnimation.prototype, "frames", { /** * Get the max numbers of frame available in the animation group * * In correlation to an arry, this would be ".length" */ get: function () { return this._animationGroup.to - this._animationGroup.from; }, enumerable: true, configurable: true }); Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", { /** * Get the current frame playing right now. * This can be used to poll the frame currently playing (and, for exmaple, display a progress bar with the data) * * In correlation to an array, this would be the current index */ get: function () { if (this._animationGroup.targetedAnimations[0] && this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0]) { return this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0].currentFrame - this._animationGroup.from; } else { return 0; } }, enumerable: true, configurable: true }); Object.defineProperty(GroupModelAnimation.prototype, "fps", { /** * Get the FPS value of this animation */ get: function () { // get the first currentFrame found for (var i = 0; i < this._animationGroup.animatables.length; ++i) { var animatable = this._animationGroup.animatables[i]; var animations = animatable.getAnimations(); if (!animations || !animations.length) { continue; } for (var idx = 0; idx < animations.length; ++idx) { if (animations[idx].animation && animations[idx].animation.framePerSecond) { return animations[idx].animation.framePerSecond; } } } return 0; }, enumerable: true, configurable: true }); Object.defineProperty(GroupModelAnimation.prototype, "playMode", { /** * What is the animation'S play mode (looping or played once) */ get: function () { return this._playMode; }, /** * Set the play mode. * If the animation is played, it will continue playing at least once more, depending on the new play mode set. * If the animation is not set, the will be initialized and will wait for the user to start playing it. */ set: function (value) { if (value === this._playMode) { return; } this._playMode = value; if (this.state === 1 /* PLAYING */) { this._animationGroup.play(this._playMode === 1 /* LOOP */); } else { this._animationGroup.reset(); this._state = 0 /* INIT */; } }, enumerable: true, configurable: true }); /** * Reset the animation group */ GroupModelAnimation.prototype.reset = function () { this._animationGroup.reset(); }; /** * Restart the animation group */ GroupModelAnimation.prototype.restart = function () { if (this.state === 2 /* PAUSED */) this._animationGroup.restart(); else this.start(); }; /** * * @param frameNumber Go to a specific frame in the animation */ GroupModelAnimation.prototype.goToFrame = function (frameNumber) { this._animationGroup.goToFrame(frameNumber + this._animationGroup.from); }; /** * Start playing the animation. */ GroupModelAnimation.prototype.start = function () { this._animationGroup.start(this.playMode === 1 /* LOOP */, this.speedRatio); if (this._animationGroup.isStarted) { this._state = 1 /* PLAYING */; } }; /** * Pause the animation */ GroupModelAnimation.prototype.pause = function () { this._animationGroup.pause(); this._state = 2 /* PAUSED */; }; /** * Stop the animation. * This will fail silently if the animation group is already stopped. */ GroupModelAnimation.prototype.stop = function () { this._animationGroup.stop(); if (!this._animationGroup.isStarted) { this._state = 3 /* STOPPED */; } }; /** * Dispose this animation object. */ GroupModelAnimation.prototype.dispose = function () { this._animationGroup.dispose(); }; return GroupModelAnimation; }()); exports.GroupModelAnimation = GroupModelAnimation; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kZWxBbmltYXRpb24uanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbW9kZWwvbW9kZWxBbmltYXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUF3SUE7OztHQUdHO0FBQ0g7SUFLSTs7O09BR0c7SUFDSCw2QkFBb0IsZUFBK0I7UUFBbkQsaUJBUUM7UUFSbUIsb0JBQWUsR0FBZixlQUFlLENBQWdCO1FBQy9DLElBQUksQ0FBQyxNQUFNLGVBQXNCLENBQUM7UUFDbEMsSUFBSSxDQUFDLFNBQVMsZUFBeUIsQ0FBQztRQUV4QyxJQUFJLENBQUMsZUFBZSxDQUFDLHdCQUF3QixDQUFDLEdBQUcsQ0FBQztZQUM5QyxLQUFJLENBQUMsSUFBSSxFQUFFLENBQUM7WUFDWixLQUFJLENBQUMsTUFBTSxnQkFBdUIsQ0FBQztRQUN2QyxDQUFDLENBQUMsQ0FBQztJQUNQLENBQUM7SUFLRCxzQkFBVyxxQ0FBSTtRQUhmOztXQUVHO2FBQ0g7WUFDSSxPQUFPLElBQUksQ0FBQyxlQUFlLENBQUMsSUFBSSxDQUFDO1FBQ3JDLENBQUM7OztPQUFBO0lBS0Qsc0JBQVcsc0NBQUs7UUFIaEI7O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QUksQ0FBQyxlQUFlLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDN0IsSUFBSSxDQUFDLE1BQU0saUJBQXdCLENBQUM7SUFDeEMsQ0FBQztJQUVEOzs7T0FHRztJQUNJLGtDQUFJLEdBQVg7UUFDSSxJQUFJLENBQUMsZUFBZSxDQUFDLElBQUksRUFBRSxDQUFDO1FBQzVCLElBQUksQ0FBQyxJQUFJLENBQUMsZUFBZSxDQUFDLFNBQVMsRUFBRTtZQUNqQyxJQUFJLENBQUMsTUFBTSxrQkFBeUIsQ0FBQztTQUN4QztJQUNMLENBQUM7SUFFRDs7T0FFRztJQUNJLHFDQUFPLEdBQWQ7UUFDSSxJQUFJLENBQUMsZUFBZSxDQUFDLE9BQU8sRUFBRSxDQUFDO0lBQ25DLENBQUM7SUFDTCwwQkFBQztBQUFELENBQUMsQUFqTEQsSUFpTEM7QUFqTFksa0RBQW1CIn0= /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var environmentSerializer_1 = __webpack_require__(25); var babylonjs_1 = __webpack_require__(0); var texture_1 = __webpack_require__(12); /** * The ViewerLabs class will hold functions that are not (!) backwards compatible. * The APIs in all labs-related classes and configuration might change. * Once stable, lab features will be moved to the publis API and configuration object. */ var ViewerLabs = /** @class */ (function () { function ViewerLabs(_scene) { this._scene = _scene; this.environment = { //irradiance irradiancePolynomialCoefficients: { x: new babylonjs_1.Vector3(0, 0, 0), y: new babylonjs_1.Vector3(0, 0, 0), z: new babylonjs_1.Vector3(0, 0, 0), xx: new babylonjs_1.Vector3(0, 0, 0), yy: new babylonjs_1.Vector3(0, 0, 0), zz: new babylonjs_1.Vector3(0, 0, 0), yz: new babylonjs_1.Vector3(0, 0, 0), zx: new babylonjs_1.Vector3(0, 0, 0), xy: new babylonjs_1.Vector3(0, 0, 0) }, textureIntensityScale: 1.0 }; } ViewerLabs.prototype.loadEnvironment = function (data, onSuccess, onProgress, onError) { var _this = this; //@! todo: should loadEnvironment cancel any currently loading environments? if (data instanceof ArrayBuffer) { this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(data); if (onSuccess) onSuccess(this.environment); } else if (typeof data === 'string') { var url = this.getAssetUrl(data); this._scene._loadFile(url, function (arrayBuffer) { _this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(arrayBuffer); if (onSuccess) onSuccess(_this.environment); }, function (progressEvent) { if (onProgress) onProgress(progressEvent.loaded, progressEvent.total); }, false, true, function (r, e) { if (onError) { onError(e); } }); } else { //data assumed to be PBREnvironment object this.environment = data; if (onSuccess) onSuccess(data); } }; /** * Applies an `EnvironmentMapConfiguration` to the scene * @param environmentMapConfiguration Environment map configuration to apply */ ViewerLabs.prototype.applyEnvironmentMapConfiguration = function (rotationY) { if (!this.environment) return; //set orientation var rotatquatRotationionY = babylonjs_1.Quaternion.RotationAxis(babylonjs_1.Axis.Y, rotationY || 0); // Add env texture to the scene. if (this.environment.specularTexture) { // IE crashes when disposing the old texture and setting a new one if (!this._scene.environmentTexture) { this._scene.environmentTexture = texture_1.TextureUtils.GetBabylonCubeTexture(this._scene, this.environment.specularTexture, false, true); } if (this._scene.environmentTexture) { this._scene.environmentTexture.level = this.environment.textureIntensityScale; this._scene.environmentTexture.invertZ = true; this._scene.environmentTexture.lodLevelInAlpha = true; var poly = this._scene.environmentTexture.sphericalPolynomial || new babylonjs_1.SphericalPolynomial(); poly.x = this.environment.irradiancePolynomialCoefficients.x; poly.y = this.environment.irradiancePolynomialCoefficients.y; poly.z = this.environment.irradiancePolynomialCoefficients.z; poly.xx = this.environment.irradiancePolynomialCoefficients.xx; poly.xy = this.environment.irradiancePolynomialCoefficients.xy; poly.yy = this.environment.irradiancePolynomialCoefficients.yy; poly.yz = this.environment.irradiancePolynomialCoefficients.yz; poly.zx = this.environment.irradiancePolynomialCoefficients.zx; poly.zz = this.environment.irradiancePolynomialCoefficients.zz; this._scene.environmentTexture.sphericalPolynomial = poly; //set orientation babylonjs_1.Matrix.FromQuaternionToRef(rotatquatRotationionY, this._scene.environmentTexture.getReflectionTextureMatrix()); } } }; /** * Get an environment asset url by using the configuration if the path is not absolute. * @param url Asset url * @returns The Asset url using the `environmentAssetsRootURL` if the url is not an absolute path. */ ViewerLabs.prototype.getAssetUrl = function (url) { var returnUrl = url; if (url && url.toLowerCase().indexOf("//") === -1) { if (!this.assetsRootURL) { // Tools.Warn("Please, specify the root url of your assets before loading the configuration (labs.environmentAssetsRootURL) or disable the background through the viewer options."); return url; } returnUrl = this.assetsRootURL + returnUrl; } return returnUrl; }; ViewerLabs.prototype.rotateShadowLight = function (shadowLight, amount, point, axis, target) { if (point === void 0) { point = babylonjs_1.Vector3.Zero(); } if (axis === void 0) { axis = babylonjs_1.Axis.Y; } if (target === void 0) { target = babylonjs_1.Vector3.Zero(); } axis.normalize(); point.subtractToRef(shadowLight.position, babylonjs_1.Tmp.Vector3[0]); babylonjs_1.Matrix.TranslationToRef(babylonjs_1.Tmp.Vector3[0].x, babylonjs_1.Tmp.Vector3[0].y, babylonjs_1.Tmp.Vector3[0].z, babylonjs_1.Tmp.Matrix[0]); babylonjs_1.Tmp.Matrix[0].invertToRef(babylonjs_1.Tmp.Matrix[2]); babylonjs_1.Matrix.RotationAxisToRef(axis, amount, babylonjs_1.Tmp.Matrix[1]); babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[1], babylonjs_1.Tmp.Matrix[2]); babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[0], babylonjs_1.Tmp.Matrix[2]); babylonjs_1.Tmp.Matrix[2].decompose(babylonjs_1.Tmp.Vector3[0], babylonjs_1.Tmp.Quaternion[0], babylonjs_1.Tmp.Vector3[1]); shadowLight.position.addInPlace(babylonjs_1.Tmp.Vector3[1]); shadowLight.setDirectionToTarget(target); }; return ViewerLabs; }()); exports.ViewerLabs = ViewerLabs; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWx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ENBQUMsQ0FBQyxFQUFFLGVBQUcsQ0FBQyxPQUFPLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQztRQUUzRSxXQUFXLENBQUMsUUFBUSxDQUFDLFVBQVUsQ0FBQyxlQUFHLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFFaEQsV0FBVyxDQUFDLG9CQUFvQixDQUFDLE1BQU0sQ0FBQyxDQUFDO0lBQzdDLENBQUM7SUFFTCxpQkFBQztBQUFELENBQUMsQUFySkQsSUFxSkM7QUFySlksZ0NBQVUifQ== /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var babylonjs_1 = __webpack_require__(0); var texture_1 = __webpack_require__(12); /** * A static class proving methods to aid parsing Spectre environment files */ var EnvironmentDeserializer = /** @class */ (function () { function EnvironmentDeserializer() { } /** * Parses an arraybuffer into a new PBREnvironment object * @param arrayBuffer The arraybuffer of the Spectre environment file * @return a PBREnvironment object */ EnvironmentDeserializer.Parse = function (arrayBuffer) { var environment = { //irradiance irradiancePolynomialCoefficients: { x: new babylonjs_1.Vector3(0, 0, 0), y: new babylonjs_1.Vector3(0, 0, 0), z: new babylonjs_1.Vector3(0, 0, 0), xx: new babylonjs_1.Vector3(0, 0, 0), yy: new babylonjs_1.Vector3(0, 0, 0), zz: new babylonjs_1.Vector3(0, 0, 0), yz: new babylonjs_1.Vector3(0, 0, 0), zx: new babylonjs_1.Vector3(0, 0, 0), xy: new babylonjs_1.Vector3(0, 0, 0) }, //specular textureIntensityScale: 1.0, }; //read .env var littleEndian = false; var magicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36]; var dataView = new DataView(arrayBuffer); var pos = 0; for (var i = 0; i < magicBytes.length; i++) { if (dataView.getUint8(pos++) !== magicBytes[i]) { babylonjs_1.Tools.Error('Not a Spectre environment map'); } } var version = dataView.getUint16(pos, littleEndian); pos += 2; if (version !== 1) { babylonjs_1.Tools.Warn('Unsupported Spectre environment map version "' + version + '"'); } //read json descriptor - collect characters up to null terminator var descriptorString = ''; var charCode = 0x00; while ((charCode = dataView.getUint8(pos++))) { descriptorString += String.fromCharCode(charCode); } var descriptor = JSON.parse(descriptorString); var payloadPos = pos; //irradiance switch (descriptor.irradiance.type) { case 'irradiance_sh_coefficients_9': //irradiance var harmonics = descriptor.irradiance; EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance(harmonics); //harmonics now represent radiance EnvironmentDeserializer._ConvertSHToSP(harmonics, environment.irradiancePolynomialCoefficients); break; default: babylonjs_1.Tools.Error('Unhandled MapType descriptor.irradiance.type (' + descriptor.irradiance.type + ')'); } //specular switch (descriptor.specular.type) { case 'cubemap_faces': var specularDescriptor = descriptor.specular; var specularTexture = environment.specularTexture = new texture_1.TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */); environment.textureIntensityScale = specularDescriptor.multiplier != null ? specularDescriptor.multiplier : 1.0; var mipmaps = specularDescriptor.mipmaps; var imageType = specularDescriptor.imageType; for (var l = 0; l < mipmaps.length; l++) { var faceRanges = mipmaps[l]; specularTexture.source[l] = []; for (var i = 0; i < 6; i++) { var range = faceRanges[i]; var bytes = new Uint8Array(arrayBuffer, payloadPos + range.pos, range.length); switch (imageType) { case 'png': //construct image element from bytes var image = new Image(); var src = URL.createObjectURL(new Blob([bytes], { type: 'image/png' })); image.src = src; specularTexture.source[l][i] = image; break; default: babylonjs_1.Tools.Error('Unhandled ImageType descriptor.specular.imageType (' + imageType + ')'); } } } break; default: babylonjs_1.Tools.Error('Unhandled MapType descriptor.specular.type (' + descriptor.specular.type + ')'); } return environment; }; /** * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation. * L = (1/pi) * E * rho * * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually. * @param harmonics Spherical harmonic coefficients (9) */ EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance = function (harmonics) { EnvironmentDeserializer._ScaleSH(harmonics, 1 / Math.PI); // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied // (The pixel shader must apply albedo after texture fetches, etc). }; /** * Convert spherical harmonics to spherical polynomial coefficients * @param harmonics Spherical harmonic coefficients (9) * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result */ EnvironmentDeserializer._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) { var rPi = 1 / Math.PI; //x outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi; outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi; outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi; outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi; outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi; outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi; outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi; outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi; outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi; //xx outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi; outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi; outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi; outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi; outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi; outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi; outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi; outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi; outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi; //yz outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi; outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi; outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi; outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi; outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi; outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi; outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi; outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi; outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi; }; /** * Multiplies harmonic coefficients in place * @param harmonics Spherical harmonic coefficients (9) * @param scaleFactor Value to multiply by */ EnvironmentDeserializer._ScaleSH = function (harmonics, scaleFactor) { harmonics.l00[0] *= scaleFactor; harmonics.l00[1] *= scaleFactor; harmonics.l00[2] *= scaleFactor; harmonics.l1_1[0] *= scaleFactor; harmonics.l1_1[1] *= scaleFactor; harmonics.l1_1[2] *= scaleFactor; harmonics.l10[0] *= scaleFactor; harmonics.l10[1] *= scaleFactor; harmonics.l10[2] *= scaleFactor; harmonics.l11[0] *= scaleFactor; harmonics.l11[1] *= scaleFactor; harmonics.l11[2] *= scaleFactor; harmonics.l2_2[0] *= scaleFactor; harmonics.l2_2[1] *= scaleFactor; harmonics.l2_2[2] *= scaleFactor; harmonics.l2_1[0] *= scaleFactor; harmonics.l2_1[1] *= scaleFactor; harmonics.l2_1[2] *= scaleFactor; harmonics.l20[0] *= scaleFactor; harmonics.l20[1] *= scaleFactor; harmonics.l20[2] *= scaleFactor; harmonics.l21[0] *= scaleFactor; harmonics.l21[1] *= scaleFactor; harmonics.l21[2] *= scaleFactor; harmonics.l22[0] *= scaleFactor; harmonics.l22[1] *= scaleFactor; harmonics.l22[2] *= scaleFactor; }; return EnvironmentDeserializer; }()); exports.EnvironmentDeserializer = EnvironmentDeserializer; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW52aXJvbm1lbnRTZXJpYWxpemVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2xhYnMvZW52aXJvbm1lbnRTZXJpYWxpemVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQTJDO0FBQzNDLHFDQUFnRTtBQW1IaEU7O0dBRUc7QUFDSDtJQUFBO0lBcU5BLENBQUM7SUFuTkc7Ozs7T0FJRztJQUNXLDZCQUFLLEdBQW5CLFVBQW9CLFdBQXdCO1FBQ3hDLElBQUksV0FBVyxHQUFtQjtZQUM5QixZQUFZO1lBQ1osZ0NBQWdDLEVBQUU7Z0JBQzlCLENBQUMsRUFBRSxJQUFJLG1CQUFPLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUM7Z0JBQ3ZCLENBQUMsRUFBRSxJQUFJLG1CQUFPLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUM7Z0JBQ3ZCLENBQUMsRUFBRSxJQUFJLG1CQUFPLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUM7Z0JBQ3ZCLEVBQUUsRUFBRSxJQUFJLG1CQUFPLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUM7Z0JBQ3hCLEVBQUUsRUFBRSxJQUFJLG1CQUFPLENBQUMsQ0FBQyxFQUFFLENBQUM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QUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztRQUNoQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztJQUNwQyxDQUFDO0lBQ0wsOEJBQUM7QUFBRCxDQUFDLEFBck5ELElBcU5DO0FBck5ZLDBEQUF1QiJ9 /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var extended_1 = __webpack_require__(27); var cache = {}; /** * * @param name the name of the custom optimizer configuration * @param upgrade set to true if you want to upgrade optimizer and false if you want to degrade */ function getCustomOptimizerByName(name, upgrade) { if (!cache[name]) { switch (name) { case 'extended': if (upgrade) { return extended_1.extendedUpgrade; } else { return extended_1.extendedDegrade; } } } return cache[name]; } exports.getCustomOptimizerByName = getCustomOptimizerByName; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvb3B0aW1pemVyL2N1c3RvbS9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUE4RDtBQUc5RCxJQUFNLEtBQUssR0FBK0QsRUFBRSxDQUFDO0FBRTdFOzs7O0dBSUc7QUFDSCxrQ0FBeUMsSUFBWSxFQUFFLE9BQWlCO0lBQ3BFLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLEVBQUU7UUFDZCxRQUFRLElBQUksRUFBRTtZQUNWLEtBQUssVUFBVTtnQkFDWCxJQUFJLE9BQU8sRUFBRTtvQkFDVCxPQUFPLDBCQUFlLENBQUM7aUJBQzFCO3FCQUNJO29CQUNELE9BQU8sMEJBQWUsQ0FBQztpQkFDMUI7U0FDUjtLQUNKO0lBRUQsT0FBTyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUM7QUFDdkIsQ0FBQztBQWRELDREQWNDIn0= /***/ }), /* 27 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var babylonjs_1 = __webpack_require__(0); /** * A custom upgrade-oriented function configuration for the scene optimizer. * * @param viewer the viewer to optimize */ function extendedUpgrade(sceneManager) { var defaultPipeline = sceneManager.defaultRenderingPipeline; // if (!this.Scene.BackgroundHelper) { // this.Scene.EngineScene.autoClear = false; // this.Scene.BackgroundHelper = true; // Would require a dedicated clear color; // return false; // } if (sceneManager.scene.getEngine().getHardwareScalingLevel() > 1) { var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() - 0.25, 0, 1); sceneManager.scene.getEngine().setHardwareScalingLevel(scaling); return false; } if (!sceneManager.scene.postProcessesEnabled) { sceneManager.scene.postProcessesEnabled = true; return false; } if (!sceneManager.groundEnabled) { sceneManager.groundEnabled = true; return false; } if (defaultPipeline && !sceneManager.fxaaEnabled) { sceneManager.fxaaEnabled = true; return false; } var hardwareScalingLevel = Math.max(1 / 2, 1 / (window.devicePixelRatio || 2)); if (sceneManager.scene.getEngine().getHardwareScalingLevel() > hardwareScalingLevel) { var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() - 0.25, 0, hardwareScalingLevel); sceneManager.scene.getEngine().setHardwareScalingLevel(scaling); return false; } if (!sceneManager.processShadows) { sceneManager.processShadows = true; return false; } if (defaultPipeline && !sceneManager.bloomEnabled) { sceneManager.bloomEnabled = true; return false; } if (!sceneManager.groundMirrorEnabled) { sceneManager.groundMirrorEnabled = true; return false; } return true; } exports.extendedUpgrade = extendedUpgrade; /** * A custom degrade-oriented function configuration for the scene optimizer. * * @param viewer the viewer to optimize */ function extendedDegrade(sceneManager) { var defaultPipeline = sceneManager.defaultRenderingPipeline; if (sceneManager.groundMirrorEnabled) { sceneManager.groundMirrorEnabled = false; return false; } if (defaultPipeline && sceneManager.bloomEnabled) { sceneManager.bloomEnabled = false; return false; } if (sceneManager.processShadows) { sceneManager.processShadows = false; return false; } if (sceneManager.scene.getEngine().getHardwareScalingLevel() < 1) { var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() + 0.25, 0, 1); sceneManager.scene.getEngine().setHardwareScalingLevel(scaling); return false; } if (defaultPipeline && sceneManager.fxaaEnabled) { sceneManager.fxaaEnabled = false; return false; } if (sceneManager.groundEnabled) { sceneManager.groundEnabled = false; return false; } if (sceneManager.scene.postProcessesEnabled) { sceneManager.scene.postProcessesEnabled = false; return false; } if (sceneManager.scene.getEngine().getHardwareScalingLevel() < 1.25) { var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() + 0.25, 0, 1.25); sceneManager.scene.getEngine().setHardwareScalingLevel(scaling); return false; } // if (this.Scene.BackgroundHelper) { // this.Scene.EngineScene.autoClear = true; // this.Scene.BackgroundHelper = false; // Would require a dedicated clear color; // return false; // } return true; } exports.extendedDegrade = extendedDegrade; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvb3B0aW1pemVyL2N1c3RvbS9leHRlbmRlZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUFvRTtBQUdwRTs7OztHQUlHO0FBQ0gseUJBQWdDLFlBQTBCO0lBQ3RELElBQUksZUFBZSxHQUE2QixZQUFZLENBQUMsd0JBQXdCLENBQUM7SUFDdEYsc0NBQXNDO0lBQ3RDLDZDQUE2QztJQUM3QyxzQ0FBc0M7SUFD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DLG9CQUFvQixHQUFHLEtBQUssQ0FBQztRQUNoRCxPQUFPLEtBQUssQ0FBQztLQUNoQjtJQUNELElBQUksWUFBWSxDQUFDLEtBQUssQ0FBQyxTQUFTLEVBQUUsQ0FBQyx1QkFBdUIsRUFBRSxHQUFHLElBQUksRUFBRTtRQUNqRSxJQUFJLE9BQU8sR0FBRyxrQkFBTSxDQUFDLEtBQUssQ0FBQyxZQUFZLENBQUMsS0FBSyxDQUFDLFNBQVMsRUFBRSxDQUFDLHVCQUF1QixFQUFFLEdBQUcsSUFBSSxFQUFFLENBQUMsRUFBRSxJQUFJLENBQUMsQ0FBQztRQUNyRyxZQUFZLENBQUMsS0FBSyxDQUFDLFNBQVMsRUFBRSxDQUFDLHVCQUF1QixDQUFDLE9BQU8sQ0FBQyxDQUFDO1FBQ2hFLE9BQU8sS0FBSyxDQUFDO0tBQ2hCO0lBQ0QscUNBQXFDO0lBQ3JDLDRDQUE0QztJQUM1Qyx1Q0FBdUM7SUFDdkMseUNBQXlDO0lBQ3pDLGdCQUFnQjtJQUNoQixJQUFJO0lBQ0osT0FBTyxJQUFJLENBQUM7QUFDaEIsQ0FBQztBQTVDRCwwQ0E0Q0MifQ== /***/ }), /* 28 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var mappers_1 = __webpack_require__(3); var types_1 = __webpack_require__(29); var configurationCompatibility_1 = __webpack_require__(53); var _1 = __webpack_require__(1); var babylonjs_1 = __webpack_require__(0); /** * The configuration loader will load the configuration object from any source and will use the defined mapper to * parse the object and return a conform ViewerConfiguration. * It is a private member of the scene. */ var ConfigurationLoader = /** @class */ (function () { function ConfigurationLoader(_enableCache) { if (_enableCache === void 0) { _enableCache = false; } this._enableCache = _enableCache; this._configurationCache = {}; this._loadRequests = []; } /** * load a configuration object that is defined in the initial configuration provided. * The viewer configuration can extend different types of configuration objects and have an extra configuration defined. * * @param initConfig the initial configuration that has the definitions of further configuration to load. * @param callback an optional callback that will be called sync, if noconfiguration needs to be loaded or configuration is payload-only * @returns A promise that delivers the extended viewer configuration, when done. */ ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) { var _this = this; if (initConfig === void 0) { initConfig = {}; } var loadedConfig = _1.deepmerge({}, initConfig); var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || ""); if (loadedConfig.configuration) { var mapperType_1 = "json"; return Promise.resolve().then(function () { if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) { // a file to load var url = ''; if (typeof loadedConfig.configuration === "string") { url = loadedConfig.configuration; } // if configuration is an object if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) { url = loadedConfig.configuration.url; var type = loadedConfig.configuration.mapper; // empty string? if (!type) { // load mapper type from filename / url type = loadedConfig.configuration.url.split('.').pop(); } mapperType_1 = type || mapperType_1; } return _this._loadFile(url); } else { if (typeof loadedConfig.configuration === "object") { mapperType_1 = loadedConfig.configuration.mapper || mapperType_1; return loadedConfig.configuration.payload || {}; } return {}; } }).then(function (data) { var mapper = mappers_1.mapperManager.getMapper(mapperType_1); var parsed = _1.deepmerge(mapper.map(data), loadedConfig); var merged = _1.deepmerge(extendedConfiguration, parsed); configurationCompatibility_1.processConfigurationCompatibility(merged); if (callback) callback(merged); return merged; }); } else { loadedConfig = _1.deepmerge(extendedConfiguration, loadedConfig); configurationCompatibility_1.processConfigurationCompatibility(loadedConfig); if (callback) callback(loadedConfig); return Promise.resolve(loadedConfig); } }; /** * Dispose the configuration loader. This will cancel file requests, if active. */ ConfigurationLoader.prototype.dispose = function () { this._loadRequests.forEach(function (request) { request.abort(); }); this._loadRequests.length = 0; }; ConfigurationLoader.prototype._loadFile = function (url) { var _this = this; var cacheReference = this._configurationCache; if (this._enableCache && cacheReference[url]) { return Promise.resolve(cacheReference[url]); } return new Promise(function (resolve, reject) { var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) { var idx = _this._loadRequests.indexOf(fileRequest); if (idx !== -1) _this._loadRequests.splice(idx, 1); if (_this._enableCache) cacheReference[url] = result; resolve(result); }, undefined, undefined, false, function (request, error) { var idx = _this._loadRequests.indexOf(fileRequest); if (idx !== -1) _this._loadRequests.splice(idx, 1); reject(error); }); _this._loadRequests.push(fileRequest); }); }; return ConfigurationLoader; }()); exports.ConfigurationLoader = ConfigurationLoader; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibG9hZGVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2NvbmZpZ3VyYXRpb24vbG9hZGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEscUNBQTBDO0FBRTFDLGlDQUErQztBQUMvQywyRUFBaUY7QUFFakYsK0JBQXVDO0FBQ3ZDLHVDQUFnRDtBQUVoRDs7OztHQUlHO0FBQ0g7SUFNSSw2QkFBb0IsWUFBNkI7UUFBN0IsNkJBQUEsRUFBQSxvQkFBNkI7UUFBN0IsaUJBQVksR0FBWixZQUFZLENBQWlCO1FBQzdDLElBQUksQ0FBQyxtQkFBbUIsR0FBRyxFQUFFLENBQUM7UUFDOUIsSUFBSSxDQUFDLGFBQWEsR0FBRyxFQUFFLENBQUM7SUFDNUIsQ0FBQztJQUVEOzs7Ozs7O09BT0c7SUFDSSwrQ0FBaUIsR0FBeEIsVUFBeUIsVUFBb0MsRUFBRSxRQUFnRDtRQUEvRyxpQkFvREM7UUFwRHdCLDJCQUFBLEVBQUEsZUFBb0M7UUFFekQsSUFBSSxZQUFZLEdBQXdCLFlBQVMsQ0FBQyxFQUFFLEVBQUUsVUFBVSxDQUFDLENBQUM7UUFFbEUsSUFBSSxxQkFBcUIsR0FBRyw0QkFBb0IsQ0FBQyxZQUFZLENBQUMsT0FBTyxJQUFJLEVBQUUsQ0FBQyxDQUFDO1FBRTdFLElBQUksWUFBWSxDQUFDLGFBQWEsRUFBRTtZQUU1QixJQUFJLFlBQVUsR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csR0FBRyxLQUFJLENBQUMsYUFBYSxDQUFDLE9BQU8sQ0FBQyxXQUFXLENBQUMsQ0FBQztnQkFDbEQsSUFBSSxHQUFHLEtBQUssQ0FBQyxDQUFDO29CQUNWLEtBQUksQ0FBQyxhQUFhLENBQUMsTUFBTSxDQUFDLEdBQUcsRUFBRSxDQUFDLENBQUMsQ0FBQztnQkFDdEMsTUFBTSxDQUFDLEtBQUssQ0FBQyxDQUFDO1lBQ2xCLENBQUMsQ0FBQyxDQUFDO1lBQ0gsS0FBSSxDQUFDLGFBQWEsQ0FBQyxJQUFJLENBQUMsV0FBVyxDQUFDLENBQUM7UUFDekMsQ0FBQyxDQUFDLENBQUM7SUFDUCxDQUFDO0lBRUwsMEJBQUM7QUFBRCxDQUFDLEFBMUdELElBMEdDO0FBMUdZLGtEQUFtQiJ9 /***/ }), /* 29 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var minimal_1 = __webpack_require__(30); exports.minimalConfiguration = minimal_1.minimalConfiguration; var default_1 = __webpack_require__(49); exports.defaultConfiguration = default_1.defaultConfiguration; var extended_1 = __webpack_require__(50); var shadowLight_1 = __webpack_require__(51); var environmentMap_1 = __webpack_require__(52); var _1 = __webpack_require__(1); /** * Get the configuration type you need to use as the base for your viewer. * The types can either be a single string, or comma separated types that will extend each other. for example: * * "default, environmentMap" will first load the default configuration and will extend it using the environmentMap configuration. * * @param types a comma-separated string of the type(s) or configuration to load. */ var getConfigurationType = function (types) { var config = {}; var typesSeparated = types.split(","); typesSeparated.forEach(function (type) { switch (type.trim()) { case 'environmentMap': config = _1.deepmerge(config, environmentMap_1.environmentMapConfiguration); break; case 'shadowDirectionalLight': config = _1.deepmerge(config, shadowLight_1.shadowDirectionalLightConfiguration); break; case 'shadowSpotLight': config = _1.deepmerge(config, shadowLight_1.shadowSpotlLightConfiguration); break; case 'extended': config = _1.deepmerge(config, extended_1.extendedConfiguration); break; case 'minimal': config = _1.deepmerge(config, minimal_1.minimalConfiguration); break; case 'none': break; case 'default': default: config = _1.deepmerge(config, default_1.defaultConfiguration); break; } if (config.extends) { config = _1.deepmerge(config, getConfigurationType(config.extends)); } }); return config; }; exports.getConfigurationType = getConfigurationType; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHFDQUFpRDtBQW9ESSwrQkFwRDVDLDhCQUFvQixDQW9ENEM7QUFuRHpFLHFDQUFpRDtBQW1EbEIsK0JBbkR0Qiw4QkFBb0IsQ0FtRHNCO0FBbERuRCx1Q0FBbUQ7QUFFbkQsNkNBQW1HO0FBQ25HLG1EQUErRDtBQUMvRCxrQ0FBMEM7QUFFMUM7Ozs7Ozs7R0FPRztBQUNILElBQUksb0JBQW9CLEdBQUcsVUFBVSxLQUFhO0lBQzlDLElBQUksTUFBTSxHQUF3QixFQUFFLENBQUM7SUFDckMsSUFBSSxjQUFjLEdBQUcsS0FBSyxDQUFDLEtBQUssQ0FBQyxHQUFHLENBQUMsQ0FBQztJQUN0QyxjQUFjLENBQUMsT0FBTyxDQUFDLFVBQUEsSUFBSTtRQUN2QixRQUFRLElBQUksQ0FBQyxJQUFJLEVBQUUsRUFBRTtZQUNqQixLQUFLLGdCQUFnQjtnQkFDakIsTUFBTSxHQUFHLFlBQVMsQ0FBQyxNQUFNLEVBQUUsNENBQTJCLENBQUMsQ0FBQztnQkFDeEQsTUFBTTtZQUNWLEtBQUssd0JBQXdCO2dCQUN6QixNQUFNLEdBQUcsWUFBUyxDQUFDLE1BQU0sRUFBRSxpREFBbUMsQ0FBQyxDQUFDO2dCQUNoRSxNQUFNO1lBQ1YsS0FBSyxpQkFBaUI7Z0JBQ2xCLE1BQU0sR0FBRyxZQUFTLENBQUMsTUFBTSxFQUFFLDJDQUE2QixDQUFDLENBQUM7Z0JBQzFELE1BQU07WUFDVixLQUFLLFVBQVU7Z0JBQ1gsTUFBTSxHQUFHLFlBQVMsQ0FBQyxNQUFNLEVBQUUsZ0NBQXFCLENBQUMsQ0FBQztnQkFDbEQsTUFBTTtZQUNWLEtBQUssU0FBUztnQkFDVixNQUFNLEdBQUcsWUFBUyxDQUFDLE1BQU0sRUFBRSw4QkFBb0IsQ0FBQyxDQUFDO2dCQUNqRCxNQUFNO1lBQ1YsS0FBSyxNQUFNO2dCQUNQLE1BQU07WUFDVixLQUFLLFNBQVMsQ0FBQztZQUNmO2dCQUNJLE1BQU0sR0FBRyxZQUFTLENBQUMsTUFBTSxFQUFFLDhCQUFvQixDQUFDLENBQUM7Z0JBQ2pELE1BQU07U0FDYjtRQUVELElBQUksTUFBTSxDQUFDLE9BQU8sRUFBRTtZQUNoQixNQUFNLEdBQUcsWUFBUyxDQUFDLE1BQU0sRUFBRSxvQkFBb0IsQ0FBQyxNQUFNLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FBQztTQUNwRTtJQUNMLENBQUMsQ0FBQyxDQUFDO0lBQ0gsT0FBTyxNQUFNLENBQUM7QUFFbEIsQ0FBQyxDQUFBO0FBRVEsb0RBQW9CIn0= /***/ }), /* 30 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var babylonjs_viewer_assets_1 = __webpack_require__(2); var babylonjs_viewer_assets_2 = __webpack_require__(2); /** * The minimal configuration needed to make the viewer work. * Some functionalities might not work correctly (like fill-screen) */ exports.minimalConfiguration = { version: "0.1", templates: { main: { html: babylonjs_viewer_assets_1.defaultTemplate }, fillContainer: { html: babylonjs_viewer_assets_1.fillContainer, params: { disable: false } }, loadingScreen: { html: babylonjs_viewer_assets_1.loadingScreen, params: { backgroundColor: "#000000", loadingImage: babylonjs_viewer_assets_2.loading } }, viewer: { html: babylonjs_viewer_assets_1.defaultViewer, }, overlay: { html: babylonjs_viewer_assets_1.overlay, params: { closeImage: babylonjs_viewer_assets_2.close, closeText: 'Close' } }, error: { html: babylonjs_viewer_assets_1.error } }, engine: { antialiasing: true } }; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWluaW1hbC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL3R5cGVzL21pbmltYWwudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSxtRUFBdUg7QUFDdkgsbUVBQXlEO0FBRXpEOzs7R0FHRztBQUNRLFFBQUEsb0JBQW9CLEdBQXdCO0lBQ25ELE9BQU8sRUFBRSxLQUFLO0lBQ2QsU0FBUyxFQUFFO1FBQ1AsSUFBSSxFQUFFO1lBQ0YsSUFBSSxFQUFFLHlDQUFlO1NBQ3hCO1FBQ0QsYUFBYSxFQUFFO1lBQ1gsSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixPQUFPLEVBQUUsS0FBSzthQUNqQjtTQUNKO1FBQ0QsYUFBYSxFQUFFO1lBQ1gsSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixlQUFlLEVBQUUsU0FBUztnQkFDMUIsWUFBWSxFQUFFLGlDQUFPO2FBQ3hCO1NBQ0o7UUFDRCxNQUFNLEVBQUU7WUFDSixJQUFJLEVBQUUsdUNBQWE7U0FDdEI7UUFDRCxPQUFPLEVBQUU7WUFDTCxJQUFJLEVBQUUsaUNBQU87WUFDYixNQUFNLEVBQUU7Z0JBQ0osVUFBVSxFQUFFLCtCQUFLO2dCQUNqQixTQUFTLEVBQUUsT0FBTzthQUNyQjtTQUNKO1FBQ0QsS0FBSyxFQUFFO1lBQ0gsSUFBSSxFQUFFLCtCQUFLO1NBQ2Q7S0FFSjtJQUNELE1BQU0sRUFBRTtRQUNKLFlBQVksRUFBRSxJQUFJO0tBQ3JCO0NBQ0osQ0FBQSJ9 /***/ }), /* 31 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.babylonFont = __webpack_require__(32); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9udC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9hc3NldHMvZm9udC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFhLFFBQUEsV0FBVyxHQUFHLE9BQU8sQ0FBQywyQkFBMkIsQ0FBQyxDQUFDIn0= /***/ }), /* 32 */ /***/ (function(module, exports) { module.exports = "data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAABIgAA8AAAAAH7gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABPUy8yAAABWAAAAEcAAABgSlp9rlZETVgAAAGgAAACBQAABeCBXolxY21hcAAAA6gAAABxAAAAsqyRvzljdnQgAAAEHAAAACAAAAAqCdkJr2ZwZ20AAAQ8AAAA8AAAAVn8nuaOZ2FzcAAABSwAAAAMAAAADAAIABtnbHlmAAAFOAAABlUAAAh+MHVDHWhlYWQAAAuQAAAAMgAAADb+LvI4aGhlYQAAC8QAAAAVAAAAJBABCAZobXR4AAAL3AAAACYAAAAqErQDvGxvY2EAAAwEAAAAIgAAACIJ6we4bWF4cAAADCgAAAAcAAAAIACJANFuYW1lAAAMRAAABTsAAAvzM/OUeXBvc3QAABGAAAAAEwAAACD/UQB3cHJlcAAAEZQAAACJAAAA03i98g542mNgZk9knMDAysDBOovVmIGBURpCM19kSGMS4mBl5WJkYgQDBiAQYEAA32AFBQYHBt7vwhxgPoRkAKtjgfAUGBgAoqoGywB42hXJUxQYBgAEwclf2qa2bdu2bdu2bdu2bdu2bTtlur15734WAwz4fwYZPHCIgWGoMHQYJqqD+mHDcGH4MEIYMYw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MXiNzO1ZobaqvKwKG9nTs12EFPBsTiifCw0JAEsXidzbXlhUEsPh0VGREeEItfTkKYjwPEEuDj4WRnAbEEwQDEEtowoSDAAMhi2M4IN5oJbjQz3GgWuNGscKPZ5CShRrPDjeaAG80JN3qTMCO79gYGBdfaTAkXAMQBKBoAAAA=" /***/ }), /* 33 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.babylonLogo = __webpack_require__(34); exports.close = __webpack_require__(35); exports.fullscreen = __webpack_require__(36); exports.helpCircle = __webpack_require__(37); exports.loading = __webpack_require__(38); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW1nLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2Fzc2V0cy9pbWcudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBYSxRQUFBLFdBQVcsR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQztBQUNuRSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsNEJBQTRCLENBQUMsQ0FBQztBQUM5QyxRQUFBLFVBQVUsR0FBRyxPQUFPLENBQUMsaUNBQWlDLENBQUMsQ0FBQztBQUN4RCxRQUFBLFVBQVUsR0FBRyxPQUFPLENBQUMsa0NBQWtDLENBQUMsQ0FBQztBQUN6RCxRQUFBLE9BQU8sR0FBRyxPQUFPLENBQUMsOEJBQThCLENBQUMsQ0FBQyJ9 /***/ }), /* 34 */ /***/ (function(module, exports) { module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB7MAAAgHCAYAAABZmyd0AAAACXBIWXMAAC4jAAAuIwF4pT92AAAgAElEQVR42uzd7XEb6Zm24Wtc+5/IgO0IyDcCtiMQNwLBEYgTgaAIhhOBpQhMRSAwghEjWCoCixHw/fE0DIKiKAIE+vM4qlDi1I531/fYRDdOPHf/dn9/HwAAAAA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P/HitsAAAAABgQZTYAAEO1TnL6i79ml/27sG9EBgAAAADDocwGAGCo3qQU2icP/HfX2Z8SBwAAAAAGSJkNAMCQnSX5evefrbABAAAAoCLKbAAAhu5dkkmssAEAAACgKv8F3qtfY+YVvDIAAAAASUVORK5CYII=" /***/ }), /* 35 */ /***/ (function(module, exports) { module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC" /***/ }), /* 36 */ /***/ (function(module, exports) { module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII=" /***/ }), /* 37 */ /***/ (function(module, exports) { module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAB/ElEQVR42u3Xs4JdQRzH8X9sqYrNNnbqtPELxKgWD7AsI71B7BcI21W9rNa+d27zjSac/5kzZ2J8yqPfGUn++xMwis2UcpsGuilQoJt6blHCJkbKt2I+FbSRpJVy5kos5nAVQxrDJWbFfP4wXYTqYL9kwRiuk9VFRksYJvKEGA+ZEPb3+udrOcNaJjGJtZyhTo8IKIVaOXmOMfKrrnsCo1WU+HFE/fxu9dk9asR+f8fswnU08fmTuDo8nZarat2P/DjobtFPP3dY8bGi6jNUE/MxuM58vNsFVvfHiHNqleqjmwo0a+zdW3zutr26Dk2ZPqW1oZli7/fzuT57dQqaFmUaZDNZ9HoDYIMbUEoWt+xb69EVuwG3CdfNcvtWNbqbbkB9ePVgK4DFDKGrcwO6CNPHJvvGdGpI0uEGGELk2WGfn8or33OxAUc/TulP8cnHVVENI5Vhp+mIa+TT9tm9pKkN7ab6tHEDRVo3LUGjTxuNpClyAzaRSiwGSbPeDRhJC99Ls7rno5zvpUw0zMMQQV1wdFzmezgvSZhJR1Aj+3QyW5Jx8JsD9okfV74p4ELIceNudMAjRodtfh8T4yETg7fvEf3pAqMlCw7QQah29kl2zOIiedLkOc9MicVcymkhSQtlzJVvxUg2UMxNaunCYOiihpsUsZ6R8t8f4DUz8hFGPnrb0AAAAABJRU5ErkJggg==" /***/ }), /* 38 */ /***/ (function(module, exports) { module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAStUlEQVR42uyaA7TrShiFn23btm3btm3btm3btm372LWd9+318nSRNk2mtz3trLXX5PbmZOafPT9nxmq1VmuKFggEZs1ms0uVSqUj8vn8Q/SP5nK5lRpMjFYLh8NTZTKZhSBxi2KxeDlEPgh+BQVrhKbfwDNgZf45QZ2J0mrxeHxGtHJRCDoUQm+FpLd4joKc5aKJaDbDNzxuZT3yyLg1FqPVWPip0un0PBCxMUScD+6wtTJr+dz49hdsmh14nMiAKK0WiUSmgbjFC4XCYSz2VeB9/p2wyaxJK9EY93set+dxwhYr1QU9U7B4s4CNIfMM+pvAzyBm1VFjPl+D3cDELdacyVy4kMsdLBMrX0kf4beM1QCt9Ff7hY14nGRpWiIHBgYmU+BDwLMRi3EMJN4KpJUBa5g05OlHthORc4amIJXgZ30EPtXWyiHITFtN0JBziDz6DB6nHtYEI+i04BZQtJqwIfcAOBXM0hCEdXR0TM1k5ydV2Iv+CLTyeXbqgWeeeeY4DmnMOGjxTrw/aDVpkxtirW7Bos09xkns6+ublAlNA3Gr4S+3JCe4ksk9YO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ssRXgpzAp1vVYjodv39cYCdspILRaGjUsf/gHJaAWdrW+QG0Rv/QrFbPHSBywngFzzDeiEkB2zovybktEch90C9wcI/zQjSelhUQ3DJTkpdrCxwD+IJroCvCdPXnMAg2PLfDU6qoF/eX6TZVl8Lclzax0dsyrVqBpO4pqAQHcDecz3EvxQwkI16kGkp9m0v2ljxoU/UGfElBUCxYCMK/HKejMj5LpRriWVx1yNIgfmhyz+83U4WzFvDsAZUa1yYwfcLAh4P3kwI+S6RMybBcrHjKg8XQshTiOZESR+bS+prONUK1niITtvezTcAGYEid2zasSpGUY1ekSztpgRcpHpsK5co1er1YRDu6DelsCMOL5d6DmVo78FBgRzcRy+pgTzFeiqVq1Ki43KZo0b/wP23paVqC/D3gAAAABJRU5ErkJggg==" /***/ }), /* 39 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.defaultTemplate = __webpack_require__(40); exports.defaultViewer = __webpack_require__(41); exports.error = __webpack_require__(42); exports.fillContainer = __webpack_require__(43); exports.help = __webpack_require__(44); exports.loadingScreen = __webpack_require__(45); exports.navbar = __webpack_require__(46); exports.overlay = __webpack_require__(47); exports.share = __webpack_require__(48); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVtcGxhdGVzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2Fzc2V0cy90ZW1wbGF0ZXMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBYSxRQUFBLGVBQWUsR0FBRyxPQUFPLENBQUMscURBQXFELENBQUMsQ0FBQztBQUNqRixRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQztBQUM3RCxRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLElBQUksR0FBRyxPQUFPLENBQUMsMENBQTBDLENBQUMsQ0FBQztBQUMzRCxRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLE1BQU0sR0FBRyxPQUFPLENBQUMsNENBQTRDLENBQUMsQ0FBQztBQUMvRCxRQUFBLE9BQU8sR0FBRyxPQUFPLENBQUMsNkNBQTZDLENBQUMsQ0FBQztBQUNqRSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQyJ9 /***/ }), /* 40 */ /***/ (function(module, exports) { module.exports = " {{#if fillScreen}} {{/if}} "; /***/ }), /* 41 */ /***/ (function(module, exports) { module.exports = " "; /***/ }), /* 42 */ /***/ (function(module, exports) { module.exports = "Error loading the model"; /***/ }), /* 43 */ /***/ (function(module, exports) { module.exports = " {{#unless disable}} {{/unless}} "; /***/ }), /* 44 */ /***/ (function(module, exports) { module.exports = "HELP"; /***/ }), /* 45 */ /***/ (function(module, exports) { module.exports = " "; /***/ }), /* 46 */ /***/ (function(module, exports) { module.exports = " {{#if (or (not animations) hideAnimations)}} {{#if hideLogo}} {{else}} {{/if}} {{/if}} {{#if disableOnFullscreen}} {{/if}} "; /***/ }), /* 47 */ /***/ (function(module, exports) { module.exports = "
{{closeText}}
"; /***/ }), /* 48 */ /***/ (function(module, exports) { module.exports = "SHARE"; /***/ }), /* 49 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var babylonjs_viewer_assets_1 = __webpack_require__(2); var babylonjs_viewer_assets_2 = __webpack_require__(2); var images = __webpack_require__(2); /** * The default configuration of the viewer, including templates (canvas, overly, loading screen) * This configuration doesn't hold specific parameters, and only defines objects that are needed for the viewer to fully work correctly. */ exports.defaultConfiguration = { version: "3.2.0-alpha4", templates: { main: { html: babylonjs_viewer_assets_1.defaultTemplate, params: { babylonFont: babylonjs_viewer_assets_2.babylonFont, noEscape: true } }, fillContainer: { html: babylonjs_viewer_assets_1.fillContainer, params: { disable: false } }, loadingScreen: { html: babylonjs_viewer_assets_1.loadingScreen, params: { backgroundColor: "#000000", loadingImage: images.loading } }, viewer: { html: babylonjs_viewer_assets_1.defaultViewer, params: { enableDragAndDrop: false } }, navBar: { html: babylonjs_viewer_assets_1.navbar, params: { speedList: { "0.5x": "0.5", "1.0x": "1.0", "1.5x": "1.5", "2.0x": "2.0", }, logoImage: images.babylonLogo, logoText: 'BabylonJS', logoLink: 'https://babylonjs.com', hideHelp: true, disableOnFullscreen: false, }, events: { pointerdown: { 'navbar-control': true, 'help-button': true }, input: { 'progress-wrapper': true }, pointerup: { 'progress-wrapper': true } } }, overlay: { html: babylonjs_viewer_assets_1.overlay, params: { closeImage: images.close, closeText: 'Close' } }, help: { html: babylonjs_viewer_assets_1.help }, share: { html: babylonjs_viewer_assets_1.share }, error: { html: babylonjs_viewer_assets_1.error } }, camera: { behaviors: { autoRotate: { type: 0 }, framing: { type: 2, zoomOnBoundingInfo: true, zoomStopsAnimation: false }, bouncing: { type: 1 } }, wheelPrecision: 200, }, skybox: {}, ground: { receiveShadows: true }, engine: { antialiasing: true }, scene: {} }; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVmYXVsdC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL3R5cGVzL2RlZmF1bHQudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSxtRUFBNEk7QUFDNUksbUVBQXNEO0FBQ3RELGdEQUFrRDtBQUVsRDs7O0dBR0c7QUFDUSxRQUFBLG9CQUFvQixHQUF3QjtJQUNuRCxPQUFPLEVBQUUsY0FBYztJQUN2QixTQUFTLEVBQUU7UUFDUCxJQUFJLEVBQUU7WUFDRixJQUFJLEVBQUU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QUNELFNBQVMsRUFBRTtvQkFDUCxrQkFBa0IsRUFBRSxJQUFJO2lCQUMzQjthQUNKO1NBQ0o7UUFDRCxPQUFPLEVBQUU7WUFDTCxJQUFJLEVBQUUsaUNBQU87WUFDYixNQUFNLEVBQUU7Z0JBQ0osVUFBVSxFQUFFLE1BQU0sQ0FBQyxLQUFLO2dCQUN4QixTQUFTLEVBQUUsT0FBTzthQUNyQjtTQUNKO1FBQ0QsSUFBSSxFQUFFO1lBQ0YsSUFBSSxFQUFFLDhCQUFJO1NBQ2I7UUFDRCxLQUFLLEVBQUU7WUFDSCxJQUFJLEVBQUUsK0JBQUs7U0FDZDtRQUNELEtBQUssRUFBRTtZQUNILElBQUksRUFBRSwrQkFBSztTQUNkO0tBRUo7SUFDRCxNQUFNLEVBQUU7UUFDSixTQUFTLEVBQUU7WUFDUCxVQUFVLEVBQUU7Z0JBQ1IsSUFBSSxFQUFFLENBQUM7YUFDVjtZQUNELE9BQU8sRUFBRTtnQkFDTCxJQUFJLEVBQUUsQ0FBQztnQkFDUCxrQkFBa0IsRUFBRSxJQUFJO2dCQUN4QixrQkFBa0IsRUFBRSxLQUFLO2FBQzVCO1lBQ0QsUUFBUSxFQUFFO2dCQUNOLElBQUksRUFBRSxDQUFDO2FBQ1Y7U0FDSjtRQUNELGNBQWMsRUFBRSxHQUFHO0tBQ3RCO0lBQ0QsTUFBTSxFQUFFLEVBQ1A7SUFDRCxNQUFNLEVBQUU7UUFDSixjQUFjLEVBQUUsSUFBSTtLQUN2QjtJQUNELE1BQU0sRUFBRTtRQUNKLFlBQVksRUFBRSxJQUFJO0tBQ3JCO0lBQ0QsS0FBSyxFQUFFLEVBQ047Q0FDSixDQUFBIn0= /***/ }), /* 50 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var babylonjs_1 = __webpack_require__(0); /** * The viewer's "extended" configuration. * This configuration defines specific obejcts and parameters that we think make any model look good. */ exports.extendedConfiguration = { version: "3.2.0", extends: "default", camera: { exposure: 3.034578, fov: 0.7853981633974483, contrast: 1.6, toneMappingEnabled: true, upperBetaLimit: 1.3962634015954636 + Math.PI / 2, lowerBetaLimit: -1.4835298641951802 + Math.PI / 2, behaviors: { framing: { type: 2, mode: 0, positionScale: 0.5, defaultElevation: 0.2617993877991494, elevationReturnWaitTime: 3000, elevationReturnTime: 2000, framingTime: 500, zoomStopsAnimation: false, radiusScale: 0.866 }, autoRotate: { type: 0, idleRotationWaitTime: 4000, idleRotationSpeed: 0.17453292519943295, idleRotationSpinupTime: 2500, zoomStopsAnimation: false }, bouncing: { type: 1, lowerRadiusTransitionRange: 0.05, upperRadiusTransitionRange: -0.2 } }, upperRadiusLimit: 5, lowerRadiusLimit: 0.5, frameOnModelLoad: true, framingElevation: 0.2617993877991494, framingRotation: 1.5707963267948966, radius: 2, alpha: 1.5708, beta: Math.PI * 0.5 - 0.2618, wheelPrecision: 300, minZ: 0.1, maxZ: 50, fovMode: 0, pinchPrecision: 1500, panningSensibility: 3000 }, lights: { light0: { type: 0, frustumEdgeFalloff: 0, intensity: 7, intensityMode: 0, radius: 0.6, range: 0.6, spotAngle: 60, diffuse: { r: 1, g: 1, b: 1 }, position: { x: -2, y: 2.5, z: 2 }, target: { x: 0, y: 0, z: 0 }, enabled: true, shadowEnabled: true, shadowBufferSize: 512, shadowMinZ: 1, shadowMaxZ: 10, shadowFieldOfView: 60, shadowFrustumSize: 2, shadowConfig: { useBlurCloseExponentialShadowMap: true, useKernelBlur: true, blurScale: 1.0, bias: 0.001, depthScale: 50 * (10 - 1), frustumEdgeFalloff: 0 } }, light1: { type: 0, frustumEdgeFalloff: 0, intensity: 7, intensityMode: 0, radius: 0.4, range: 0.4, spotAngle: 57, diffuse: { r: 1, g: 1, b: 1 }, position: { x: 4, y: 3, z: -0.5 }, target: { x: 0, y: 0, z: 0 }, enabled: true, shadowEnabled: false, shadowBufferSize: 512, shadowMinZ: 0.2, shadowMaxZ: 10, shadowFieldOfView: 28, shadowFrustumSize: 2 }, light2: { type: 0, frustumEdgeFalloff: 0, intensity: 1, intensityMode: 0, radius: 0.5, range: 0.5, spotAngle: 42.85, diffuse: { r: 0.8, g: 0.8, b: 0.8 }, position: { x: -1, y: 3, z: -3 }, target: { x: 0, y: 0, z: 0 }, enabled: true, shadowEnabled: false, shadowBufferSize: 512, shadowMinZ: 0.2, shadowMaxZ: 10, shadowFieldOfView: 45, shadowFrustumSize: 2 } }, ground: { shadowLevel: 0.9, texture: "Ground_2.0-1024.png", material: { primaryColorHighlightLevel: 0.035, primaryColorShadowLevel: 0, enableNoise: true, useRGBColor: false, maxSimultaneousLights: 1, diffuseTexture: { gammaSpace: true } }, opacity: 1, mirror: false, receiveShadows: true, size: 5 }, skybox: { scale: 11, cubeTexture: { url: "Skybox_2.0-256.dds" }, material: { primaryColorHighlightLevel: 0.03, primaryColorShadowLevel: 0.03, enableNoise: true, useRGBColor: false, reflectionTexture: { gammaSpace: true } } }, engine: { renderInBackground: true }, scene: { flags: { shadowsEnabled: true, particlesEnabled: false, collisionsEnabled: false, lightsEnabled: true, texturesEnabled: true, lensFlaresEnabled: false, proceduralTexturesEnabled: false, renderTargetsEnabled: true, spritesEnabled: false, skeletonsEnabled: true, audioEnabled: false, }, defaultMaterial: { materialType: 'pbr', reflectivityColor: { r: 0.1, g: 0.1, b: 0.1 }, microSurface: 0.6 }, clearColor: { r: 0.9, g: 0.9, b: 0.9, a: 1.0 }, imageProcessingConfiguration: { vignetteCentreX: 0, vignetteCentreY: 0, vignetteColor: { r: 0.086, g: 0.184, b: 0.259, a: 1 }, vignetteWeight: 0.855, vignetteStretch: 0.5, vignetteBlendMode: 0, vignetteCameraFov: 0.7853981633974483, isEnabled: true, colorCurves: { shadowsHue: 0, shadowsDensity: 0, shadowsSaturation: 0, shadowsExposure: 0, midtonesHue: 0, midtonesDensity: 0, midtonesExposure: 0, midtonesSaturation: 0, highlightsHue: 0, highlightsDensity: 0, highlightsExposure: 0, highlightsSaturation: 0 } }, mainColor: { r: 0.8823529411764706, g: 0.8823529411764706, b: 0.8823529411764706 } }, loaderPlugins: { extendedMaterial: true, applyMaterialConfig: true, msftLod: true, telemetry: true }, model: { rotationOffsetAxis: { x: 0, y: -1, z: 0 }, rotationOffsetAngle: babylonjs_1.Tools.ToRadians(210), material: { directEnabled: true, directIntensity: 0.884, emissiveIntensity: 1.04, environmentIntensity: 0.6 }, entryAnimation: { scaling: { x: 0, y: 0, z: 0 }, time: 0.5, easingFunction: 4, easingMode: 1 }, exitAnimation: { scaling: { x: 0, y: 0, z: 0 }, time: 0.5, easingFunction: 4, easingMode: 1 }, normalize: true, castShadow: true, receiveShadows: true }, lab: { assetsRootURL: 'https://viewer.babylonjs.com/assets/environment/', environmentMap: { texture: "EnvMap_2.0-256.env", rotationY: 3, tintLevel: 0.4 }, defaultRenderingPipelines: { bloomEnabled: true, bloomThreshold: 1.0, fxaaEnabled: true, bloomWeight: 0.05 } } }; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9leHRlbmRlZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUNBLHVDQUFrQztBQUVsQzs7O0dBR0c7QUFDUSxRQUFBLHFCQUFxQixHQUF3QjtJQUNwRCxPQUFPLEVBQUUsT0FBTztJQUNoQixPQUFPLEVBQUUsU0FBUztJQUNsQixNQUFNLEVBQUU7UUFDSixRQUFRLEVBQUUsUUFBUTtRQUNsQixHQUFHLEVBQUUsa0JBQWtCO1FBQ3ZCLFFBQVEsRUFBRSxHQUFHO1FBQ2Isa0JBQWtCLEVBQUUsSUFBSTtRQUN4QixjQUFjLEVBQUUsa0JBQWtCLEdBQUcsSUFBSSxDQUFDLEVBQUUsR0FBRyxDQUFDO1FBQ2hELGNBQWMsRUFBRSxDQUFDL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WUFDWixTQUFTLEVBQUUsR0FBRztTQUNqQjtRQUNELHlCQUF5QixFQUFFO1lBQ3ZCLFlBQVksRUFBRSxJQUFJO1lBQ2xCLGNBQWMsRUFBRSxHQUFHO1lBQ25CLFdBQVcsRUFBRSxJQUFJO1lBQ2pCLFdBQVcsRUFBRSxJQUFJO1NBQ3BCO0tBQ0o7Q0FDSixDQUFBIn0= /***/ }), /* 51 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Defines a default directional shadow light for normalized objects (!) */ exports.shadowDirectionalLightConfiguration = { model: { receiveShadows: true, castShadow: true }, ground: { receiveShadows: true }, lights: { shadowDirectionalLight: { type: 1, shadowEnabled: true, target: { x: 0, y: 0, z: 0.5 }, position: { x: 1.49, y: 2.39, z: -1.33 }, diffuse: { r: 0.867, g: 0.816, b: 0.788 }, intensity: 4.887, intensityMode: 0, shadowBufferSize: 1024, shadowFrustumSize: 6.0, shadowFieldOfView: 50.977, shadowMinZ: 0.1, shadowMaxZ: 10.0, shadowConfig: { blurKernel: 32, useBlurCloseExponentialShadowMap: true } } } }; /** * Defines a default shadow-enabled spot light for normalized objects. */ exports.shadowSpotlLightConfiguration = { model: { receiveShadows: true, castShadow: true }, ground: { receiveShadows: true }, lights: { shadowSpotLight: { type: 2, intensity: 2, shadowEnabled: true, target: { x: 0, y: 0, z: 0.5 }, position: { x: 0, y: 3.5, z: 3.7 }, angle: 1, shadowOrthoScale: 0.5, shadowBufferSize: 1024, shadowMinZ: 0.1, shadowMaxZ: 50.0, shadowConfig: { frustumEdgeFalloff: 0.5, blurKernel: 32, useBlurExponentialShadowMap: true } } } }; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2hhZG93TGlnaHQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9zaGFkb3dMaWdodC50cyJ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QWMsRUFBRSxJQUFJO1FBQ3BCLFVBQVUsRUFBRSxJQUFJO0tBQ25CO0lBQ0QsTUFBTSxFQUFFO1FBQ0osY0FBYyxFQUFFLElBQUk7S0FDdkI7SUFDRCxNQUFNLEVBQUU7UUFDSixlQUFlLEVBQUU7WUFDYixJQUFJLEVBQUUsQ0FBQztZQUNQLFNBQVMsRUFBRSxDQUFDO1lBQ1osYUFBYSxFQUFFLElBQUk7WUFDbkIsTUFBTSxFQUFFLEVBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxHQUFHLEVBQUU7WUFDOUIsUUFBUSxFQUFFLEVBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLEVBQUUsR0FBRyxFQUFFLENBQUMsRUFBRSxHQUFHLEVBQUU7WUFDbEMsS0FBSyxFQUFFLENBQUM7WUFDUixnQkFBZ0IsRUFBRSxHQUFHO1lBQ3JCLGdCQUFnQixFQUFFLElBQUk7WUFDdEIsVUFBVSxFQUFFLEdBQUc7WUFDZixVQUFVLEVBQUUsSUFBSTtZQUNoQixZQUFZLEVBQUU7Z0JBQ1Ysa0JBQWtCLEVBQUUsR0FBRztnQkFDdkIsVUFBVSxFQUFFLEVBQUU7Z0JBQ2QsMkJBQTJCLEVBQUUsSUFBSTthQUNwQztTQUNKO0tBQ0o7Q0FDSixDQUFBIn0= /***/ }), /* 52 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Lab-oriented default .env support */ exports.environmentMapConfiguration = { lab: { assetsRootURL: '/assets/environment/', environmentMap: { texture: 'EnvMap_2.0-256.env', rotationY: 0, tintLevel: 0.4 } } }; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW52aXJvbm1lbnRNYXAuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9lbnZpcm9ubWVudE1hcC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUVBOztHQUVHO0FBQ1UsUUFBQSwyQkFBMkIsR0FBd0I7SUFDNUQsR0FBRyxFQUFFO1FBQ0QsYUFBYSxFQUFFLHNCQUFzQjtRQUNyQyxjQUFjLEVBQUU7WUFDWixPQUFPLEVBQUUsb0JBQW9CO1lBQzdCLFNBQVMsRUFBRSxDQUFDO1lBQ1osU0FBUyxFQUFFLEdBQUc7U0FDakI7S0FDSjtDQUNKLENBQUEifQ== /***/ }), /* 53 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var configuration_1 = __webpack_require__(11); /** * This function will make sure the configuration file is taking deprecated fields into account * and is setting them to the correct keys and values. * * @param configuration The configuration to process. Mutable! */ function processConfigurationCompatibility(configuration) { if (configuration.camera) { // camera contrast -> image processing contrast if (configuration.camera.contrast !== undefined) { setKeyInObject(configuration, "scene.imageProcessingConfiguration.contrast", configuration.camera.contrast); } // camera exposure -> image processing exposure if (configuration.camera.exposure !== undefined) { setKeyInObject(configuration, "scene.imageProcessingConfiguration.exposure", configuration.camera.exposure); } } if (configuration.scene) { //glow if (configuration.scene.glow) { setKeyInObject(configuration, "lab.defaultRenderingPipelines.glowLayerEnabled", true); var enabledProcessing = configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", configuration); if (enabledProcessing !== false) { setKeyInObject(configuration, "scene.imageProcessingConfiguration.isEnabled", true); } } } } exports.processConfigurationCompatibility = processConfigurationCompatibility; function setKeyInObject(object, keys, value, shouldOverwrite) { var keySplit = keys.split("."); if (keySplit.length === 0) return; var lastKey = keySplit.pop(); if (!lastKey) return; var curObj = object; keySplit.forEach(function (key) { curObj[key] = curObj[key] || {}; curObj = curObj[key]; }); if (curObj[lastKey] !== undefined && !shouldOverwrite) return; curObj[lastKey] = value; } //# sourceMappingURL=data:application/json;base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UUsSUFBSSxDQUFDLENBQUM7YUFDdkY7U0FDSjtLQUNKO0FBQ0wsQ0FBQztBQTFCRCw4RUEwQkM7QUFFRCx3QkFBd0IsTUFBVyxFQUFFLElBQVksRUFBRSxLQUFVLEVBQUUsZUFBeUI7SUFDcEYsSUFBSSxRQUFRLEdBQUcsSUFBSSxDQUFDLEtBQUssQ0FBQyxHQUFHLENBQUMsQ0FBQztJQUMvQixJQUFJLFFBQVEsQ0FBQyxNQUFNLEtBQUssQ0FBQztRQUFFLE9BQU87SUFDbEMsSUFBSSxPQUFPLEdBQUcsUUFBUSxDQUFDLEdBQUcsRUFBRSxDQUFDO0lBQzdCLElBQUksQ0FBQyxPQUFPO1FBQUUsT0FBTztJQUNyQixJQUFJLE1BQU0sR0FBRyxNQUFNLENBQUM7SUFDcEIsUUFBUSxDQUFDLE9BQU8sQ0FBQyxVQUFBLEdBQUc7UUFDaEIsTUFBTSxDQUFDLEdBQUcsQ0FBQyxHQUFHLE1BQU0sQ0FBQyxHQUFHLENBQUMsSUFBSSxFQUFFLENBQUM7UUFDaEMsTUFBTSxHQUFHLE1BQU0sQ0FBQyxHQUFHLENBQUMsQ0FBQztJQUN6QixDQUFDLENBQUMsQ0FBQztJQUNILElBQUksTUFBTSxDQUFDLE9BQU8sQ0FBQyxLQUFLLFNBQVMsSUFBSSxDQUFDLGVBQWU7UUFBRSxPQUFPO0lBQzlELE1BQU0sQ0FBQyxPQUFPLENBQUMsR0FBRyxLQUFLLENBQUM7QUFDNUIsQ0FBQyJ9 /***/ }), /* 54 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var telemetryLoaderPlugin_1 = __webpack_require__(55); exports.TelemetryLoaderPlugin = telemetryLoaderPlugin_1.TelemetryLoaderPlugin; var msftLodLoaderPlugin_1 = __webpack_require__(56); exports.MSFTLodLoaderPlugin = msftLodLoaderPlugin_1.MSFTLodLoaderPlugin; var applyMaterialConfig_1 = __webpack_require__(57); exports.ApplyMaterialConfigPlugin = applyMaterialConfig_1.ApplyMaterialConfigPlugin; var extendedMaterialLoaderPlugin_1 = __webpack_require__(58); exports.ExtendedMaterialLoaderPlugin = extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin; var babylonjs_1 = __webpack_require__(0); var pluginCache = {}; /** * Get a loader plugin according to its name. * The plugin will be cached and will be reused if called for again. * * @param name the name of the plugin */ function getLoaderPluginByName(name) { if (!pluginCache[name]) { switch (name) { case 'telemetry': pluginCache[name] = new telemetryLoaderPlugin_1.TelemetryLoaderPlugin(); break; case 'msftLod': pluginCache[name] = new msftLodLoaderPlugin_1.MSFTLodLoaderPlugin(); break; case 'applyMaterialConfig': pluginCache[name] = new applyMaterialConfig_1.ApplyMaterialConfigPlugin(); break; case 'extendedMaterial': pluginCache[name] = new extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin(); break; } } return pluginCache[name]; } exports.getLoaderPluginByName = getLoaderPluginByName; /** * */ function addLoaderPlugin(name, plugin) { if (pluginCache[name]) { babylonjs_1.Tools.Warn("Overwriting plugin with the same name - " + name); } pluginCache[name] = plugin; } exports.addLoaderPlugin = addLoaderPlugin; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvbG9hZGVyL3BsdWdpbnMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpRUFBZ0U7QUFTdkQsZ0NBVEEsNkNBQXFCLENBU0E7QUFQOUIsNkRBQTREO0FBT2IsOEJBUHRDLHlDQUFtQixDQU9zQztBQU5sRSw2REFBa0U7QUFNRSxvQ0FOM0QsK0NBQXlCLENBTTJEO0FBTDdGLCtFQUE4RTtBQUtpQix1Q0FMdEYsMkRBQTRCLENBS3NGO0FBSjNILHVDQUFrQztBQUVsQyxJQUFNLFdBQVcsR0FBcUMsRUFBRSxDQUFDO0FBSXpEOzs7OztHQUtHO0FBQ0gsK0JBQXNDLElBQVk7SUFDOUMsSUFBSSxDQUFDLFdBQVcsQ0FBQyxJQUFJLENBQUMsRUFBRTtRQUNwQixRQUFRLElBQUksRUFBRTtZQUNWLEtBQUssV0FBVztnQkFDWixXQUFXLENBQUMsSUFBSSxDQUFDLEdBQUcsSUFBSSw2Q0FBcUIsRUFBRSxDQUFDO2dCQUNoRCxNQUFNO1lBQ1YsS0FBSyxTQUFTO2dCQUNWLFdBQVcsQ0FBQyxJQUFJLENBQUMsR0FBRyxJQUFJLHlDQUFtQixFQUFFLENBQUM7Z0JBQzlDLE1BQU07WUFDVixLQUFLLHFCQUFxQjtnQkFDdEIsV0FBVyxDQUFDLElBQUksQ0FBQyxHQUFHLElBQUksK0NBQXlCLEVBQUUsQ0FBQztnQkFDcEQsTUFBTTtZQUNWLEtBQUssa0JBQWtCO2dCQUNuQixXQUFXLENBQUMsSUFBSSxDQUFDLEdBQUcsSUFBSSwyREFBNEIsRUFBRSxDQUFDO2dCQUN2RCxNQUFNO1NBQ2I7S0FDSjtJQUVELE9BQU8sV0FBVyxDQUFDLElBQUksQ0FBQyxDQUFDO0FBQzdCLENBQUM7QUFuQkQsc0RBbUJDO0FBRUQ7O0dBRUc7QUFDSCx5QkFBZ0MsSUFBWSxFQUFFLE1BQXFCO0lBQy9ELElBQUksV0FBVyxDQUFDLElBQUksQ0FBQyxFQUFFO1FBQ25CLGlCQUFLLENBQUMsSUFBSSxDQUFDLDBDQUEwQyxHQUFHLElBQUksQ0FBQyxDQUFDO0tBQ2pFO0lBQ0QsV0FBVyxDQUFDLElBQUksQ0FBQyxHQUFHLE1BQU0sQ0FBQztBQUMvQixDQUFDO0FBTEQsMENBS0MifQ== /***/ }), /* 55 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var telemetryManager_1 = __webpack_require__(6); var babylonjs_1 = __webpack_require__(0); var TelemetryLoaderPlugin = /** @class */ (function () { function TelemetryLoaderPlugin() { } TelemetryLoaderPlugin.prototype.onInit = function (loader, model) { this._model = model; this._loadStart = babylonjs_1.Tools.Now; }; TelemetryLoaderPlugin.prototype.onLoaded = function (model) { telemetryManager_1.telemetryManager.broadcast("Model Loaded", model.getViewerId(), { model: model, loadTime: babylonjs_1.Tools.Now - this._loadStart }); telemetryManager_1.telemetryManager.flushWebGLErrors(model.rootMesh.getEngine(), model.getViewerId()); }; TelemetryLoaderPlugin.prototype.onError = function (message, exception) { this._loadEnd = babylonjs_1.Tools.Now; telemetryManager_1.telemetryManager.broadcast("Load Error", this._model.getViewerId(), { model: this._model, loadTime: this._loadEnd - this._loadStart }); telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.rootMesh.getEngine(), this._model.getViewerId()); }; TelemetryLoaderPlugin.prototype.onComplete = function () { this._loadEnd = babylonjs_1.Tools.Now; telemetryManager_1.telemetryManager.broadcast("Load Complete", this._model.getViewerId(), { model: this._model, loadTime: this._loadEnd - this._loadStart }); telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.rootMesh.getEngine(), this._model.getViewerId()); }; return TelemetryLoaderPlugin; }()); exports.TelemetryLoaderPlugin = TelemetryLoaderPlugin; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVsZW1ldHJ5TG9hZGVyUGx1Z2luLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vLi4vc3JjL2xvYWRlci9wbHVnaW5zL3RlbGVtZXRyeUxvYWRlclBsdWdpbi50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUNBLG9FQUFtRTtBQUVuRSx1Q0FBK0U7QUFHL0U7SUFBQTtJQXVDQSxDQUFDO0lBaENVLHNDQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUF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LEdBQUcsQ0FBQztRQUMxQixtQ0FBZ0IsQ0FBQyxTQUFTLENBQUMsZUFBZSxFQUFFLElBQUksQ0FBQyxNQUFNLENBQUMsV0FBVyxFQUFFLEVBQUU7WUFDbkUsS0FBSyxFQUFFLElBQUksQ0FBQyxNQUFNO1lBQ2xCLFFBQVEsRUFBRSxJQUFJLENBQUMsUUFBUSxHQUFHLElBQUksQ0FBQyxVQUFVO1NBQzVDLENBQUMsQ0FBQztRQUVILG1DQUFnQixDQUFDLGdCQUFnQixDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsUUFBUSxDQUFDLFNBQVMsRUFBRSxFQUFFLElBQUksQ0FBQyxNQUFNLENBQUMsV0FBVyxFQUFFLENBQUMsQ0FBQztJQUNuRyxDQUFDO0lBQ0wsNEJBQUM7QUFBRCxDQUFDLEFBdkNELElBdUNDO0FBdkNZLHNEQUFxQiJ9 /***/ }), /* 56 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * A loder plugin to use MSFT_lod extension correctly (glTF) */ var MSFTLodLoaderPlugin = /** @class */ (function () { function MSFTLodLoaderPlugin() { } MSFTLodLoaderPlugin.prototype.onInit = function (loader, model) { this._model = model; }; MSFTLodLoaderPlugin.prototype.onExtensionLoaded = function (extension) { if (extension.name === "MSFT_lod" && this._model.configuration.loaderConfiguration) { var MSFT_lod = extension; MSFT_lod.enabled = !!this._model.configuration.loaderConfiguration.progressiveLoading; MSFT_lod.maxLODsToLoad = this._model.configuration.loaderConfiguration.maxLODsToLoad || Number.MAX_VALUE; } }; return MSFTLodLoaderPlugin; }()); exports.MSFTLodLoaderPlugin = MSFTLodLoaderPlugin; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibXNmdExvZExvYWRlclBsdWdpbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9tc2Z0TG9kTG9hZGVyUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBS0E7O0dBRUc7QUFDSDtJQUFBO0lBZUEsQ0FBQztJQVhVLG9DQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO0lBQ3hCLENBQUM7SUFFTSwrQ0FBaUIsR0FBeEIsVUFBeUIsU0FBK0I7UUFDcEQsSUFBSSxTQUFTLENBQUMsSUFBSSxLQUFLLFVBQVUsSUFBSSxJQUFJLENBQUMsTUFBTSxDQUFDLGFBQWEsQ0FBQyxtQkFBbUIsRUFBRTtZQUNoRixJQUFNLFFBQVEsR0FBRyxTQUFzQyxDQUFDO1lBQ3hELFFBQVEsQ0FBQyxPQUFPLEdBQUcsQ0FBQyxDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsYUFBYSxDQUFDLG1CQUFtQixDQUFDLGtCQUFrQixDQUFDO1lBQ3RGLFFBQVEsQ0FBQyxhQUFhLEdBQUcsSUFBSSxDQUFDLE1BQU0sQ0FBQyxhQUFhLENBQUMsbUJBQW1CLENBQUMsYUFBYSxJQUFJLE1BQU0sQ0FBQyxTQUFTLENBQUM7U0FDNUc7SUFDTCxDQUFDO0lBQ0wsMEJBQUM7QUFBRCxDQUFDLEFBZkQsSUFlQztBQWZZLGtEQUFtQiJ9 /***/ }), /* 57 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Force-apply material configuration right after a material was loaded. */ var ApplyMaterialConfigPlugin = /** @class */ (function () { function ApplyMaterialConfigPlugin() { } ApplyMaterialConfigPlugin.prototype.onInit = function (loader, model) { this._model = model; }; ApplyMaterialConfigPlugin.prototype.onMaterialLoaded = function (material) { this._model && this._model._applyModelMaterialConfiguration(material); }; return ApplyMaterialConfigPlugin; }()); exports.ApplyMaterialConfigPlugin = ApplyMaterialConfigPlugin; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBwbHlNYXRlcmlhbENvbmZpZy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9hcHBseU1hdGVyaWFsQ29uZmlnLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBS0E7O0dBRUc7QUFDSDtJQUFBO0lBV0EsQ0FBQztJQVBVLDBDQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO0lBQ3hCLENBQUM7SUFFTSxvREFBZ0IsR0FBdkIsVUFBd0IsUUFBa0I7UUFDdEMsSUFBSSxDQUFDLE1BQU0sSUFBSSxJQUFJLENBQUMsTUFBTSxDQUFDLGdDQUFnQyxDQUFDLFFBQVEsQ0FBQyxDQUFDO0lBQzFFLENBQUM7SUFDTCxnQ0FBQztBQUFELENBQUMsQUFYRCxJQVdDO0FBWFksOERBQXlCIn0= /***/ }), /* 58 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var babylonjs_1 = __webpack_require__(0); /** * A (PBR) material will be extended using this function. * This function will hold extra default configuration for the viewer, if not implemented in Babylon itself. */ var ExtendedMaterialLoaderPlugin = /** @class */ (function () { function ExtendedMaterialLoaderPlugin() { } ExtendedMaterialLoaderPlugin.prototype.onMaterialLoaded = function (baseMaterial) { var material = baseMaterial; material.alphaMode = babylonjs_1.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF; }; return ExtendedMaterialLoaderPlugin; }()); exports.ExtendedMaterialLoaderPlugin = ExtendedMaterialLoaderPlugin; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWRNYXRlcmlhbExvYWRlclBsdWdpbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9leHRlbmRlZE1hdGVyaWFsTG9hZGVyUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBRUEsdUNBQTRJO0FBRTVJOzs7R0FHRztBQUNIO0lBQUE7SUFNQSxDQUFDO0lBSlUsdURBQWdCLEdBQXZCLFVBQXdCLFlBQXNCO1FBQzFDLElBQUksUUFBUSxHQUFHLFlBQTJCLENBQUM7UUFDM0MsUUFBUSxDQUFDLFNBQVMsR0FBRyxrQkFBTSxDQUFDLDhCQUE4QixDQUFDO0lBQy9ELENBQUM7SUFDTCxtQ0FBQztBQUFELENBQUMsQUFORCxJQU1DO0FBTlksb0VBQTRCIn0= /***/ }), /* 59 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var babylonjs_1 = __webpack_require__(0); var ObservablesManager = /** @class */ (function () { function ObservablesManager() { this.onSceneInitObservable = new babylonjs_1.Observable(); this.onEngineInitObservable = new babylonjs_1.Observable(); this.onModelLoadedObservable = new babylonjs_1.Observable(); this.onModelLoadProgressObservable = new babylonjs_1.Observable(); this.onModelLoadErrorObservable = new babylonjs_1.Observable(); this.onModelAddedObservable = new babylonjs_1.Observable(); this.onModelRemovedObservable = new babylonjs_1.Observable(); this.onViewerInitDoneObservable = new babylonjs_1.Observable(); this.onLoaderInitObservable = new babylonjs_1.Observable(); this.onFrameRenderedObservable = new babylonjs_1.Observable(); } ObservablesManager.prototype.dispose = function () { this.onSceneInitObservable.clear(); this.onEngineInitObservable.clear(); this.onModelLoadedObservable.clear(); this.onModelLoadProgressObservable.clear(); this.onModelLoadErrorObservable.clear(); this.onModelAddedObservable.clear(); this.onModelRemovedObservable.clear(); this.onViewerInitDoneObservable.clear(); this.onLoaderInitObservable.clear(); this.onFrameRenderedObservable.clear(); }; return ObservablesManager; }()); exports.ObservablesManager = ObservablesManager; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoib2JzZXJ2YWJsZXNNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL21hbmFnZXJzL29ic2VydmFibGVzTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUE2SDtBQUc3SDtJQStDSTtRQUNJLElBQUksQ0FBQyxxQkFBcUIsR0FBRyxJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUM5QyxJQUFJLENBQUMsc0JBQXNCLEdBQUcsSUFBSSxzQkFBVSxFQUFFLENBQUM7UUFDL0MsSUFBSSxDQUFDLHVCQUF1QixHQUFHLElBQUksc0JBQVUsRUFBRSxDQUFDO1FBQ2hELElBQUksQ0FBQyw2QkFBNkIsR0FBRyxJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUN0RCxJQUFJLENBQUMsMEJBQTBCLEdBQUcsSUFBSSxzQkFBVSxFQUFFLENBQUM7UUFDbkQsSUFBSSxDQUFDLHNCQUFzQixHQUFHLElBQUksc0JBQVUsRUFBRSxDQUFDO1FBQy9DLElBQUksQ0FBQyx3QkFBd0IsR0FBRyxJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUNqRCxJQUFJLENBQUMsMEJBQTBCLEdBQUcsSUFBSSxzQkFBVSxFQUFFLENBQUM7UUFDbkQsSUFBSSxDQUFDLHNCQUFzQixHQUFHLElBQUksc0JBQVUsRUFBRSxDQUFDO1FBQy9DLElBQUksQ0FBQyx5QkFBeUIsR0FBRyxJQUFJLHNCQUFVLEVBQUUsQ0FBQztJQUN0RCxDQUFDO0lBRUQsb0NBQU8sR0FBUDtRQUNJLElBQUksQ0FBQyxxQkFBcUIsQ0FBQyxLQUFLLEVBQUUsQ0FBQztRQUNuQyxJQUFJLENBQUMsc0JBQXNCLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDcEMsSUFBSSxDQUFDLHVCQUF1QixDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ3JDLElBQUksQ0FBQyw2QkFBNkIsQ0FBQyxLQUFLLEVBQUUsQ0FBQztRQUMzQyxJQUFJLENBQUMsMEJBQTBCLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDeEMsSUFBSSxDQUFDLHNCQUFzQixDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ3BDLElBQUksQ0FBQyx3QkFBd0IsQ0FBQyxLQUFLLEVBQUUsQ0FBQztRQUN0QyxJQUFJLENBQUMsMEJBQTBCLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDeEMsSUFBSSxDQUFDLHNCQUFzQixDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ3BDLElBQUksQ0FBQyx5QkFBeUIsQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUMzQyxDQUFDO0lBRUwseUJBQUM7QUFBRCxDQUFDLEFBekVELElBeUVDO0FBekVZLGdEQUFrQiJ9 /***/ }), /* 60 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var babylonjs_1 = __webpack_require__(0); var ConfigurationContainer = /** @class */ (function () { function ConfigurationContainer() { this.mainColor = babylonjs_1.Color3.White(); this.reflectionColor = babylonjs_1.Color3.White(); } return ConfigurationContainer; }()); exports.ConfigurationContainer = ConfigurationContainer; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbkNvbnRhaW5lci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2NvbmZpZ3VyYXRpb25Db250YWluZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSx1Q0FBbUM7QUFFbkM7SUFBQTtRQU1XLGNBQVMsR0FBVyxrQkFBTSxDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ25DLG9CQUFlLEdBQVcsa0JBQU0sQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUNwRCxDQUFDO0lBQUQsNkJBQUM7QUFBRCxDQUFDLEFBUkQsSUFRQztBQVJZLHdEQUFzQiJ9 /***/ }), /* 61 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var babylonjs_1 = __webpack_require__(0); var helper_1 = __webpack_require__(1); var Handlebars = __webpack_require__(62); var eventManager_1 = __webpack_require__(63); var _1 = __webpack_require__(1); /** * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML. * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer. */ var TemplateManager = /** @class */ (function () { function TemplateManager(containerElement) { this.containerElement = containerElement; this.templates = {}; this.onTemplateInit = new babylonjs_1.Observable(); this.onTemplateLoaded = new babylonjs_1.Observable(); this.onTemplateStateChange = new babylonjs_1.Observable(); this.onAllLoaded = new babylonjs_1.Observable(); this.onEventTriggered = new babylonjs_1.Observable(); this.eventManager = new eventManager_1.EventManager(this); } /** * Initialize the template(s) for the viewer. Called bay the Viewer class * @param templates the templates to be used to initialize the main template */ TemplateManager.prototype.initTemplate = function (templates) { var _this = this; var internalInit = function (dependencyMap, name, parentTemplate) { //init template var template = _this.templates[name]; var childrenTemplates = Object.keys(dependencyMap).map(function (childName) { return internalInit(dependencyMap[childName], childName, template); }); // register the observers //template.onLoaded.add(() => { var addToParent = function () { var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement; template.appendTo(containingElement); _this._checkLoadedState(); }; if (parentTemplate && !parentTemplate.parent) { parentTemplate.onAppended.add(function () { addToParent(); }); } else { addToParent(); } //}); return template; }; //build the html tree return this._buildHTMLTree(templates).then(function (htmlTree) { if (_this.templates['main']) { internalInit(htmlTree, 'main'); } else { _this._checkLoadedState(); } return; }); }; /** * * This function will create a simple map with child-dependencies of the template html tree. * It will compile each template, check if its children exist in the configuration and will add them if they do. * It is expected that the main template will be called main! * * @param templates */ TemplateManager.prototype._buildHTMLTree = function (templates) { var _this = this; var promises = Object.keys(templates).map(function (name) { // if the template was overridden if (!templates[name]) return Promise.resolve(false); // else - we have a template, let's do our job! var template = new Template(name, templates[name]); template.onLoaded.add(function () { _this.onTemplateLoaded.notifyObservers(template); }); template.onStateChange.add(function () { _this.onTemplateStateChange.notifyObservers(template); }); _this.onTemplateInit.notifyObservers(template); // make sure the global onEventTriggered is called as well template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); }); _this.templates[name] = template; return template.initPromise; }); return Promise.all(promises).then(function () { var templateStructure = {}; // now iterate through all templates and check for children: var buildTree = function (parentObject, name) { _this.templates[name].isInHtmlTree = true; var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; }); childNodes.forEach(function (element) { parentObject[element] = {}; buildTree(parentObject[element], element); }); }; if (_this.templates['main']) { buildTree(templateStructure, "main"); } return templateStructure; }); }; /** * Get the canvas in the template tree. * There must be one and only one canvas inthe template. */ TemplateManager.prototype.getCanvas = function () { return this.containerElement.querySelector('canvas'); }; /** * Get a specific template from the template tree * @param name the name of the template to load */ TemplateManager.prototype.getTemplate = function (name) { return this.templates[name]; }; TemplateManager.prototype._checkLoadedState = function () { var _this = this; var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) { return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree; }); if (done) { this.onAllLoaded.notifyObservers(this); } }; /** * Dispose the template manager */ TemplateManager.prototype.dispose = function () { var _this = this; // dispose all templates Object.keys(this.templates).forEach(function (template) { _this.templates[template].dispose(); }); this.templates = {}; this.eventManager.dispose(); this.onTemplateInit.clear(); this.onAllLoaded.clear(); this.onEventTriggered.clear(); this.onTemplateLoaded.clear(); this.onTemplateStateChange.clear(); }; return TemplateManager; }()); exports.TemplateManager = TemplateManager; // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js Handlebars.registerHelper('eachInMap', function (map, block) { var out = ''; Object.keys(map).map(function (prop) { var data = map[prop]; if (typeof data === 'object') { data.id = data.id || prop; out += block.fn(data); } else { out += block.fn({ id: prop, value: data }); } }); return out; }); Handlebars.registerHelper('add', function (a, b) { var out = a + b; return out; }); Handlebars.registerHelper('eq', function (a, b) { var out = (a == b); return out; }); Handlebars.registerHelper('or', function (a, b) { var out = a || b; return out; }); Handlebars.registerHelper('not', function (a) { var out = !a; return out; }); Handlebars.registerHelper('count', function (map) { return map.length; }); Handlebars.registerHelper('gt', function (a, b) { var out = a > b; return out; }); /** * This class represents a single template in the viewer's template tree. * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar. * A template is injected using the template manager in the correct position. * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection) * * For further information please refer to the documentation page, https://doc.babylonjs.com */ var Template = /** @class */ (function () { function Template(name, _configuration) { var _this = this; this.name = name; this._configuration = _configuration; this.onLoaded = new babylonjs_1.Observable(); this.onAppended = new babylonjs_1.Observable(); this.onStateChange = new babylonjs_1.Observable(); this.onEventTriggered = new babylonjs_1.Observable(); this.loadRequests = []; this.isLoaded = false; this.isShown = false; this.isInHtmlTree = false; var htmlContentPromise = this._getTemplateAsHtml(_configuration); this.initPromise = htmlContentPromise.then(function (htmlTemplate) { if (htmlTemplate) { _this._htmlTemplate = htmlTemplate; var compiledTemplate = Handlebars.compile(htmlTemplate, { noEscape: (_this._configuration.params && !!_this._configuration.params.noEscape) }); var config = _this._configuration.params || {}; _this._rawHtml = compiledTemplate(config); try { _this._fragment = document.createRange().createContextualFragment(_this._rawHtml); } catch (e) { var test = document.createElement(_this.name); test.innerHTML = _this._rawHtml; _this._fragment = test; } _this.isLoaded = true; _this.isShown = true; _this.onLoaded.notifyObservers(_this); } return _this; }); } /** * Some templates have parameters (like background color for example). * The parameters are provided to Handlebars which in turn generates the template. * This function will update the template with the new parameters * * Note that when updating parameters the events will be registered again (after being cleared). * * @param params the new template parameters */ Template.prototype.updateParams = function (params, append) { if (append === void 0) { append = true; } if (append) { this._configuration.params = _1.deepmerge(this._configuration.params, params); } else { this._configuration.params = params; } // update the template if (this.isLoaded) { // this.dispose(); } var compiledTemplate = Handlebars.compile(this._htmlTemplate); var config = this._configuration.params || {}; this._rawHtml = compiledTemplate(config); try { this._fragment = document.createRange().createContextualFragment(this._rawHtml); } catch (e) { var test = document.createElement(this.name); test.innerHTML = this._rawHtml; this._fragment = test; } if (this.parent) { this.appendTo(this.parent, true); } }; Object.defineProperty(Template.prototype, "configuration", { /** * Get the template'S configuration */ get: function () { return this._configuration; }, enumerable: true, configurable: true }); /** * A template can be a parent element for other templates or HTML elements. * This function will deliver all child HTML elements of this template. */ Template.prototype.getChildElements = function () { var childrenArray = []; //Edge and IE don't support frage,ent.children var children = this._fragment && this._fragment.children; if (!this._fragment) { var fragment = this.parent.querySelector(this.name); if (fragment) { children = fragment.querySelectorAll('*'); } } if (!children) { // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'. children = this._fragment.querySelectorAll('*'); } for (var i = 0; i < children.length; ++i) { childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase())); } return childrenArray; }; /** * Appending the template to a parent HTML element. * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true. * @param parent the parent to which the template is added * @param forceRemove if the parent already exists, shoud the template be removed from it? */ Template.prototype.appendTo = function (parent, forceRemove) { var _this = this; if (this.parent) { if (forceRemove && this._addedFragment) { /*let fragement = this.parent.querySelector(this.name) if (fragement) this.parent.removeChild(fragement);*/ this.parent.innerHTML = ''; } else { return; } } this.parent = parent; if (this._configuration.id) { this.parent.id = this._configuration.id; } if (this._fragment) { this.parent.appendChild(this._fragment); this._addedFragment = this._fragment; } else { this.parent.insertAdjacentHTML("beforeend", this._rawHtml); } // appended only one frame after. setTimeout(function () { _this._registerEvents(); _this.onAppended.notifyObservers(_this); }); }; /** * Show the template using the provided visibilityFunction, or natively using display: flex. * The provided function returns a promise that should be fullfilled when the element is shown. * Since it is a promise async operations are more than possible. * See the default viewer for an opacity example. * @param visibilityFunction The function to execute to show the template. */ Template.prototype.show = function (visibilityFunction) { var _this = this; if (this._isHiding) return Promise.resolve(this); return Promise.resolve().then(function () { _this._isShowing = true; if (visibilityFunction) { return visibilityFunction(_this); } else { // flex? box? should this be configurable easier than the visibilityFunction? _this.parent.style.display = 'flex'; // support old browsers with no flex: if (_this.parent.style.display !== 'flex') { _this.parent.style.display = ''; } return _this; } }).then(function () { _this.isShown = true; _this._isShowing = false; _this.onStateChange.notifyObservers(_this); return _this; }); }; /** * Hide the template using the provided visibilityFunction, or natively using display: none. * The provided function returns a promise that should be fullfilled when the element is hidden. * Since it is a promise async operations are more than possible. * See the default viewer for an opacity example. * @param visibilityFunction The function to execute to show the template. */ Template.prototype.hide = function (visibilityFunction) { var _this = this; if (this._isShowing) return Promise.resolve(this); return Promise.resolve().then(function () { _this._isHiding = true; if (visibilityFunction) { return visibilityFunction(_this); } else { // flex? box? should this be configurable easier than the visibilityFunction? _this.parent.style.display = 'none'; return _this; } }).then(function () { _this.isShown = false; _this._isHiding = false; _this.onStateChange.notifyObservers(_this); return _this; }); }; /** * Dispose this template */ Template.prototype.dispose = function () { this.onAppended.clear(); this.onEventTriggered.clear(); this.onLoaded.clear(); this.onStateChange.clear(); this.isLoaded = false; // remove from parent try { this.parent.removeChild(this._fragment); } catch (e) { //noop } this.loadRequests.forEach(function (request) { request.abort(); }); if (this._registeredEvents) { this._registeredEvents.forEach(function (evt) { evt.htmlElement.removeEventListener(evt.eventName, evt.function); }); } delete this._fragment; }; Template.prototype._getTemplateAsHtml = function (templateConfig) { var _this = this; if (!templateConfig) { return Promise.reject('No templateConfig provided'); } else if (templateConfig.html !== undefined) { return Promise.resolve(templateConfig.html); } else { var location_1 = this._getTemplateLocation(templateConfig); if (helper_1.isUrl(location_1)) { return new Promise(function (resolve, reject) { var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) { resolve(data); }, undefined, undefined, false, function (request, error) { reject(error); }); _this.loadRequests.push(fileRequest); }); } else { location_1 = location_1.replace('#', ''); var element = document.getElementById(location_1); if (element) { return Promise.resolve(element.innerHTML); } else { return Promise.reject('Template ID not found'); } } } }; Template.prototype._registerEvents = function () { var _this = this; this._registeredEvents = this._registeredEvents || []; if (this._registeredEvents.length) { // first remove the registered events this._registeredEvents.forEach(function (evt) { evt.htmlElement.removeEventListener(evt.eventName, evt.function); }); } if (this._configuration.events) { var _loop_1 = function (eventName) { if (this_1._configuration.events && this_1._configuration.events[eventName]) { var functionToFire_1 = function (selector, event) { _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector }); }; // if boolean, set the parent as the event listener if (typeof this_1._configuration.events[eventName] === 'boolean') { var selector = this_1.parent.id; if (selector) { selector = '#' + selector; } else { selector = this_1.parent.tagName; } var binding = functionToFire_1.bind(this_1, selector); this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, selector), false); this_1._registeredEvents.push({ htmlElement: this_1.parent, eventName: eventName, function: binding }); } else if (typeof this_1._configuration.events[eventName] === 'object') { var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {}); // strict null checl is working incorrectly, must override: var event_1 = this_1._configuration.events[eventName] || {}; selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) { if (selector && selector.indexOf('#') !== 0) { selector = '#' + selector; } var htmlElement = _this.parent.querySelector(selector); if (htmlElement) { var binding = functionToFire_1.bind(_this, selector); htmlElement.addEventListener(eventName, binding, false); _this._registeredEvents.push({ htmlElement: htmlElement, eventName: eventName, function: binding }); } }); } } }; var this_1 = this; for (var eventName in this._configuration.events) { _loop_1(eventName); } } }; Template.prototype._getTemplateLocation = function (templateConfig) { if (!templateConfig || typeof templateConfig === 'string') { return templateConfig; } else { return templateConfig.location; } }; return Template; }()); exports.Template = Template; //# sourceMappingURL=data:application/json;base64,eyJ2ZX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Qzs0QkFDbkUsSUFBSSxXQUFXLEVBQUU7Z0NBQ2IsSUFBSSxPQUFPLEdBQUcsZ0JBQWMsQ0FBQyxJQUFJLENBQUMsS0FBSSxFQUFFLFFBQVEsQ0FBQyxDQUFDO2dDQUNsRCxXQUFXLENBQUMsZ0JBQWdCLENBQUMsU0FBUyxFQUFFLE9BQU8sRUFBRSxLQUFLLENBQUMsQ0FBQztnQ0FDeEQsS0FBSSxDQUFDLGlCQUFpQixDQUFDLElBQUksQ0FBQztvQ0FDeEIsV0FBVyxFQUFFLFdBQVc7b0NBQ3hCLFNBQVMsRUFBRSxTQUFTO29DQUNwQixRQUFRLEVBQUUsT0FBTztpQ0FDcEIsQ0FBQyxDQUFDOzZCQUNOO3dCQUNMLENBQUMsQ0FBQyxDQUFDO3FCQUNOO2lCQUNKO1lBQ0wsQ0FBQzs7WUExQ0QsS0FBSyxJQUFJLFNBQVMsSUFBSSxJQUFJLENBQUMsY0FBYyxDQUFDLE1BQU07d0JBQXZDLFNBQVM7YUEwQ2pCO1NBQ0o7SUFDTCxDQUFDO0lBRU8sdUNBQW9CLEdBQTVCLFVBQTZCLGNBQWM7UUFDdkMsSUFBSSxDQUFDLGNBQWMsSUFBSSxPQUFPLGNBQWMsS0FBSyxRQUFRLEVBQUU7WUFDdkQsT0FBTyxjQUFjLENBQUM7U0FDekI7YUFBTTtZQUNILE9BQU8sY0FBYyxDQUFDLFFBQVEsQ0FBQztTQUNsQztJQUNMLENBQUM7SUFDTCxlQUFDO0FBQUQsQ0FBQyxBQS9XRCxJQStXQztBQS9XWSw0QkFBUSJ9 /***/ }), /* 62 */ /***/ (function(module, exports, __webpack_require__) { /**! @license handlebars v4.0.11 Copyright (C) 2011-2017 by Yehuda Katz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ (function webpackUniversalModuleDefinition(root, factory) { if(true) module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["Handlebars"] = factory(); else root["Handlebars"] = factory(); })(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] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = 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; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _handlebarsRuntime = __webpack_require__(2); var _handlebarsRuntime2 = _interopRequireDefault(_handlebarsRuntime); // Compiler imports var _handlebarsCompilerAst = __webpack_require__(35); var _handlebarsCompilerAst2 = _interopRequireDefault(_handlebarsCompilerAst); var _handlebarsCompilerBase = __webpack_require__(36); var _handlebarsCompilerCompiler = __webpack_require__(41); var _handlebarsCompilerJavascriptCompiler = __webpack_require__(42); var _handlebarsCompilerJavascriptCompiler2 = _interopRequireDefault(_handlebarsCompilerJavascriptCompiler); var _handlebarsCompilerVisitor = __webpack_require__(39); var _handlebarsCompilerVisitor2 = _interopRequireDefault(_handlebarsCompilerVisitor); var _handlebarsNoConflict = __webpack_require__(34); var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict); var _create = _handlebarsRuntime2['default'].create; function create() { var hb = _create(); hb.compile = function (input, options) { return _handlebarsCompilerCompiler.compile(input, options, hb); }; hb.precompile = function (input, options) { return _handlebarsCompilerCompiler.precompile(input, options, hb); }; hb.AST = _handlebarsCompilerAst2['default']; hb.Compiler = _handlebarsCompilerCompiler.Compiler; hb.JavaScriptCompiler = _handlebarsCompilerJavascriptCompiler2['default']; hb.Parser = _handlebarsCompilerBase.parser; hb.parse = _handlebarsCompilerBase.parse; return hb; } var inst = create(); inst.create = create; _handlebarsNoConflict2['default'](inst); inst.Visitor = _handlebarsCompilerVisitor2['default']; inst['default'] = inst; exports['default'] = inst; module.exports = exports['default']; /***/ }), /* 1 */ /***/ (function(module, exports) { "use strict"; exports["default"] = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; }; exports.__esModule = true; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireWildcard = __webpack_require__(3)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _handlebarsBase = __webpack_require__(4); var base = _interopRequireWildcard(_handlebarsBase); // Each of these augment the Handlebars object. No need to setup here. // (This is done to easily share code between commonjs and browse envs) var _handlebarsSafeString = __webpack_require__(21); var _handlebarsSafeString2 = _interopRequireDefault(_handlebarsSafeString); var _handlebarsException = __webpack_require__(6); var _handlebarsException2 = _interopRequireDefault(_handlebarsException); var _handlebarsUtils = __webpack_require__(5); var Utils = _interopRequireWildcard(_handlebarsUtils); var _handlebarsRuntime = __webpack_require__(22); var runtime = _interopRequireWildcard(_handlebarsRuntime); var _handlebarsNoConflict = __webpack_require__(34); var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict); // For compatibility and usage outside of module systems, make the Handlebars object a namespace function create() { var hb = new base.HandlebarsEnvironment(); Utils.extend(hb, base); hb.SafeString = _handlebarsSafeString2['default']; hb.Exception = _handlebarsException2['default']; hb.Utils = Utils; hb.escapeExpression = Utils.escapeExpression; hb.VM = runtime; hb.template = function (spec) { return runtime.template(spec, hb); }; return hb; } var inst = create(); inst.create = create; _handlebarsNoConflict2['default'](inst); inst['default'] = inst; exports['default'] = inst; module.exports = exports['default']; /***/ }), /* 3 */ /***/ (function(module, exports) { "use strict"; exports["default"] = function (obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } }; exports.__esModule = true; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; exports.HandlebarsEnvironment = HandlebarsEnvironment; var _utils = __webpack_require__(5); var _exception = __webpack_require__(6); var _exception2 = _interopRequireDefault(_exception); var _helpers = __webpack_require__(10); var _decorators = __webpack_require__(18); var _logger = __webpack_require__(20); var _logger2 = _interopRequireDefault(_logger); var VERSION = '4.0.11'; exports.VERSION = VERSION; var COMPILER_REVISION = 7; exports.COMPILER_REVISION = COMPILER_REVISION; var REVISION_CHANGES = { 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it 2: '== 1.0.0-rc.3', 3: '== 1.0.0-rc.4', 4: '== 1.x.x', 5: '== 2.0.0-alpha.x', 6: '>= 2.0.0-beta.1', 7: '>= 4.0.0' }; exports.REVISION_CHANGES = REVISION_CHANGES; var objectType = '[object Object]'; function HandlebarsEnvironment(helpers, partials, decorators) { this.helpers = helpers || {}; this.partials = partials || {}; this.decorators = decorators || {}; _helpers.registerDefaultHelpers(this); _decorators.registerDefaultDecorators(this); } HandlebarsEnvironment.prototype = { constructor: HandlebarsEnvironment, logger: _logger2['default'], log: _logger2['default'].log, registerHelper: function registerHelper(name, fn) { if (_utils.toString.call(name) === objectType) { if (fn) { throw new _exception2['default']('Arg not supported with multiple helpers'); } _utils.extend(this.helpers, name); } else { this.helpers[name] = fn; } }, unregisterHelper: function unregisterHelper(name) { delete this.helpers[name]; }, registerPartial: function registerPartial(name, partial) { if (_utils.toString.call(name) === objectType) { _utils.extend(this.partials, name); } else { if (typeof partial === 'undefined') { throw new _exception2['default']('Attempting to register a partial called "' + name + '" as undefined'); } this.partials[name] = partial; } }, unregisterPartial: function unregisterPartial(name) { delete this.partials[name]; }, registerDecorator: function registerDecorator(name, fn) { if (_utils.toString.call(name) === objectType) { if (fn) { throw new _exception2['default']('Arg not supported with multiple decorators'); } _utils.extend(this.decorators, name); } else { this.decorators[name] = fn; } }, unregisterDecorator: function unregisterDecorator(name) { delete this.decorators[name]; } }; var log = _logger2['default'].log; exports.log = log; exports.createFrame = _utils.createFrame; exports.logger = _logger2['default']; /***/ }), /* 5 */ /***/ (function(module, exports) { 'use strict'; exports.__esModule = true; exports.extend = extend; exports.indexOf = indexOf; exports.escapeExpression = escapeExpression; exports.isEmpty = isEmpty; exports.createFrame = createFrame; exports.blockParams = blockParams; exports.appendContextPath = appendContextPath; var escape = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', '`': '`', '=': '=' }; var badChars = /[&<>"'`=]/g, possible = /[&<>"'`=]/; function escapeChar(chr) { return escape[chr]; } function extend(obj /* , ...source */) { for (var i = 1; i < arguments.length; i++) { for (var key in arguments[i]) { if (Object.prototype.hasOwnProperty.call(arguments[i], key)) { obj[key] = arguments[i][key]; } } } return obj; } var toString = Object.prototype.toString; exports.toString = toString; // Sourced from lodash // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt /* eslint-disable func-style */ var isFunction = function isFunction(value) { return typeof value === 'function'; }; // fallback for older versions of Chrome and Safari /* istanbul ignore next */ if (isFunction(/x/)) { exports.isFunction = isFunction = function (value) { return typeof value === 'function' && toString.call(value) === '[object Function]'; }; } exports.isFunction = isFunction; /* eslint-enable func-style */ /* istanbul ignore next */ var isArray = Array.isArray || function (value) { return value && typeof value === 'object' ? toString.call(value) === '[object Array]' : false; }; exports.isArray = isArray; // Older IE versions do not directly support indexOf so we must implement our own, sadly. function indexOf(array, value) { for (var i = 0, len = array.length; i < len; i++) { if (array[i] === value) { return i; } } return -1; } function escapeExpression(string) { if (typeof string !== 'string') { // don't escape SafeStrings, since they're already safe if (string && string.toHTML) { return string.toHTML(); } else if (string == null) { return ''; } else if (!string) { return string + ''; } // Force a string conversion as this will be done by the append regardless and // the regex test will do this transparently behind the scenes, causing issues if // an object's to string has escaped characters in it. string = '' + string; } if (!possible.test(string)) { return string; } return string.replace(badChars, escapeChar); } function isEmpty(value) { if (!value && value !== 0) { return true; } else if (isArray(value) && value.length === 0) { return true; } else { return false; } } function createFrame(object) { var frame = extend({}, object); frame._parent = object; return frame; } function blockParams(params, ids) { params.path = ids; return params; } function appendContextPath(contextPath, id) { return (contextPath ? contextPath + '.' : '') + id; } /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _Object$defineProperty = __webpack_require__(7)['default']; exports.__esModule = true; var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; function Exception(message, node) { var loc = node && node.loc, line = undefined, column = undefined; if (loc) { line = loc.start.line; column = loc.start.column; message += ' - ' + line + ':' + column; } var tmp = Error.prototype.constructor.call(this, message); // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work. for (var idx = 0; idx < errorProps.length; idx++) { this[errorProps[idx]] = tmp[errorProps[idx]]; } /* istanbul ignore else */ if (Error.captureStackTrace) { Error.captureStackTrace(this, Exception); } try { if (loc) { this.lineNumber = line; // Work around issue under safari where we can't directly set the column value /* istanbul ignore next */ if (_Object$defineProperty) { Object.defineProperty(this, 'column', { value: column, enumerable: true }); } else { this.column = column; } } } catch (nop) { /* Ignore if the browser is very particular */ } } Exception.prototype = new Error(); exports['default'] = Exception; module.exports = exports['default']; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(8), __esModule: true }; /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { var $ = __webpack_require__(9); module.exports = function defineProperty(it, key, desc){ return $.setDesc(it, key, desc); }; /***/ }), /* 9 */ /***/ (function(module, exports) { var $Object = Object; module.exports = { create: $Object.create, getProto: $Object.getPrototypeOf, isEnum: {}.propertyIsEnumerable, getDesc: $Object.getOwnPropertyDescriptor, setDesc: $Object.defineProperty, setDescs: $Object.defineProperties, getKeys: $Object.keys, getNames: $Object.getOwnPropertyNames, getSymbols: $Object.getOwnPropertySymbols, each: [].forEach }; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; exports.registerDefaultHelpers = registerDefaultHelpers; var _helpersBlockHelperMissing = __webpack_require__(11); var _helpersBlockHelperMissing2 = _interopRequireDefault(_helpersBlockHelperMissing); var _helpersEach = __webpack_require__(12); var _helpersEach2 = _interopRequireDefault(_helpersEach); var _helpersHelperMissing = __webpack_require__(13); var _helpersHelperMissing2 = _interopRequireDefault(_helpersHelperMissing); var _helpersIf = __webpack_require__(14); var _helpersIf2 = _interopRequireDefault(_helpersIf); var _helpersLog = __webpack_require__(15); var _helpersLog2 = _interopRequireDefault(_helpersLog); var _helpersLookup = __webpack_require__(16); var _helpersLookup2 = _interopRequireDefault(_helpersLookup); var _helpersWith = __webpack_require__(17); var _helpersWith2 = _interopRequireDefault(_helpersWith); function registerDefaultHelpers(instance) { _helpersBlockHelperMissing2['default'](instance); _helpersEach2['default'](instance); _helpersHelperMissing2['default'](instance); _helpersIf2['default'](instance); _helpersLog2['default'](instance); _helpersLookup2['default'](instance); _helpersWith2['default'](instance); } /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _utils = __webpack_require__(5); exports['default'] = function (instance) { instance.registerHelper('blockHelperMissing', function (context, options) { var inverse = options.inverse, fn = options.fn; if (context === true) { return fn(this); } else if (context === false || context == null) { return inverse(this); } else if (_utils.isArray(context)) { if (context.length > 0) { if (options.ids) { options.ids = [options.name]; } return instance.helpers.each(context, options); } else { return inverse(this); } } else { if (options.data && options.ids) { var data = _utils.createFrame(options.data); data.contextPath = _utils.appendContextPath(options.data.contextPath, options.name); options = { data: data }; } return fn(context, options); } }); }; module.exports = exports['default']; /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _utils = __webpack_require__(5); var _exception = __webpack_require__(6); var _exception2 = _interopRequireDefault(_exception); exports['default'] = function (instance) { instance.registerHelper('each', function (context, options) { if (!options) { throw new _exception2['default']('Must pass iterator to #each'); } var fn = options.fn, inverse = options.inverse, i = 0, ret = '', data = undefined, contextPath = undefined; if (options.data && options.ids) { contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]) + '.'; } if (_utils.isFunction(context)) { context = context.call(this); } if (options.data) { data = _utils.createFrame(options.data); } function execIteration(field, index, last) { if (data) { data.key = field; data.index = index; data.first = index === 0; data.last = !!last; if (contextPath) { data.contextPath = contextPath + field; } } ret = ret + fn(context[field], { data: data, blockParams: _utils.blockParams([context[field], field], [contextPath + field, null]) }); } if (context && typeof context === 'object') { if (_utils.isArray(context)) { for (var j = context.length; i < j; i++) { if (i in context) { execIteration(i, i, i === context.length - 1); } } } else { var priorKey = undefined; for (var key in context) { if (context.hasOwnProperty(key)) { // We're running the iterations one step out of sync so we can detect // the last iteration without have to scan the object twice and create // an itermediate keys array. if (priorKey !== undefined) { execIteration(priorKey, i - 1); } priorKey = key; i++; } } if (priorKey !== undefined) { execIteration(priorKey, i - 1, true); } } } if (i === 0) { ret = inverse(this); } return ret; }); }; module.exports = exports['default']; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _exception = __webpack_require__(6); var _exception2 = _interopRequireDefault(_exception); exports['default'] = function (instance) { instance.registerHelper('helperMissing', function () /* [args, ]options */{ if (arguments.length === 1) { // A missing field in a {{foo}} construct. return undefined; } else { // Someone is actually trying to call something, blow up. throw new _exception2['default']('Missing helper: "' + arguments[arguments.length - 1].name + '"'); } }); }; module.exports = exports['default']; /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _utils = __webpack_require__(5); exports['default'] = function (instance) { instance.registerHelper('if', function (conditional, options) { if (_utils.isFunction(conditional)) { conditional = conditional.call(this); } // Default behavior is to render the positive path if the value is truthy and not empty. // The `includeZero` option may be set to treat the condtional as purely not empty based on the // behavior of isEmpty. Effectively this determines if 0 is handled by the positive path or negative. if (!options.hash.includeZero && !conditional || _utils.isEmpty(conditional)) { return options.inverse(this); } else { return options.fn(this); } }); instance.registerHelper('unless', function (conditional, options) { return instance.helpers['if'].call(this, conditional, { fn: options.inverse, inverse: options.fn, hash: options.hash }); }); }; module.exports = exports['default']; /***/ }), /* 15 */ /***/ (function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = function (instance) { instance.registerHelper('log', function () /* message, options */{ var args = [undefined], options = arguments[arguments.length - 1]; for (var i = 0; i < arguments.length - 1; i++) { args.push(arguments[i]); } var level = 1; if (options.hash.level != null) { level = options.hash.level; } else if (options.data && options.data.level != null) { level = options.data.level; } args[0] = level; instance.log.apply(instance, args); }); }; module.exports = exports['default']; /***/ }), /* 16 */ /***/ (function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = function (instance) { instance.registerHelper('lookup', function (obj, field) { return obj && obj[field]; }); }; module.exports = exports['default']; /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _utils = __webpack_require__(5); exports['default'] = function (instance) { instance.registerHelper('with', function (context, options) { if (_utils.isFunction(context)) { context = context.call(this); } var fn = options.fn; if (!_utils.isEmpty(context)) { var data = options.data; if (options.data && options.ids) { data = _utils.createFrame(options.data); data.contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]); } return fn(context, { data: data, blockParams: _utils.blockParams([context], [data && data.contextPath]) }); } else { return options.inverse(this); } }); }; module.exports = exports['default']; /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; exports.registerDefaultDecorators = registerDefaultDecorators; var _decoratorsInline = __webpack_require__(19); var _decoratorsInline2 = _interopRequireDefault(_decoratorsInline); function registerDefaultDecorators(instance) { _decoratorsInline2['default'](instance); } /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _utils = __webpack_require__(5); exports['default'] = function (instance) { instance.registerDecorator('inline', function (fn, props, container, options) { var ret = fn; if (!props.partials) { props.partials = {}; ret = function (context, options) { // Create a new partials stack frame prior to exec. var original = container.partials; container.partials = _utils.extend({}, original, props.partials); var ret = fn(context, options); container.partials = original; return ret; }; } props.partials[options.args[0]] = options.fn; return ret; }); }; module.exports = exports['default']; /***/ }), /* 20 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _utils = __webpack_require__(5); var logger = { methodMap: ['debug', 'info', 'warn', 'error'], level: 'info', // Maps a given level value to the `methodMap` indexes above. lookupLevel: function lookupLevel(level) { if (typeof level === 'string') { var levelMap = _utils.indexOf(logger.methodMap, level.toLowerCase()); if (levelMap >= 0) { level = levelMap; } else { level = parseInt(level, 10); } } return level; }, // Can be overridden in the host environment log: function log(level) { level = logger.lookupLevel(level); if (typeof console !== 'undefined' && logger.lookupLevel(logger.level) <= level) { var method = logger.methodMap[level]; if (!console[method]) { // eslint-disable-line no-console method = 'log'; } for (var _len = arguments.length, message = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { message[_key - 1] = arguments[_key]; } console[method].apply(console, message); // eslint-disable-line no-console } } }; exports['default'] = logger; module.exports = exports['default']; /***/ }), /* 21 */ /***/ (function(module, exports) { // Build out our basic SafeString type 'use strict'; exports.__esModule = true; function SafeString(string) { this.string = string; } SafeString.prototype.toString = SafeString.prototype.toHTML = function () { return '' + this.string; }; exports['default'] = SafeString; module.exports = exports['default']; /***/ }), /* 22 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _Object$seal = __webpack_require__(23)['default']; var _interopRequireWildcard = __webpack_require__(3)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; exports.checkRevision = checkRevision; exports.template = template; exports.wrapProgram = wrapProgram; exports.resolvePartial = resolvePartial; exports.invokePartial = invokePartial; exports.noop = noop; var _utils = __webpack_require__(5); var Utils = _interopRequireWildcard(_utils); var _exception = __webpack_require__(6); var _exception2 = _interopRequireDefault(_exception); var _base = __webpack_require__(4); function checkRevision(compilerInfo) { var compilerRevision = compilerInfo && compilerInfo[0] || 1, currentRevision = _base.COMPILER_REVISION; if (compilerRevision !== currentRevision) { if (compilerRevision < currentRevision) { var runtimeVersions = _base.REVISION_CHANGES[currentRevision], compilerVersions = _base.REVISION_CHANGES[compilerRevision]; throw new _exception2['default']('Template was precompiled with an older version of Handlebars than the current runtime. ' + 'Please update your precompiler to a newer version (' + runtimeVersions + ') or downgrade your runtime to an older version (' + compilerVersions + ').'); } else { // Use the embedded version info since the runtime doesn't know about this revision yet throw new _exception2['default']('Template was precompiled with a newer version of Handlebars than the current runtime. ' + 'Please update your runtime to a newer version (' + compilerInfo[1] + ').'); } } } function template(templateSpec, env) { /* istanbul ignore next */ if (!env) { throw new _exception2['default']('No environment passed to template'); } if (!templateSpec || !templateSpec.main) { throw new _exception2['default']('Unknown template object: ' + typeof templateSpec); } templateSpec.main.decorator = templateSpec.main_d; // Note: Using env.VM references rather than local var references throughout this section to allow // for external users to override these as psuedo-supported APIs. env.VM.checkRevision(templateSpec.compiler); function invokePartialWrapper(partial, context, options) { if (options.hash) { context = Utils.extend({}, context, options.hash); if (options.ids) { options.ids[0] = true; } } partial = env.VM.resolvePartial.call(this, partial, context, options); var result = env.VM.invokePartial.call(this, partial, context, options); if (result == null && env.compile) { options.partials[options.name] = env.compile(partial, templateSpec.compilerOptions, env); result = options.partials[options.name](context, options); } if (result != null) { if (options.indent) { var lines = result.split('\n'); for (var i = 0, l = lines.length; i < l; i++) { if (!lines[i] && i + 1 === l) { break; } lines[i] = options.indent + lines[i]; } result = lines.join('\n'); } return result; } else { throw new _exception2['default']('The partial ' + options.name + ' could not be compiled when running in runtime-only mode'); } } // Just add water var container = { strict: function strict(obj, name) { if (!(name in obj)) { throw new _exception2['default']('"' + name + '" not defined in ' + obj); } return obj[name]; }, lookup: function lookup(depths, name) { var len = depths.length; for (var i = 0; i < len; i++) { if (depths[i] && depths[i][name] != null) { return depths[i][name]; } } }, lambda: function lambda(current, context) { return typeof current === 'function' ? current.call(context) : current; }, escapeExpression: Utils.escapeExpression, invokePartial: invokePartialWrapper, fn: function fn(i) { var ret = templateSpec[i]; ret.decorator = templateSpec[i + '_d']; return ret; }, programs: [], program: function program(i, data, declaredBlockParams, blockParams, depths) { var programWrapper = this.programs[i], fn = this.fn(i); if (data || depths || blockParams || declaredBlockParams) { programWrapper = wrapProgram(this, i, fn, data, declaredBlockParams, blockParams, depths); } else if (!programWrapper) { programWrapper = this.programs[i] = wrapProgram(this, i, fn); } return programWrapper; }, data: function data(value, depth) { while (value && depth--) { value = value._parent; } return value; }, merge: function merge(param, common) { var obj = param || common; if (param && common && param !== common) { obj = Utils.extend({}, common, param); } return obj; }, // An empty object to use as replacement for null-contexts nullContext: _Object$seal({}), noop: env.VM.noop, compilerInfo: templateSpec.compiler }; function ret(context) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var data = options.data; ret._setup(options); if (!options.partial && templateSpec.useData) { data = initData(context, data); } var depths = undefined, blockParams = templateSpec.useBlockParams ? [] : undefined; if (templateSpec.useDepths) { if (options.depths) { depths = context != options.depths[0] ? [context].concat(options.depths) : options.depths; } else { depths = [context]; } } function main(context /*, options*/) { return '' + templateSpec.main(container, context, container.helpers, container.partials, data, blockParams, depths); } main = executeDecorators(templateSpec.main, main, container, options.depths || [], data, blockParams); return main(context, options); } ret.isTop = true; ret._setup = function (options) { if (!options.partial) { container.helpers = container.merge(options.helpers, env.helpers); if (templateSpec.usePartial) { container.partials = container.merge(options.partials, env.partials); } if (templateSpec.usePartial || templateSpec.useDecorators) { container.decorators = container.merge(options.decorators, env.decorators); } } else { container.helpers = options.helpers; container.partials = options.partials; container.decorators = options.decorators; } }; ret._child = function (i, data, blockParams, depths) { if (templateSpec.useBlockParams && !blockParams) { throw new _exception2['default']('must pass block params'); } if (templateSpec.useDepths && !depths) { throw new _exception2['default']('must pass parent depths'); } return wrapProgram(container, i, templateSpec[i], data, 0, blockParams, depths); }; return ret; } function wrapProgram(container, i, fn, data, declaredBlockParams, blockParams, depths) { function prog(context) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var currentDepths = depths; if (depths && context != depths[0] && !(context === container.nullContext && depths[0] === null)) { currentDepths = [context].concat(depths); } return fn(container, context, container.helpers, container.partials, options.data || data, blockParams && [options.blockParams].concat(blockParams), currentDepths); } prog = executeDecorators(fn, prog, container, depths, data, blockParams); prog.program = i; prog.depth = depths ? depths.length : 0; prog.blockParams = declaredBlockParams || 0; return prog; } function resolvePartial(partial, context, options) { if (!partial) { if (options.name === '@partial-block') { partial = options.data['partial-block']; } else { partial = options.partials[options.name]; } } else if (!partial.call && !options.name) { // This is a dynamic partial that returned a string options.name = partial; partial = options.partials[partial]; } return partial; } function invokePartial(partial, context, options) { // Use the current closure context to save the partial-block if this partial var currentPartialBlock = options.data && options.data['partial-block']; options.partial = true; if (options.ids) { options.data.contextPath = options.ids[0] || options.data.contextPath; } var partialBlock = undefined; if (options.fn && options.fn !== noop) { (function () { options.data = _base.createFrame(options.data); // Wrapper function to get access to currentPartialBlock from the closure var fn = options.fn; partialBlock = options.data['partial-block'] = function partialBlockWrapper(context) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; // Restore the partial-block from the closure for the execution of the block // i.e. the part inside the block of the partial call. options.data = _base.createFrame(options.data); options.data['partial-block'] = currentPartialBlock; return fn(context, options); }; if (fn.partials) { options.partials = Utils.extend({}, options.partials, fn.partials); } })(); } if (partial === undefined && partialBlock) { partial = partialBlock; } if (partial === undefined) { throw new _exception2['default']('The partial ' + options.name + ' could not be found'); } else if (partial instanceof Function) { return partial(context, options); } } function noop() { return ''; } function initData(context, data) { if (!data || !('root' in data)) { data = data ? _base.createFrame(data) : {}; data.root = context; } return data; } function executeDecorators(fn, prog, container, depths, data, blockParams) { if (fn.decorator) { var props = {}; prog = fn.decorator(prog, props, container, depths && depths[0], data, blockParams, depths); Utils.extend(prog, props); } return prog; } /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(24), __esModule: true }; /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(25); module.exports = __webpack_require__(30).Object.seal; /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.17 Object.seal(O) var isObject = __webpack_require__(26); __webpack_require__(27)('seal', function($seal){ return function seal(it){ return $seal && isObject(it) ? $seal(it) : it; }; }); /***/ }), /* 26 */ /***/ (function(module, exports) { module.exports = function(it){ return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }), /* 27 */ /***/ (function(module, exports, __webpack_require__) { // most Object methods by ES6 should accept primitives var $export = __webpack_require__(28) , core = __webpack_require__(30) , fails = __webpack_require__(33); module.exports = function(KEY, exec){ var fn = (core.Object || {})[KEY] || Object[KEY] , exp = {}; exp[KEY] = exec(fn); $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp); }; /***/ }), /* 28 */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(29) , core = __webpack_require__(30) , ctx = __webpack_require__(31) , PROTOTYPE = 'prototype'; var $export = function(type, name, source){ var IS_FORCED = type & $export.F , IS_GLOBAL = type & $export.G , IS_STATIC = type & $export.S , IS_PROTO = type & $export.P , IS_BIND = type & $export.B , IS_WRAP = type & $export.W , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE] , key, own, out; if(IS_GLOBAL)source = name; for(key in source){ // contains in native own = !IS_FORCED && target && key in target; if(own && key in exports)continue; // export native or passed out = own ? target[key] : source[key]; // prevent global pollution for namespaces exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] // bind timers to global for call from export context : IS_BIND && own ? ctx(out, global) // wrap global constructors for prevent change them in library : IS_WRAP && target[key] == out ? (function(C){ var F = function(param){ return this instanceof C ? new C(param) : C(param); }; F[PROTOTYPE] = C[PROTOTYPE]; return F; // make static versions for prototype methods })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; if(IS_PROTO)(exports[PROTOTYPE] || (exports[PROTOTYPE] = {}))[key] = out; } }; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap module.exports = $export; /***/ }), /* 29 */ /***/ (function(module, exports) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef /***/ }), /* 30 */ /***/ (function(module, exports) { var core = module.exports = {version: '1.2.6'}; if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef /***/ }), /* 31 */ /***/ (function(module, exports, __webpack_require__) { // optional / simple context binding var aFunction = __webpack_require__(32); module.exports = function(fn, that, length){ aFunction(fn); if(that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); }; case 2: return function(a, b){ return fn.call(that, a, b); }; case 3: return function(a, b, c){ return fn.call(that, a, b, c); }; } return function(/* ...args */){ return fn.apply(that, arguments); }; }; /***/ }), /* 32 */ /***/ (function(module, exports) { module.exports = function(it){ if(typeof it != 'function')throw TypeError(it + ' is not a function!'); return it; }; /***/ }), /* 33 */ /***/ (function(module, exports) { module.exports = function(exec){ try { return !!exec(); } catch(e){ return true; } }; /***/ }), /* 34 */ /***/ (function(module, exports) { /* WEBPACK VAR INJECTION */(function(global) {/* global window */ 'use strict'; exports.__esModule = true; exports['default'] = function (Handlebars) { /* istanbul ignore next */ var root = typeof global !== 'undefined' ? global : window, $Handlebars = root.Handlebars; /* istanbul ignore next */ Handlebars.noConflict = function () { if (root.Handlebars === Handlebars) { root.Handlebars = $Handlebars; } return Handlebars; }; }; module.exports = exports['default']; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }), /* 35 */ /***/ (function(module, exports) { 'use strict'; exports.__esModule = true; var AST = { // Public API used to evaluate derived attributes regarding AST nodes helpers: { // a mustache is definitely a helper if: // * it is an eligible helper, and // * it has at least one parameter or hash segment helperExpression: function helperExpression(node) { return node.type === 'SubExpression' || (node.type === 'MustacheStatement' || node.type === 'BlockStatement') && !!(node.params && node.params.length || node.hash); }, scopedId: function scopedId(path) { return (/^\.|this\b/.test(path.original) ); }, // an ID is simple if it only has one part, and that part is not // `..` or `this`. simpleId: function simpleId(path) { return path.parts.length === 1 && !AST.helpers.scopedId(path) && !path.depth; } } }; // Must be exported as an object rather than the root of the module as the jison lexer // must modify the object to operate properly. exports['default'] = AST; module.exports = exports['default']; /***/ }), /* 36 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireDefault = __webpack_require__(1)['default']; var _interopRequireWildcard = __webpack_require__(3)['default']; exports.__esModule = true; exports.parse = parse; var _parser = __webpack_require__(37); var _parser2 = _interopRequireDefault(_parser); var _whitespaceControl = __webpack_require__(38); var _whitespaceControl2 = _interopRequireDefault(_whitespaceControl); var _helpers = __webpack_require__(40); var Helpers = _interopRequireWildcard(_helpers); var _utils = __webpack_require__(5); exports.parser = _parser2['default']; var yy = {}; _utils.extend(yy, Helpers); function parse(input, options) { // Just return if an already-compiled AST was passed in. if (input.type === 'Program') { return input; } _parser2['default'].yy = yy; // Altering the shared object here, but this is ok as parser is a sync operation yy.locInfo = function (locInfo) { return new yy.SourceLocation(options && options.srcName, locInfo); }; var strip = new _whitespaceControl2['default'](options); return strip.accept(_parser2['default'].parse(input)); } /***/ }), /* 37 */ /***/ (function(module, exports) { // File ignored in coverage tests via setting in .istanbul.yml /* Jison generated parser */ "use strict"; exports.__esModule = true; var handlebars = (function () { var parser = { trace: function trace() {}, yy: {}, symbols_: { "error": 2, "root": 3, "program": 4, "EOF": 5, "program_repetition0": 6, "statement": 7, "mustache": 8, "block": 9, "rawBlock": 10, "partial": 11, "partialBlock": 12, "content": 13, "COMMENT": 14, "CONTENT": 15, "openRawBlock": 16, "rawBlock_repetition_plus0": 17, "END_RAW_BLOCK": 18, "OPEN_RAW_BLOCK": 19, "helperName": 20, "openRawBlock_repetition0": 21, "openRawBlock_option0": 22, "CLOSE_RAW_BLOCK": 23, "openBlock": 24, "block_option0": 25, "closeBlock": 26, "openInverse": 27, "block_option1": 28, "OPEN_BLOCK": 29, "openBlock_repetition0": 30, "openBlock_option0": 31, "openBlock_option1": 32, "CLOSE": 33, "OPEN_INVERSE": 34, "openInverse_repetition0": 35, "openInverse_option0": 36, "openInverse_option1": 37, "openInverseChain": 38, "OPEN_INVERSE_CHAIN": 39, "openInverseChain_repetition0": 40, "openInverseChain_option0": 41, "openInverseChain_option1": 42, "inverseAndProgram": 43, "INVERSE": 44, "inverseChain": 45, "inverseChain_option0": 46, "OPEN_ENDBLOCK": 47, "OPEN": 48, "mustache_repetition0": 49, "mustache_option0": 50, "OPEN_UNESCAPED": 51, "mustache_repetition1": 52, "mustache_option1": 53, "CLOSE_UNESCAPED": 54, "OPEN_PARTIAL": 55, "partialName": 56, "partial_repetition0": 57, "partial_option0": 58, "openPartialBlock": 59, "OPEN_PARTIAL_BLOCK": 60, "openPartialBlock_repetition0": 61, "openPartialBlock_option0": 62, "param": 63, "sexpr": 64, "OPEN_SEXPR": 65, "sexpr_repetition0": 66, "sexpr_option0": 67, "CLOSE_SEXPR": 68, "hash": 69, "hash_repetition_plus0": 70, "hashSegment": 71, "ID": 72, "EQUALS": 73, "blockParams": 74, "OPEN_BLOCK_PARAMS": 75, "blockParams_repetition_plus0": 76, "CLOSE_BLOCK_PARAMS": 77, "path": 78, "dataName": 79, "STRING": 80, "NUMBER": 81, "BOOLEAN": 82, "UNDEFINED": 83, "NULL": 84, "DATA": 85, "pathSegments": 86, "SEP": 87, "$accept": 0, "$end": 1 }, terminals_: { 2: "error", 5: "EOF", 14: "COMMENT", 15: "CONTENT", 18: "END_RAW_BLOCK", 19: "OPEN_RAW_BLOCK", 23: "CLOSE_RAW_BLOCK", 29: "OPEN_BLOCK", 33: "CLOSE", 34: "OPEN_INVERSE", 39: "OPEN_INVERSE_CHAIN", 44: "INVERSE", 47: "OPEN_ENDBLOCK", 48: "OPEN", 51: "OPEN_UNESCAPED", 54: "CLOSE_UNESCAPED", 55: "OPEN_PARTIAL", 60: "OPEN_PARTIAL_BLOCK", 65: "OPEN_SEXPR", 68: "CLOSE_SEXPR", 72: "ID", 73: "EQUALS", 75: "OPEN_BLOCK_PARAMS", 77: "CLOSE_BLOCK_PARAMS", 80: "STRING", 81: "NUMBER", 82: "BOOLEAN", 83: "UNDEFINED", 84: "NULL", 85: "DATA", 87: "SEP" }, productions_: [0, [3, 2], [4, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [13, 1], [10, 3], [16, 5], [9, 4], [9, 4], [24, 6], [27, 6], [38, 6], [43, 2], [45, 3], [45, 1], [26, 3], [8, 5], [8, 5], [11, 5], [12, 3], [59, 5], [63, 1], [63, 1], [64, 5], [69, 1], [71, 3], [74, 3], [20, 1], [20, 1], [20, 1], [20, 1], [20, 1], [20, 1], [20, 1], [56, 1], [56, 1], [79, 2], [78, 1], [86, 3], [86, 1], [6, 0], [6, 2], [17, 1], [17, 2], [21, 0], [21, 2], [22, 0], [22, 1], [25, 0], [25, 1], [28, 0], [28, 1], [30, 0], [30, 2], [31, 0], [31, 1], [32, 0], [32, 1], [35, 0], [35, 2], [36, 0], [36, 1], [37, 0], [37, 1], [40, 0], [40, 2], [41, 0], [41, 1], [42, 0], [42, 1], [46, 0], [46, 1], [49, 0], [49, 2], [50, 0], [50, 1], [52, 0], [52, 2], [53, 0], [53, 1], [57, 0], [57, 2], [58, 0], [58, 1], [61, 0], [61, 2], [62, 0], [62, 1], [66, 0], [66, 2], [67, 0], [67, 1], [70, 1], [70, 2], [76, 1], [76, 2]], performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$ /**/) { var $0 = $$.length - 1; switch (yystate) { case 1: return $$[$0 - 1]; break; case 2: this.$ = yy.prepareProgram($$[$0]); break; case 3: this.$ = $$[$0]; break; case 4: this.$ = $$[$0]; break; case 5: this.$ = $$[$0]; break; case 6: this.$ = $$[$0]; break; case 7: this.$ = $$[$0]; break; case 8: this.$ = $$[$0]; break; case 9: this.$ = { type: 'CommentStatement', value: yy.stripComment($$[$0]), strip: yy.stripFlags($$[$0], $$[$0]), loc: yy.locInfo(this._$) }; break; case 10: this.$ = { type: 'ContentStatement', original: $$[$0], value: $$[$0], loc: yy.locInfo(this._$) }; break; case 11: this.$ = yy.prepareRawBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$); break; case 12: this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1] }; break; case 13: this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], false, this._$); break; case 14: this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], true, this._$); break; case 15: this.$ = { open: $$[$0 - 5], path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) }; break; case 16: this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) }; break; case 17: this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) }; break; case 18: this.$ = { strip: yy.stripFlags($$[$0 - 1], $$[$0 - 1]), program: $$[$0] }; break; case 19: var inverse = yy.prepareBlock($$[$0 - 2], $$[$0 - 1], $$[$0], $$[$0], false, this._$), program = yy.prepareProgram([inverse], $$[$0 - 1].loc); program.chained = true; this.$ = { strip: $$[$0 - 2].strip, program: program, chain: true }; break; case 20: this.$ = $$[$0]; break; case 21: this.$ = { path: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 2], $$[$0]) }; break; case 22: this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$); break; case 23: this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$); break; case 24: this.$ = { type: 'PartialStatement', name: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1], indent: '', strip: yy.stripFlags($$[$0 - 4], $$[$0]), loc: yy.locInfo(this._$) }; break; case 25: this.$ = yy.preparePartialBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$); break; case 26: this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 4], $$[$0]) }; break; case 27: this.$ = $$[$0]; break; case 28: this.$ = $$[$0]; break; case 29: this.$ = { type: 'SubExpression', path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1], loc: yy.locInfo(this._$) }; break; case 30: this.$ = { type: 'Hash', pairs: $$[$0], loc: yy.locInfo(this._$) }; break; case 31: this.$ = { type: 'HashPair', key: yy.id($$[$0 - 2]), value: $$[$0], loc: yy.locInfo(this._$) }; break; case 32: this.$ = yy.id($$[$0 - 1]); break; case 33: this.$ = $$[$0]; break; case 34: this.$ = $$[$0]; break; case 35: this.$ = { type: 'StringLiteral', value: $$[$0], original: $$[$0], loc: yy.locInfo(this._$) }; break; case 36: this.$ = { type: 'NumberLiteral', value: Number($$[$0]), original: Number($$[$0]), loc: yy.locInfo(this._$) }; break; case 37: this.$ = { type: 'BooleanLiteral', value: $$[$0] === 'true', original: $$[$0] === 'true', loc: yy.locInfo(this._$) }; break; case 38: this.$ = { type: 'UndefinedLiteral', original: undefined, value: undefined, loc: yy.locInfo(this._$) }; break; case 39: this.$ = { type: 'NullLiteral', original: null, value: null, loc: yy.locInfo(this._$) }; break; case 40: this.$ = $$[$0]; break; case 41: this.$ = $$[$0]; break; case 42: this.$ = yy.preparePath(true, $$[$0], this._$); break; case 43: this.$ = yy.preparePath(false, $$[$0], this._$); break; case 44: $$[$0 - 2].push({ part: yy.id($$[$0]), original: $$[$0], separator: $$[$0 - 1] });this.$ = $$[$0 - 2]; break; case 45: this.$ = [{ part: yy.id($$[$0]), original: $$[$0] }]; break; case 46: this.$ = []; break; case 47: $$[$0 - 1].push($$[$0]); break; case 48: this.$ = [$$[$0]]; break; case 49: $$[$0 - 1].push($$[$0]); break; case 50: this.$ = []; break; case 51: $$[$0 - 1].push($$[$0]); break; case 58: this.$ = []; break; case 59: $$[$0 - 1].push($$[$0]); break; case 64: this.$ = []; break; case 65: $$[$0 - 1].push($$[$0]); break; case 70: this.$ = []; break; case 71: $$[$0 - 1].push($$[$0]); break; case 78: this.$ = []; break; case 79: $$[$0 - 1].push($$[$0]); break; case 82: this.$ = []; break; case 83: $$[$0 - 1].push($$[$0]); break; case 86: this.$ = []; break; case 87: $$[$0 - 1].push($$[$0]); break; case 90: this.$ = []; break; case 91: $$[$0 - 1].push($$[$0]); break; case 94: this.$ = []; break; case 95: $$[$0 - 1].push($$[$0]); break; case 98: this.$ = [$$[$0]]; break; case 99: $$[$0 - 1].push($$[$0]); break; case 100: this.$ = [$$[$0]]; break; case 101: $$[$0 - 1].push($$[$0]); break; } }, table: [{ 3: 1, 4: 2, 5: [2, 46], 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 1: [3] }, { 5: [1, 4] }, { 5: [2, 2], 7: 5, 8: 6, 9: 7, 10: 8, 11: 9, 12: 10, 13: 11, 14: [1, 12], 15: [1, 20], 16: 17, 19: [1, 23], 24: 15, 27: 16, 29: [1, 21], 34: [1, 22], 39: [2, 2], 44: [2, 2], 47: [2, 2], 48: [1, 13], 51: [1, 14], 55: [1, 18], 59: 19, 60: [1, 24] }, { 1: [2, 1] }, { 5: [2, 47], 14: [2, 47], 15: [2, 47], 19: [2, 47], 29: [2, 47], 34: [2, 47], 39: [2, 47], 44: [2, 47], 47: [2, 47], 48: [2, 47], 51: [2, 47], 55: [2, 47], 60: [2, 47] }, { 5: [2, 3], 14: [2, 3], 15: [2, 3], 19: [2, 3], 29: [2, 3], 34: [2, 3], 39: [2, 3], 44: [2, 3], 47: [2, 3], 48: [2, 3], 51: [2, 3], 55: [2, 3], 60: [2, 3] }, { 5: [2, 4], 14: [2, 4], 15: [2, 4], 19: [2, 4], 29: [2, 4], 34: [2, 4], 39: [2, 4], 44: [2, 4], 47: [2, 4], 48: [2, 4], 51: [2, 4], 55: [2, 4], 60: [2, 4] }, { 5: [2, 5], 14: [2, 5], 15: [2, 5], 19: [2, 5], 29: [2, 5], 34: [2, 5], 39: [2, 5], 44: [2, 5], 47: [2, 5], 48: [2, 5], 51: [2, 5], 55: [2, 5], 60: [2, 5] }, { 5: [2, 6], 14: [2, 6], 15: [2, 6], 19: [2, 6], 29: [2, 6], 34: [2, 6], 39: [2, 6], 44: [2, 6], 47: [2, 6], 48: [2, 6], 51: [2, 6], 55: [2, 6], 60: [2, 6] }, { 5: [2, 7], 14: [2, 7], 15: [2, 7], 19: [2, 7], 29: [2, 7], 34: [2, 7], 39: [2, 7], 44: [2, 7], 47: [2, 7], 48: [2, 7], 51: [2, 7], 55: [2, 7], 60: [2, 7] }, { 5: [2, 8], 14: [2, 8], 15: [2, 8], 19: [2, 8], 29: [2, 8], 34: [2, 8], 39: [2, 8], 44: [2, 8], 47: [2, 8], 48: [2, 8], 51: [2, 8], 55: [2, 8], 60: [2, 8] }, { 5: [2, 9], 14: [2, 9], 15: [2, 9], 19: [2, 9], 29: [2, 9], 34: [2, 9], 39: [2, 9], 44: [2, 9], 47: [2, 9], 48: [2, 9], 51: [2, 9], 55: [2, 9], 60: [2, 9] }, { 20: 25, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 36, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 37, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 39: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 4: 38, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 13: 40, 15: [1, 20], 17: 39 }, { 20: 42, 56: 41, 64: 43, 65: [1, 44], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 45, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 5: [2, 10], 14: [2, 10], 15: [2, 10], 18: [2, 10], 19: [2, 10], 29: [2, 10], 34: [2, 10], 39: [2, 10], 44: [2, 10], 47: [2, 10], 48: [2, 10], 51: [2, 10], 55: [2, 10], 60: [2, 10] }, { 20: 46, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 47, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 48, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 42, 56: 49, 64: 43, 65: [1, 44], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [2, 78], 49: 50, 65: [2, 78], 72: [2, 78], 80: [2, 78], 81: [2, 78], 82: [2, 78], 83: [2, 78], 84: [2, 78], 85: [2, 78] }, { 23: [2, 33], 33: [2, 33], 54: [2, 33], 65: [2, 33], 68: [2, 33], 72: [2, 33], 75: [2, 33], 80: [2, 33], 81: [2, 33], 82: [2, 33], 83: [2, 33], 84: [2, 33], 85: [2, 33] }, { 23: [2, 34], 33: [2, 34], 54: [2, 34], 65: [2, 34], 68: [2, 34], 72: [2, 34], 75: [2, 34], 80: [2, 34], 81: [2, 34], 82: [2, 34], 83: [2, 34], 84: [2, 34], 85: [2, 34] }, { 23: [2, 35], 33: [2, 35], 54: [2, 35], 65: [2, 35], 68: [2, 35], 72: [2, 35], 75: [2, 35], 80: [2, 35], 81: [2, 35], 82: [2, 35], 83: [2, 35], 84: [2, 35], 85: [2, 35] }, { 23: [2, 36], 33: [2, 36], 54: [2, 36], 65: [2, 36], 68: [2, 36], 72: [2, 36], 75: [2, 36], 80: [2, 36], 81: [2, 36], 82: [2, 36], 83: [2, 36], 84: [2, 36], 85: [2, 36] }, { 23: [2, 37], 33: [2, 37], 54: [2, 37], 65: [2, 37], 68: [2, 37], 72: [2, 37], 75: [2, 37], 80: [2, 37], 81: [2, 37], 82: [2, 37], 83: [2, 37], 84: [2, 37], 85: [2, 37] }, { 23: [2, 38], 33: [2, 38], 54: [2, 38], 65: [2, 38], 68: [2, 38], 72: [2, 38], 75: [2, 38], 80: [2, 38], 81: [2, 38], 82: [2, 38], 83: [2, 38], 84: [2, 38], 85: [2, 38] }, { 23: [2, 39], 33: [2, 39], 54: [2, 39], 65: [2, 39], 68: [2, 39], 72: [2, 39], 75: [2, 39], 80: [2, 39], 81: [2, 39], 82: [2, 39], 83: [2, 39], 84: [2, 39], 85: [2, 39] }, { 23: [2, 43], 33: [2, 43], 54: [2, 43], 65: [2, 43], 68: [2, 43], 72: [2, 43], 75: [2, 43], 80: [2, 43], 81: [2, 43], 82: [2, 43], 83: [2, 43], 84: [2, 43], 85: [2, 43], 87: [1, 51] }, { 72: [1, 35], 86: 52 }, { 23: [2, 45], 33: [2, 45], 54: [2, 45], 65: [2, 45], 68: [2, 45], 72: [2, 45], 75: [2, 45], 80: [2, 45], 81: [2, 45], 82: [2, 45], 83: [2, 45], 84: [2, 45], 85: [2, 45], 87: [2, 45] }, { 52: 53, 54: [2, 82], 65: [2, 82], 72: [2, 82], 80: [2, 82], 81: [2, 82], 82: [2, 82], 83: [2, 82], 84: [2, 82], 85: [2, 82] }, { 25: 54, 38: 56, 39: [1, 58], 43: 57, 44: [1, 59], 45: 55, 47: [2, 54] }, { 28: 60, 43: 61, 44: [1, 59], 47: [2, 56] }, { 13: 63, 15: [1, 20], 18: [1, 62] }, { 15: [2, 48], 18: [2, 48] }, { 33: [2, 86], 57: 64, 65: [2, 86], 72: [2, 86], 80: [2, 86], 81: [2, 86], 82: [2, 86], 83: [2, 86], 84: [2, 86], 85: [2, 86] }, { 33: [2, 40], 65: [2, 40], 72: [2, 40], 80: [2, 40], 81: [2, 40], 82: [2, 40], 83: [2, 40], 84: [2, 40], 85: [2, 40] }, { 33: [2, 41], 65: [2, 41], 72: [2, 41], 80: [2, 41], 81: [2, 41], 82: [2, 41], 83: [2, 41], 84: [2, 41], 85: [2, 41] }, { 20: 65, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 26: 66, 47: [1, 67] }, { 30: 68, 33: [2, 58], 65: [2, 58], 72: [2, 58], 75: [2, 58], 80: [2, 58], 81: [2, 58], 82: [2, 58], 83: [2, 58], 84: [2, 58], 85: [2, 58] }, { 33: [2, 64], 35: 69, 65: [2, 64], 72: [2, 64], 75: [2, 64], 80: [2, 64], 81: [2, 64], 82: [2, 64], 83: [2, 64], 84: [2, 64], 85: [2, 64] }, { 21: 70, 23: [2, 50], 65: [2, 50], 72: [2, 50], 80: [2, 50], 81: [2, 50], 82: [2, 50], 83: [2, 50], 84: [2, 50], 85: [2, 50] }, { 33: [2, 90], 61: 71, 65: [2, 90], 72: [2, 90], 80: [2, 90], 81: [2, 90], 82: [2, 90], 83: [2, 90], 84: [2, 90], 85: [2, 90] }, { 20: 75, 33: [2, 80], 50: 72, 63: 73, 64: 76, 65: [1, 44], 69: 74, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 72: [1, 80] }, { 23: [2, 42], 33: [2, 42], 54: [2, 42], 65: [2, 42], 68: [2, 42], 72: [2, 42], 75: [2, 42], 80: [2, 42], 81: [2, 42], 82: [2, 42], 83: [2, 42], 84: [2, 42], 85: [2, 42], 87: [1, 51] }, { 20: 75, 53: 81, 54: [2, 84], 63: 82, 64: 76, 65: [1, 44], 69: 83, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 26: 84, 47: [1, 67] }, { 47: [2, 55] }, { 4: 85, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 39: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 47: [2, 20] }, { 20: 86, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 87, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 26: 88, 47: [1, 67] }, { 47: [2, 57] }, { 5: [2, 11], 14: [2, 11], 15: [2, 11], 19: [2, 11], 29: [2, 11], 34: [2, 11], 39: [2, 11], 44: [2, 11], 47: [2, 11], 48: [2, 11], 51: [2, 11], 55: [2, 11], 60: [2, 11] }, { 15: [2, 49], 18: [2, 49] }, { 20: 75, 33: [2, 88], 58: 89, 63: 90, 64: 76, 65: [1, 44], 69: 91, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 65: [2, 94], 66: 92, 68: [2, 94], 72: [2, 94], 80: [2, 94], 81: [2, 94], 82: [2, 94], 83: [2, 94], 84: [2, 94], 85: [2, 94] }, { 5: [2, 25], 14: [2, 25], 15: [2, 25], 19: [2, 25], 29: [2, 25], 34: [2, 25], 39: [2, 25], 44: [2, 25], 47: [2, 25], 48: [2, 25], 51: [2, 25], 55: [2, 25], 60: [2, 25] }, { 20: 93, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 31: 94, 33: [2, 60], 63: 95, 64: 76, 65: [1, 44], 69: 96, 70: 77, 71: 78, 72: [1, 79], 75: [2, 60], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 33: [2, 66], 36: 97, 63: 98, 64: 76, 65: [1, 44], 69: 99, 70: 77, 71: 78, 72: [1, 79], 75: [2, 66], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 22: 100, 23: [2, 52], 63: 101, 64: 76, 65: [1, 44], 69: 102, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 33: [2, 92], 62: 103, 63: 104, 64: 76, 65: [1, 44], 69: 105, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [1, 106] }, { 33: [2, 79], 65: [2, 79], 72: [2, 79], 80: [2, 79], 81: [2, 79], 82: [2, 79], 83: [2, 79], 84: [2, 79], 85: [2, 79] }, { 33: [2, 81] }, { 23: [2, 27], 33: [2, 27], 54: [2, 27], 65: [2, 27], 68: [2, 27], 72: [2, 27], 75: [2, 27], 80: [2, 27], 81: [2, 27], 82: [2, 27], 83: [2, 27], 84: [2, 27], 85: [2, 27] }, { 23: [2, 28], 33: [2, 28], 54: [2, 28], 65: [2, 28], 68: [2, 28], 72: [2, 28], 75: [2, 28], 80: [2, 28], 81: [2, 28], 82: [2, 28], 83: [2, 28], 84: [2, 28], 85: [2, 28] }, { 23: [2, 30], 33: [2, 30], 54: [2, 30], 68: [2, 30], 71: 107, 72: [1, 108], 75: [2, 30] }, { 23: [2, 98], 33: [2, 98], 54: [2, 98], 68: [2, 98], 72: [2, 98], 75: [2, 98] }, { 23: [2, 45], 33: [2, 45], 54: [2, 45], 65: [2, 45], 68: [2, 45], 72: [2, 45], 73: [1, 109], 75: [2, 45], 80: [2, 45], 81: [2, 45], 82: [2, 45], 83: [2, 45], 84: [2, 45], 85: [2, 45], 87: [2, 45] }, { 23: [2, 44], 33: [2, 44], 54: [2, 44], 65: [2, 44], 68: [2, 44], 72: [2, 44], 75: [2, 44], 80: [2, 44], 81: [2, 44], 82: [2, 44], 83: [2, 44], 84: [2, 44], 85: [2, 44], 87: [2, 44] }, { 54: [1, 110] }, { 54: [2, 83], 65: [2, 83], 72: [2, 83], 80: [2, 83], 81: [2, 83], 82: [2, 83], 83: [2, 83], 84: [2, 83], 85: [2, 83] }, { 54: [2, 85] }, { 5: [2, 13], 14: [2, 13], 15: [2, 13], 19: [2, 13], 29: [2, 13], 34: [2, 13], 39: [2, 13], 44: [2, 13], 47: [2, 13], 48: [2, 13], 51: [2, 13], 55: [2, 13], 60: [2, 13] }, { 38: 56, 39: [1, 58], 43: 57, 44: [1, 59], 45: 112, 46: 111, 47: [2, 76] }, { 33: [2, 70], 40: 113, 65: [2, 70], 72: [2, 70], 75: [2, 70], 80: [2, 70], 81: [2, 70], 82: [2, 70], 83: [2, 70], 84: [2, 70], 85: [2, 70] }, { 47: [2, 18] }, { 5: [2, 14], 14: [2, 14], 15: [2, 14], 19: [2, 14], 29: [2, 14], 34: [2, 14], 39: [2, 14], 44: [2, 14], 47: [2, 14], 48: [2, 14], 51: [2, 14], 55: [2, 14], 60: [2, 14] }, { 33: [1, 114] }, { 33: [2, 87], 65: [2, 87], 72: [2, 87], 80: [2, 87], 81: [2, 87], 82: [2, 87], 83: [2, 87], 84: [2, 87], 85: [2, 87] }, { 33: [2, 89] }, { 20: 75, 63: 116, 64: 76, 65: [1, 44], 67: 115, 68: [2, 96], 69: 117, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [1, 118] }, { 32: 119, 33: [2, 62], 74: 120, 75: [1, 121] }, { 33: [2, 59], 65: [2, 59], 72: [2, 59], 75: [2, 59], 80: [2, 59], 81: [2, 59], 82: [2, 59], 83: [2, 59], 84: [2, 59], 85: [2, 59] }, { 33: [2, 61], 75: [2, 61] }, { 33: [2, 68], 37: 122, 74: 123, 75: [1, 121] }, { 33: [2, 65], 65: [2, 65], 72: [2, 65], 75: [2, 65], 80: [2, 65], 81: [2, 65], 82: [2, 65], 83: [2, 65], 84: [2, 65], 85: [2, 65] }, { 33: [2, 67], 75: [2, 67] }, { 23: [1, 124] }, { 23: [2, 51], 65: [2, 51], 72: [2, 51], 80: [2, 51], 81: [2, 51], 82: [2, 51], 83: [2, 51], 84: [2, 51], 85: [2, 51] }, { 23: [2, 53] }, { 33: [1, 125] }, { 33: [2, 91], 65: [2, 91], 72: [2, 91], 80: [2, 91], 81: [2, 91], 82: [2, 91], 83: [2, 91], 84: [2, 91], 85: [2, 91] }, { 33: [2, 93] }, { 5: [2, 22], 14: [2, 22], 15: [2, 22], 19: [2, 22], 29: [2, 22], 34: [2, 22], 39: [2, 22], 44: [2, 22], 47: [2, 22], 48: [2, 22], 51: [2, 22], 55: [2, 22], 60: [2, 22] }, { 23: [2, 99], 33: [2, 99], 54: [2, 99], 68: [2, 99], 72: [2, 99], 75: [2, 99] }, { 73: [1, 109] }, { 20: 75, 63: 126, 64: 76, 65: [1, 44], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 5: [2, 23], 14: [2, 23], 15: [2, 23], 19: [2, 23], 29: [2, 23], 34: [2, 23], 39: [2, 23], 44: [2, 23], 47: [2, 23], 48: [2, 23], 51: [2, 23], 55: [2, 23], 60: [2, 23] }, { 47: [2, 19] }, { 47: [2, 77] }, { 20: 75, 33: [2, 72], 41: 127, 63: 128, 64: 76, 65: [1, 44], 69: 129, 70: 77, 71: 78, 72: [1, 79], 75: [2, 72], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 5: [2, 24], 14: [2, 24], 15: [2, 24], 19: [2, 24], 29: [2, 24], 34: [2, 24], 39: [2, 24], 44: [2, 24], 47: [2, 24], 48: [2, 24], 51: [2, 24], 55: [2, 24], 60: [2, 24] }, { 68: [1, 130] }, { 65: [2, 95], 68: [2, 95], 72: [2, 95], 80: [2, 95], 81: [2, 95], 82: [2, 95], 83: [2, 95], 84: [2, 95], 85: [2, 95] }, { 68: [2, 97] }, { 5: [2, 21], 14: [2, 21], 15: [2, 21], 19: [2, 21], 29: [2, 21], 34: [2, 21], 39: [2, 21], 44: [2, 21], 47: [2, 21], 48: [2, 21], 51: [2, 21], 55: [2, 21], 60: [2, 21] }, { 33: [1, 131] }, { 33: [2, 63] }, { 72: [1, 133], 76: 132 }, { 33: [1, 134] }, { 33: [2, 69] }, { 15: [2, 12] }, { 14: [2, 26], 15: [2, 26], 19: [2, 26], 29: [2, 26], 34: [2, 26], 47: [2, 26], 48: [2, 26], 51: [2, 26], 55: [2, 26], 60: [2, 26] }, { 23: [2, 31], 33: [2, 31], 54: [2, 31], 68: [2, 31], 72: [2, 31], 75: [2, 31] }, { 33: [2, 74], 42: 135, 74: 136, 75: [1, 121] }, { 33: [2, 71], 65: [2, 71], 72: [2, 71], 75: [2, 71], 80: [2, 71], 81: [2, 71], 82: [2, 71], 83: [2, 71], 84: [2, 71], 85: [2, 71] }, { 33: [2, 73], 75: [2, 73] }, { 23: [2, 29], 33: [2, 29], 54: [2, 29], 65: [2, 29], 68: [2, 29], 72: [2, 29], 75: [2, 29], 80: [2, 29], 81: [2, 29], 82: [2, 29], 83: [2, 29], 84: [2, 29], 85: [2, 29] }, { 14: [2, 15], 15: [2, 15], 19: [2, 15], 29: [2, 15], 34: [2, 15], 39: [2, 15], 44: [2, 15], 47: [2, 15], 48: [2, 15], 51: [2, 15], 55: [2, 15], 60: [2, 15] }, { 72: [1, 138], 77: [1, 137] }, { 72: [2, 100], 77: [2, 100] }, { 14: [2, 16], 15: [2, 16], 19: [2, 16], 29: [2, 16], 34: [2, 16], 44: [2, 16], 47: [2, 16], 48: [2, 16], 51: [2, 16], 55: [2, 16], 60: [2, 16] }, { 33: [1, 139] }, { 33: [2, 75] }, { 33: [2, 32] }, { 72: [2, 101], 77: [2, 101] }, { 14: [2, 17], 15: [2, 17], 19: [2, 17], 29: [2, 17], 34: [2, 17], 39: [2, 17], 44: [2, 17], 47: [2, 17], 48: [2, 17], 51: [2, 17], 55: [2, 17], 60: [2, 17] }], defaultActions: { 4: [2, 1], 55: [2, 55], 57: [2, 20], 61: [2, 57], 74: [2, 81], 83: [2, 85], 87: [2, 18], 91: [2, 89], 102: [2, 53], 105: [2, 93], 111: [2, 19], 112: [2, 77], 117: [2, 97], 120: [2, 63], 123: [2, 69], 124: [2, 12], 136: [2, 75], 137: [2, 32] }, parseError: function parseError(str, hash) { throw new Error(str); }, parse: function parse(input) { var self = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = "", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1; this.lexer.setInput(input); this.lexer.yy = this.yy; this.yy.lexer = this.lexer; this.yy.parser = this; if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {}; var yyloc = this.lexer.yylloc; lstack.push(yyloc); var ranges = this.lexer.options && this.lexer.options.ranges; if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError; function popStack(n) { stack.length = stack.length - 2 * n; vstack.length = vstack.length - n; lstack.length = lstack.length - n; } function lex() { var token; token = self.lexer.lex() || 1; if (typeof token !== "number") { token = self.symbols_[token] || token; } return token; } var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected; while (true) { state = stack[stack.length - 1]; if (this.defaultActions[state]) { action = this.defaultActions[state]; } else { if (symbol === null || typeof symbol == "undefined") { symbol = lex(); } action = table[state] && table[state][symbol]; } if (typeof action === "undefined" || !action.length || !action[0]) { var errStr = ""; if (!recovering) { expected = []; for (p in table[state]) if (this.terminals_[p] && p > 2) { expected.push("'" + this.terminals_[p] + "'"); } if (this.lexer.showPosition) { errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'"; } else { errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1 ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'"); } this.parseError(errStr, { text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected }); } } if (action[0] instanceof Array && action.length > 1) { throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol); } switch (action[0]) { case 1: stack.push(symbol); vstack.push(this.lexer.yytext); lstack.push(this.lexer.yylloc); stack.push(action[1]); symbol = null; if (!preErrorSymbol) { yyleng = this.lexer.yyleng; yytext = this.lexer.yytext; yylineno = this.lexer.yylineno; yyloc = this.lexer.yylloc; if (recovering > 0) recovering--; } else { symbol = preErrorSymbol; preErrorSymbol = null; } break; case 2: len = this.productions_[action[1]][1]; yyval.$ = vstack[vstack.length - len]; yyval._$ = { first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column }; if (ranges) { yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]]; } r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack); if (typeof r !== "undefined") { return r; } if (len) { stack = stack.slice(0, -1 * len * 2); vstack = vstack.slice(0, -1 * len); lstack = lstack.slice(0, -1 * len); } stack.push(this.productions_[action[1]][0]); vstack.push(yyval.$); lstack.push(yyval._$); newState = table[stack[stack.length - 2]][stack[stack.length - 1]]; stack.push(newState); break; case 3: return true; } } return true; } }; /* Jison generated lexer */ var lexer = (function () { var lexer = { EOF: 1, parseError: function parseError(str, hash) { if (this.yy.parser) { this.yy.parser.parseError(str, hash); } else { throw new Error(str); } }, setInput: function setInput(input) { this._input = input; this._more = this._less = this.done = false; this.yylineno = this.yyleng = 0; this.yytext = this.matched = this.match = ''; this.conditionStack = ['INITIAL']; this.yylloc = { first_line: 1, first_column: 0, last_line: 1, last_column: 0 }; if (this.options.ranges) this.yylloc.range = [0, 0]; this.offset = 0; return this; }, input: function input() { var ch = this._input[0]; this.yytext += ch; this.yyleng++; this.offset++; this.match += ch; this.matched += ch; var lines = ch.match(/(?:\r\n?|\n).*/g); if (lines) { this.yylineno++; this.yylloc.last_line++; } else { this.yylloc.last_column++; } if (this.options.ranges) this.yylloc.range[1]++; this._input = this._input.slice(1); return ch; }, unput: function unput(ch) { var len = ch.length; var lines = ch.split(/(?:\r\n?|\n)/g); this._input = ch + this._input; this.yytext = this.yytext.substr(0, this.yytext.length - len - 1); //this.yyleng -= len; this.offset -= len; var oldLines = this.match.split(/(?:\r\n?|\n)/g); this.match = this.match.substr(0, this.match.length - 1); this.matched = this.matched.substr(0, this.matched.length - 1); if (lines.length - 1) this.yylineno -= lines.length - 1; var r = this.yylloc.range; this.yylloc = { first_line: this.yylloc.first_line, last_line: this.yylineno + 1, first_column: this.yylloc.first_column, last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len }; if (this.options.ranges) { this.yylloc.range = [r[0], r[0] + this.yyleng - len]; } return this; }, more: function more() { this._more = true; return this; }, less: function less(n) { this.unput(this.match.slice(n)); }, pastInput: function pastInput() { var past = this.matched.substr(0, this.matched.length - this.match.length); return (past.length > 20 ? '...' : '') + past.substr(-20).replace(/\n/g, ""); }, upcomingInput: function upcomingInput() { var next = this.match; if (next.length < 20) { next += this._input.substr(0, 20 - next.length); } return (next.substr(0, 20) + (next.length > 20 ? '...' : '')).replace(/\n/g, ""); }, showPosition: function showPosition() { var pre = this.pastInput(); var c = new Array(pre.length + 1).join("-"); return pre + this.upcomingInput() + "\n" + c + "^"; }, next: function next() { if (this.done) { return this.EOF; } if (!this._input) this.done = true; var token, match, tempMatch, index, col, lines; if (!this._more) { this.yytext = ''; this.match = ''; } var rules = this._currentRules(); for (var i = 0; i < rules.length; i++) { tempMatch = this._input.match(this.rules[rules[i]]); if (tempMatch && (!match || tempMatch[0].length > match[0].length)) { match = tempMatch; index = i; if (!this.options.flex) break; } } if (match) { lines = match[0].match(/(?:\r\n?|\n).*/g); if (lines) this.yylineno += lines.length; this.yylloc = { first_line: this.yylloc.last_line, last_line: this.yylineno + 1, first_column: this.yylloc.last_column, last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length }; this.yytext += match[0]; this.match += match[0]; this.matches = match; this.yyleng = this.yytext.length; if (this.options.ranges) { this.yylloc.range = [this.offset, this.offset += this.yyleng]; } this._more = false; this._input = this._input.slice(match[0].length); this.matched += match[0]; token = this.performAction.call(this, this.yy, this, rules[index], this.conditionStack[this.conditionStack.length - 1]); if (this.done && this._input) this.done = false; if (token) return token;else return; } if (this._input === "") { return this.EOF; } else { return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), { text: "", token: null, line: this.yylineno }); } }, lex: function lex() { var r = this.next(); if (typeof r !== 'undefined') { return r; } else { return this.lex(); } }, begin: function begin(condition) { this.conditionStack.push(condition); }, popState: function popState() { return this.conditionStack.pop(); }, _currentRules: function _currentRules() { return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules; }, topState: function topState() { return this.conditionStack[this.conditionStack.length - 2]; }, pushState: function begin(condition) { this.begin(condition); } }; lexer.options = {}; lexer.performAction = function anonymous(yy, yy_, $avoiding_name_collisions, YY_START /**/) { function strip(start, end) { return yy_.yytext = yy_.yytext.substr(start, yy_.yyleng - end); } var YYSTATE = YY_START; switch ($avoiding_name_collisions) { case 0: if (yy_.yytext.slice(-2) === "\\\\") { strip(0, 1); this.begin("mu"); } else if (yy_.yytext.slice(-1) === "\\") { strip(0, 1); this.begin("emu"); } else { this.begin("mu"); } if (yy_.yytext) return 15; break; case 1: return 15; break; case 2: this.popState(); return 15; break; case 3: this.begin('raw');return 15; break; case 4: this.popState(); // Should be using `this.topState()` below, but it currently // returns the second top instead of the first top. Opened an // issue about it at https://github.com/zaach/jison/issues/291 if (this.conditionStack[this.conditionStack.length - 1] === 'raw') { return 15; } else { yy_.yytext = yy_.yytext.substr(5, yy_.yyleng - 9); return 'END_RAW_BLOCK'; } break; case 5: return 15; break; case 6: this.popState(); return 14; break; case 7: return 65; break; case 8: return 68; break; case 9: return 19; break; case 10: this.popState(); this.begin('raw'); return 23; break; case 11: return 55; break; case 12: return 60; break; case 13: return 29; break; case 14: return 47; break; case 15: this.popState();return 44; break; case 16: this.popState();return 44; break; case 17: return 34; break; case 18: return 39; break; case 19: return 51; break; case 20: return 48; break; case 21: this.unput(yy_.yytext); this.popState(); this.begin('com'); break; case 22: this.popState(); return 14; break; case 23: return 48; break; case 24: return 73; break; case 25: return 72; break; case 26: return 72; break; case 27: return 87; break; case 28: // ignore whitespace break; case 29: this.popState();return 54; break; case 30: this.popState();return 33; break; case 31: yy_.yytext = strip(1, 2).replace(/\\"/g, '"');return 80; break; case 32: yy_.yytext = strip(1, 2).replace(/\\'/g, "'");return 80; break; case 33: return 85; break; case 34: return 82; break; case 35: return 82; break; case 36: return 83; break; case 37: return 84; break; case 38: return 81; break; case 39: return 75; break; case 40: return 77; break; case 41: return 72; break; case 42: yy_.yytext = yy_.yytext.replace(/\\([\\\]])/g, '$1');return 72; break; case 43: return 'INVALID'; break; case 44: return 5; break; } }; lexer.rules = [/^(?:[^\x00]*?(?=(\{\{)))/, /^(?:[^\x00]+)/, /^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/, /^(?:\{\{\{\{(?=[^\/]))/, /^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/, /^(?:[^\x00]*?(?=(\{\{\{\{)))/, /^(?:[\s\S]*?--(~)?\}\})/, /^(?:\()/, /^(?:\))/, /^(?:\{\{\{\{)/, /^(?:\}\}\}\})/, /^(?:\{\{(~)?>)/, /^(?:\{\{(~)?#>)/, /^(?:\{\{(~)?#\*?)/, /^(?:\{\{(~)?\/)/, /^(?:\{\{(~)?\^\s*(~)?\}\})/, /^(?:\{\{(~)?\s*else\s*(~)?\}\})/, /^(?:\{\{(~)?\^)/, /^(?:\{\{(~)?\s*else\b)/, /^(?:\{\{(~)?\{)/, /^(?:\{\{(~)?&)/, /^(?:\{\{(~)?!--)/, /^(?:\{\{(~)?![\s\S]*?\}\})/, /^(?:\{\{(~)?\*?)/, /^(?:=)/, /^(?:\.\.)/, /^(?:\.(?=([=~}\s\/.)|])))/, /^(?:[\/.])/, /^(?:\s+)/, /^(?:\}(~)?\}\})/, /^(?:(~)?\}\})/, /^(?:"(\\["]|[^"])*")/, /^(?:'(\\[']|[^'])*')/, /^(?:@)/, /^(?:true(?=([~}\s)])))/, /^(?:false(?=([~}\s)])))/, /^(?:undefined(?=([~}\s)])))/, /^(?:null(?=([~}\s)])))/, /^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/, /^(?:as\s+\|)/, /^(?:\|)/, /^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/, /^(?:\[(\\\]|[^\]])*\])/, /^(?:.)/, /^(?:$)/]; lexer.conditions = { "mu": { "rules": [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44], "inclusive": false }, "emu": { "rules": [2], "inclusive": false }, "com": { "rules": [6], "inclusive": false }, "raw": { "rules": [3, 4, 5], "inclusive": false }, "INITIAL": { "rules": [0, 1, 44], "inclusive": true } }; return lexer; })(); parser.lexer = lexer; function Parser() { this.yy = {}; }Parser.prototype = parser;parser.Parser = Parser; return new Parser(); })();exports["default"] = handlebars; module.exports = exports["default"]; /***/ }), /* 38 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _visitor = __webpack_require__(39); var _visitor2 = _interopRequireDefault(_visitor); function WhitespaceControl() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; this.options = options; } WhitespaceControl.prototype = new _visitor2['default'](); WhitespaceControl.prototype.Program = function (program) { var doStandalone = !this.options.ignoreStandalone; var isRoot = !this.isRootSeen; this.isRootSeen = true; var body = program.body; for (var i = 0, l = body.length; i < l; i++) { var current = body[i], strip = this.accept(current); if (!strip) { continue; } var _isPrevWhitespace = isPrevWhitespace(body, i, isRoot), _isNextWhitespace = isNextWhitespace(body, i, isRoot), openStandalone = strip.openStandalone && _isPrevWhitespace, closeStandalone = strip.closeStandalone && _isNextWhitespace, inlineStandalone = strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace; if (strip.close) { omitRight(body, i, true); } if (strip.open) { omitLeft(body, i, true); } if (doStandalone && inlineStandalone) { omitRight(body, i); if (omitLeft(body, i)) { // If we are on a standalone node, save the indent info for partials if (current.type === 'PartialStatement') { // Pull out the whitespace from the final line current.indent = /([ \t]+$)/.exec(body[i - 1].original)[1]; } } } if (doStandalone && openStandalone) { omitRight((current.program || current.inverse).body); // Strip out the previous content node if it's whitespace only omitLeft(body, i); } if (doStandalone && closeStandalone) { // Always strip the next node omitRight(body, i); omitLeft((current.inverse || current.program).body); } } return program; }; WhitespaceControl.prototype.BlockStatement = WhitespaceControl.prototype.DecoratorBlock = WhitespaceControl.prototype.PartialBlockStatement = function (block) { this.accept(block.program); this.accept(block.inverse); // Find the inverse program that is involed with whitespace stripping. var program = block.program || block.inverse, inverse = block.program && block.inverse, firstInverse = inverse, lastInverse = inverse; if (inverse && inverse.chained) { firstInverse = inverse.body[0].program; // Walk the inverse chain to find the last inverse that is actually in the chain. while (lastInverse.chained) { lastInverse = lastInverse.body[lastInverse.body.length - 1].program; } } var strip = { open: block.openStrip.open, close: block.closeStrip.close, // Determine the standalone candiacy. Basically flag our content as being possibly standalone // so our parent can determine if we actually are standalone openStandalone: isNextWhitespace(program.body), closeStandalone: isPrevWhitespace((firstInverse || program).body) }; if (block.openStrip.close) { omitRight(program.body, null, true); } if (inverse) { var inverseStrip = block.inverseStrip; if (inverseStrip.open) { omitLeft(program.body, null, true); } if (inverseStrip.close) { omitRight(firstInverse.body, null, true); } if (block.closeStrip.open) { omitLeft(lastInverse.body, null, true); } // Find standalone else statments if (!this.options.ignoreStandalone && isPrevWhitespace(program.body) && isNextWhitespace(firstInverse.body)) { omitLeft(program.body); omitRight(firstInverse.body); } } else if (block.closeStrip.open) { omitLeft(program.body, null, true); } return strip; }; WhitespaceControl.prototype.Decorator = WhitespaceControl.prototype.MustacheStatement = function (mustache) { return mustache.strip; }; WhitespaceControl.prototype.PartialStatement = WhitespaceControl.prototype.CommentStatement = function (node) { /* istanbul ignore next */ var strip = node.strip || {}; return { inlineStandalone: true, open: strip.open, close: strip.close }; }; function isPrevWhitespace(body, i, isRoot) { if (i === undefined) { i = body.length; } // Nodes that end with newlines are considered whitespace (but are special // cased for strip operations) var prev = body[i - 1], sibling = body[i - 2]; if (!prev) { return isRoot; } if (prev.type === 'ContentStatement') { return (sibling || !isRoot ? /\r?\n\s*?$/ : /(^|\r?\n)\s*?$/).test(prev.original); } } function isNextWhitespace(body, i, isRoot) { if (i === undefined) { i = -1; } var next = body[i + 1], sibling = body[i + 2]; if (!next) { return isRoot; } if (next.type === 'ContentStatement') { return (sibling || !isRoot ? /^\s*?\r?\n/ : /^\s*?(\r?\n|$)/).test(next.original); } } // Marks the node to the right of the position as omitted. // I.e. {{foo}}' ' will mark the ' ' node as omitted. // // If i is undefined, then the first child will be marked as such. // // If mulitple is truthy then all whitespace will be stripped out until non-whitespace // content is met. function omitRight(body, i, multiple) { var current = body[i == null ? 0 : i + 1]; if (!current || current.type !== 'ContentStatement' || !multiple && current.rightStripped) { return; } var original = current.value; current.value = current.value.replace(multiple ? /^\s+/ : /^[ \t]*\r?\n?/, ''); current.rightStripped = current.value !== original; } // Marks the node to the left of the position as omitted. // I.e. ' '{{foo}} will mark the ' ' node as omitted. // // If i is undefined then the last child will be marked as such. // // If mulitple is truthy then all whitespace will be stripped out until non-whitespace // content is met. function omitLeft(body, i, multiple) { var current = body[i == null ? body.length - 1 : i - 1]; if (!current || current.type !== 'ContentStatement' || !multiple && current.leftStripped) { return; } // We omit the last node if it's whitespace only and not preceeded by a non-content node. var original = current.value; current.value = current.value.replace(multiple ? /\s+$/ : /[ \t]+$/, ''); current.leftStripped = current.value !== original; return current.leftStripped; } exports['default'] = WhitespaceControl; module.exports = exports['default']; /***/ }), /* 39 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _exception = __webpack_require__(6); var _exception2 = _interopRequireDefault(_exception); function Visitor() { this.parents = []; } Visitor.prototype = { constructor: Visitor, mutating: false, // Visits a given value. If mutating, will replace the value if necessary. acceptKey: function acceptKey(node, name) { var value = this.accept(node[name]); if (this.mutating) { // Hacky sanity check: This may have a few false positives for type for the helper // methods but will generally do the right thing without a lot of overhead. if (value && !Visitor.prototype[value.type]) { throw new _exception2['default']('Unexpected node type "' + value.type + '" found when accepting ' + name + ' on ' + node.type); } node[name] = value; } }, // Performs an accept operation with added sanity check to ensure // required keys are not removed. acceptRequired: function acceptRequired(node, name) { this.acceptKey(node, name); if (!node[name]) { throw new _exception2['default'](node.type + ' requires ' + name); } }, // Traverses a given array. If mutating, empty respnses will be removed // for child elements. acceptArray: function acceptArray(array) { for (var i = 0, l = array.length; i < l; i++) { this.acceptKey(array, i); if (!array[i]) { array.splice(i, 1); i--; l--; } } }, accept: function accept(object) { if (!object) { return; } /* istanbul ignore next: Sanity code */ if (!this[object.type]) { throw new _exception2['default']('Unknown type: ' + object.type, object); } if (this.current) { this.parents.unshift(this.current); } this.current = object; var ret = this[object.type](object); this.current = this.parents.shift(); if (!this.mutating || ret) { return ret; } else if (ret !== false) { return object; } }, Program: function Program(program) { this.acceptArray(program.body); }, MustacheStatement: visitSubExpression, Decorator: visitSubExpression, BlockStatement: visitBlock, DecoratorBlock: visitBlock, PartialStatement: visitPartial, PartialBlockStatement: function PartialBlockStatement(partial) { visitPartial.call(this, partial); this.acceptKey(partial, 'program'); }, ContentStatement: function ContentStatement() /* content */{}, CommentStatement: function CommentStatement() /* comment */{}, SubExpression: visitSubExpression, PathExpression: function PathExpression() /* path */{}, StringLiteral: function StringLiteral() /* string */{}, NumberLiteral: function NumberLiteral() /* number */{}, BooleanLiteral: function BooleanLiteral() /* bool */{}, UndefinedLiteral: function UndefinedLiteral() /* literal */{}, NullLiteral: function NullLiteral() /* literal */{}, Hash: function Hash(hash) { this.acceptArray(hash.pairs); }, HashPair: function HashPair(pair) { this.acceptRequired(pair, 'value'); } }; function visitSubExpression(mustache) { this.acceptRequired(mustache, 'path'); this.acceptArray(mustache.params); this.acceptKey(mustache, 'hash'); } function visitBlock(block) { visitSubExpression.call(this, block); this.acceptKey(block, 'program'); this.acceptKey(block, 'inverse'); } function visitPartial(partial) { this.acceptRequired(partial, 'name'); this.acceptArray(partial.params); this.acceptKey(partial, 'hash'); } exports['default'] = Visitor; module.exports = exports['default']; /***/ }), /* 40 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; exports.SourceLocation = SourceLocation; exports.id = id; exports.stripFlags = stripFlags; exports.stripComment = stripComment; exports.preparePath = preparePath; exports.prepareMustache = prepareMustache; exports.prepareRawBlock = prepareRawBlock; exports.prepareBlock = prepareBlock; exports.prepareProgram = prepareProgram; exports.preparePartialBlock = preparePartialBlock; var _exception = __webpack_require__(6); var _exception2 = _interopRequireDefault(_exception); function validateClose(open, close) { close = close.path ? close.path.original : close; if (open.path.original !== close) { var errorNode = { loc: open.path.loc }; throw new _exception2['default'](open.path.original + " doesn't match " + close, errorNode); } } function SourceLocation(source, locInfo) { this.source = source; this.start = { line: locInfo.first_line, column: locInfo.first_column }; this.end = { line: locInfo.last_line, column: locInfo.last_column }; } function id(token) { if (/^\[.*\]$/.test(token)) { return token.substr(1, token.length - 2); } else { return token; } } function stripFlags(open, close) { return { open: open.charAt(2) === '~', close: close.charAt(close.length - 3) === '~' }; } function stripComment(comment) { return comment.replace(/^\{\{~?\!-?-?/, '').replace(/-?-?~?\}\}$/, ''); } function preparePath(data, parts, loc) { loc = this.locInfo(loc); var original = data ? '@' : '', dig = [], depth = 0, depthString = ''; for (var i = 0, l = parts.length; i < l; i++) { var part = parts[i].part, // If we have [] syntax then we do not treat path references as operators, // i.e. foo.[this] resolves to approximately context.foo['this'] isLiteral = parts[i].original !== part; original += (parts[i].separator || '') + part; if (!isLiteral && (part === '..' || part === '.' || part === 'this')) { if (dig.length > 0) { throw new _exception2['default']('Invalid path: ' + original, { loc: loc }); } else if (part === '..') { depth++; depthString += '../'; } } else { dig.push(part); } } return { type: 'PathExpression', data: data, depth: depth, parts: dig, original: original, loc: loc }; } function prepareMustache(path, params, hash, open, strip, locInfo) { // Must use charAt to support IE pre-10 var escapeFlag = open.charAt(3) || open.charAt(2), escaped = escapeFlag !== '{' && escapeFlag !== '&'; var decorator = /\*/.test(open); return { type: decorator ? 'Decorator' : 'MustacheStatement', path: path, params: params, hash: hash, escaped: escaped, strip: strip, loc: this.locInfo(locInfo) }; } function prepareRawBlock(openRawBlock, contents, close, locInfo) { validateClose(openRawBlock, close); locInfo = this.locInfo(locInfo); var program = { type: 'Program', body: contents, strip: {}, loc: locInfo }; return { type: 'BlockStatement', path: openRawBlock.path, params: openRawBlock.params, hash: openRawBlock.hash, program: program, openStrip: {}, inverseStrip: {}, closeStrip: {}, loc: locInfo }; } function prepareBlock(openBlock, program, inverseAndProgram, close, inverted, locInfo) { if (close && close.path) { validateClose(openBlock, close); } var decorator = /\*/.test(openBlock.open); program.blockParams = openBlock.blockParams; var inverse = undefined, inverseStrip = undefined; if (inverseAndProgram) { if (decorator) { throw new _exception2['default']('Unexpected inverse block on decorator', inverseAndProgram); } if (inverseAndProgram.chain) { inverseAndProgram.program.body[0].closeStrip = close.strip; } inverseStrip = inverseAndProgram.strip; inverse = inverseAndProgram.program; } if (inverted) { inverted = inverse; inverse = program; program = inverted; } return { type: decorator ? 'DecoratorBlock' : 'BlockStatement', path: openBlock.path, params: openBlock.params, hash: openBlock.hash, program: program, inverse: inverse, openStrip: openBlock.strip, inverseStrip: inverseStrip, closeStrip: close && close.strip, loc: this.locInfo(locInfo) }; } function prepareProgram(statements, loc) { if (!loc && statements.length) { var firstLoc = statements[0].loc, lastLoc = statements[statements.length - 1].loc; /* istanbul ignore else */ if (firstLoc && lastLoc) { loc = { source: firstLoc.source, start: { line: firstLoc.start.line, column: firstLoc.start.column }, end: { line: lastLoc.end.line, column: lastLoc.end.column } }; } } return { type: 'Program', body: statements, strip: {}, loc: loc }; } function preparePartialBlock(open, program, close, locInfo) { validateClose(open, close); return { type: 'PartialBlockStatement', name: open.path, params: open.params, hash: open.hash, program: program, openStrip: open.strip, closeStrip: close && close.strip, loc: this.locInfo(locInfo) }; } /***/ }), /* 41 */ /***/ (function(module, exports, __webpack_require__) { /* eslint-disable new-cap */ 'use strict'; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; exports.Compiler = Compiler; exports.precompile = precompile; exports.compile = compile; var _exception = __webpack_require__(6); var _exception2 = _interopRequireDefault(_exception); var _utils = __webpack_require__(5); var _ast = __webpack_require__(35); var _ast2 = _interopRequireDefault(_ast); var slice = [].slice; function Compiler() {} // the foundHelper register will disambiguate helper lookup from finding a // function in a context. This is necessary for mustache compatibility, which // requires that context functions in blocks are evaluated by blockHelperMissing, // and then proceed as if the resulting value was provided to blockHelperMissing. Compiler.prototype = { compiler: Compiler, equals: function equals(other) { var len = this.opcodes.length; if (other.opcodes.length !== len) { return false; } for (var i = 0; i < len; i++) { var opcode = this.opcodes[i], otherOpcode = other.opcodes[i]; if (opcode.opcode !== otherOpcode.opcode || !argEquals(opcode.args, otherOpcode.args)) { return false; } } // We know that length is the same between the two arrays because they are directly tied // to the opcode behavior above. len = this.children.length; for (var i = 0; i < len; i++) { if (!this.children[i].equals(other.children[i])) { return false; } } return true; }, guid: 0, compile: function compile(program, options) { this.sourceNode = []; this.opcodes = []; this.children = []; this.options = options; this.stringParams = options.stringParams; this.trackIds = options.trackIds; options.blockParams = options.blockParams || []; // These changes will propagate to the other compiler components var knownHelpers = options.knownHelpers; options.knownHelpers = { 'helperMissing': true, 'blockHelperMissing': true, 'each': true, 'if': true, 'unless': true, 'with': true, 'log': true, 'lookup': true }; if (knownHelpers) { for (var _name in knownHelpers) { /* istanbul ignore else */ if (_name in knownHelpers) { this.options.knownHelpers[_name] = knownHelpers[_name]; } } } return this.accept(program); }, compileProgram: function compileProgram(program) { var childCompiler = new this.compiler(), // eslint-disable-line new-cap result = childCompiler.compile(program, this.options), guid = this.guid++; this.usePartial = this.usePartial || result.usePartial; this.children[guid] = result; this.useDepths = this.useDepths || result.useDepths; return guid; }, accept: function accept(node) { /* istanbul ignore next: Sanity code */ if (!this[node.type]) { throw new _exception2['default']('Unknown type: ' + node.type, node); } this.sourceNode.unshift(node); var ret = this[node.type](node); this.sourceNode.shift(); return ret; }, Program: function Program(program) { this.options.blockParams.unshift(program.blockParams); var body = program.body, bodyLength = body.length; for (var i = 0; i < bodyLength; i++) { this.accept(body[i]); } this.options.blockParams.shift(); this.isSimple = bodyLength === 1; this.blockParams = program.blockParams ? program.blockParams.length : 0; return this; }, BlockStatement: function BlockStatement(block) { transformLiteralToPath(block); var program = block.program, inverse = block.inverse; program = program && this.compileProgram(program); inverse = inverse && this.compileProgram(inverse); var type = this.classifySexpr(block); if (type === 'helper') { this.helperSexpr(block, program, inverse); } else if (type === 'simple') { this.simpleSexpr(block); // now that the simple mustache is resolved, we need to // evaluate it by executing `blockHelperMissing` this.opcode('pushProgram', program); this.opcode('pushProgram', inverse); this.opcode('emptyHash'); this.opcode('blockValue', block.path.original); } else { this.ambiguousSexpr(block, program, inverse); // now that the simple mustache is resolved, we need to // evaluate it by executing `blockHelperMissing` this.opcode('pushProgram', program); this.opcode('pushProgram', inverse); this.opcode('emptyHash'); this.opcode('ambiguousBlockValue'); } this.opcode('append'); }, DecoratorBlock: function DecoratorBlock(decorator) { var program = decorator.program && this.compileProgram(decorator.program); var params = this.setupFullMustacheParams(decorator, program, undefined), path = decorator.path; this.useDecorators = true; this.opcode('registerDecorator', params.length, path.original); }, PartialStatement: function PartialStatement(partial) { this.usePartial = true; var program = partial.program; if (program) { program = this.compileProgram(partial.program); } var params = partial.params; if (params.length > 1) { throw new _exception2['default']('Unsupported number of partial arguments: ' + params.length, partial); } else if (!params.length) { if (this.options.explicitPartialContext) { this.opcode('pushLiteral', 'undefined'); } else { params.push({ type: 'PathExpression', parts: [], depth: 0 }); } } var partialName = partial.name.original, isDynamic = partial.name.type === 'SubExpression'; if (isDynamic) { this.accept(partial.name); } this.setupFullMustacheParams(partial, program, undefined, true); var indent = partial.indent || ''; if (this.options.preventIndent && indent) { this.opcode('appendContent', indent); indent = ''; } this.opcode('invokePartial', isDynamic, partialName, indent); this.opcode('append'); }, PartialBlockStatement: function PartialBlockStatement(partialBlock) { this.PartialStatement(partialBlock); }, MustacheStatement: function MustacheStatement(mustache) { this.SubExpression(mustache); if (mustache.escaped && !this.options.noEscape) { this.opcode('appendEscaped'); } else { this.opcode('append'); } }, Decorator: function Decorator(decorator) { this.DecoratorBlock(decorator); }, ContentStatement: function ContentStatement(content) { if (content.value) { this.opcode('appendContent', content.value); } }, CommentStatement: function CommentStatement() {}, SubExpression: function SubExpression(sexpr) { transformLiteralToPath(sexpr); var type = this.classifySexpr(sexpr); if (type === 'simple') { this.simpleSexpr(sexpr); } else if (type === 'helper') { this.helperSexpr(sexpr); } else { this.ambiguousSexpr(sexpr); } }, ambiguousSexpr: function ambiguousSexpr(sexpr, program, inverse) { var path = sexpr.path, name = path.parts[0], isBlock = program != null || inverse != null; this.opcode('getContext', path.depth); this.opcode('pushProgram', program); this.opcode('pushProgram', inverse); path.strict = true; this.accept(path); this.opcode('invokeAmbiguous', name, isBlock); }, simpleSexpr: function simpleSexpr(sexpr) { var path = sexpr.path; path.strict = true; this.accept(path); this.opcode('resolvePossibleLambda'); }, helperSexpr: function helperSexpr(sexpr, program, inverse) { var params = this.setupFullMustacheParams(sexpr, program, inverse), path = sexpr.path, name = path.parts[0]; if (this.options.knownHelpers[name]) { this.opcode('invokeKnownHelper', params.length, name); } else if (this.options.knownHelpersOnly) { throw new _exception2['default']('You specified knownHelpersOnly, but used the unknown helper ' + name, sexpr); } else { path.strict = true; path.falsy = true; this.accept(path); this.opcode('invokeHelper', params.length, path.original, _ast2['default'].helpers.simpleId(path)); } }, PathExpression: function PathExpression(path) { this.addDepth(path.depth); this.opcode('getContext', path.depth); var name = path.parts[0], scoped = _ast2['default'].helpers.scopedId(path), blockParamId = !path.depth && !scoped && this.blockParamIndex(name); if (blockParamId) { this.opcode('lookupBlockParam', blockParamId, path.parts); } else if (!name) { // Context reference, i.e. `{{foo .}}` or `{{foo ..}}` this.opcode('pushContext'); } else if (path.data) { this.options.data = true; this.opcode('lookupData', path.depth, path.parts, path.strict); } else { this.opcode('lookupOnContext', path.parts, path.falsy, path.strict, scoped); } }, StringLiteral: function StringLiteral(string) { this.opcode('pushString', string.value); }, NumberLiteral: function NumberLiteral(number) { this.opcode('pushLiteral', number.value); }, BooleanLiteral: function BooleanLiteral(bool) { this.opcode('pushLiteral', bool.value); }, UndefinedLiteral: function UndefinedLiteral() { this.opcode('pushLiteral', 'undefined'); }, NullLiteral: function NullLiteral() { this.opcode('pushLiteral', 'null'); }, Hash: function Hash(hash) { var pairs = hash.pairs, i = 0, l = pairs.length; this.opcode('pushHash'); for (; i < l; i++) { this.pushParam(pairs[i].value); } while (i--) { this.opcode('assignToHash', pairs[i].key); } this.opcode('popHash'); }, // HELPERS opcode: function opcode(name) { this.opcodes.push({ opcode: name, args: slice.call(arguments, 1), loc: this.sourceNode[0].loc }); }, addDepth: function addDepth(depth) { if (!depth) { return; } this.useDepths = true; }, classifySexpr: function classifySexpr(sexpr) { var isSimple = _ast2['default'].helpers.simpleId(sexpr.path); var isBlockParam = isSimple && !!this.blockParamIndex(sexpr.path.parts[0]); // a mustache is an eligible helper if: // * its id is simple (a single part, not `this` or `..`) var isHelper = !isBlockParam && _ast2['default'].helpers.helperExpression(sexpr); // if a mustache is an eligible helper but not a definite // helper, it is ambiguous, and will be resolved in a later // pass or at runtime. var isEligible = !isBlockParam && (isHelper || isSimple); // if ambiguous, we can possibly resolve the ambiguity now // An eligible helper is one that does not have a complex path, i.e. `this.foo`, `../foo` etc. if (isEligible && !isHelper) { var _name2 = sexpr.path.parts[0], options = this.options; if (options.knownHelpers[_name2]) { isHelper = true; } else if (options.knownHelpersOnly) { isEligible = false; } } if (isHelper) { return 'helper'; } else if (isEligible) { return 'ambiguous'; } else { return 'simple'; } }, pushParams: function pushParams(params) { for (var i = 0, l = params.length; i < l; i++) { this.pushParam(params[i]); } }, pushParam: function pushParam(val) { var value = val.value != null ? val.value : val.original || ''; if (this.stringParams) { if (value.replace) { value = value.replace(/^(\.?\.\/)*/g, '').replace(/\//g, '.'); } if (val.depth) { this.addDepth(val.depth); } this.opcode('getContext', val.depth || 0); this.opcode('pushStringParam', value, val.type); if (val.type === 'SubExpression') { // SubExpressions get evaluated and passed in // in string params mode. this.accept(val); } } else { if (this.trackIds) { var blockParamIndex = undefined; if (val.parts && !_ast2['default'].helpers.scopedId(val) && !val.depth) { blockParamIndex = this.blockParamIndex(val.parts[0]); } if (blockParamIndex) { var blockParamChild = val.parts.slice(1).join('.'); this.opcode('pushId', 'BlockParam', blockParamIndex, blockParamChild); } else { value = val.original || value; if (value.replace) { value = value.replace(/^this(?:\.|$)/, '').replace(/^\.\//, '').replace(/^\.$/, ''); } this.opcode('pushId', val.type, value); } } this.accept(val); } }, setupFullMustacheParams: function setupFullMustacheParams(sexpr, program, inverse, omitEmpty) { var params = sexpr.params; this.pushParams(params); this.opcode('pushProgram', program); this.opcode('pushProgram', inverse); if (sexpr.hash) { this.accept(sexpr.hash); } else { this.opcode('emptyHash', omitEmpty); } return params; }, blockParamIndex: function blockParamIndex(name) { for (var depth = 0, len = this.options.blockParams.length; depth < len; depth++) { var blockParams = this.options.blockParams[depth], param = blockParams && _utils.indexOf(blockParams, name); if (blockParams && param >= 0) { return [depth, param]; } } } }; function precompile(input, options, env) { if (input == null || typeof input !== 'string' && input.type !== 'Program') { throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.precompile. You passed ' + input); } options = options || {}; if (!('data' in options)) { options.data = true; } if (options.compat) { options.useDepths = true; } var ast = env.parse(input, options), environment = new env.Compiler().compile(ast, options); return new env.JavaScriptCompiler().compile(environment, options); } function compile(input, options, env) { if (options === undefined) options = {}; if (input == null || typeof input !== 'string' && input.type !== 'Program') { throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.compile. You passed ' + input); } options = _utils.extend({}, options); if (!('data' in options)) { options.data = true; } if (options.compat) { options.useDepths = true; } var compiled = undefined; function compileInput() { var ast = env.parse(input, options), environment = new env.Compiler().compile(ast, options), templateSpec = new env.JavaScriptCompiler().compile(environment, options, undefined, true); return env.template(templateSpec); } // Template is only compiled on first use and cached after that point. function ret(context, execOptions) { if (!compiled) { compiled = compileInput(); } return compiled.call(this, context, execOptions); } ret._setup = function (setupOptions) { if (!compiled) { compiled = compileInput(); } return compiled._setup(setupOptions); }; ret._child = function (i, data, blockParams, depths) { if (!compiled) { compiled = compileInput(); } return compiled._child(i, data, blockParams, depths); }; return ret; } function argEquals(a, b) { if (a === b) { return true; } if (_utils.isArray(a) && _utils.isArray(b) && a.length === b.length) { for (var i = 0; i < a.length; i++) { if (!argEquals(a[i], b[i])) { return false; } } return true; } } function transformLiteralToPath(sexpr) { if (!sexpr.path.parts) { var literal = sexpr.path; // Casting to string here to make false and 0 literal values play nicely with the rest // of the system. sexpr.path = { type: 'PathExpression', data: false, depth: 0, parts: [literal.original + ''], original: literal.original + '', loc: literal.loc }; } } /***/ }), /* 42 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _base = __webpack_require__(4); var _exception = __webpack_require__(6); var _exception2 = _interopRequireDefault(_exception); var _utils = __webpack_require__(5); var _codeGen = __webpack_require__(43); var _codeGen2 = _interopRequireDefault(_codeGen); function Literal(value) { this.value = value; } function JavaScriptCompiler() {} JavaScriptCompiler.prototype = { // PUBLIC API: You can override these methods in a subclass to provide // alternative compiled forms for name lookup and buffering semantics nameLookup: function nameLookup(parent, name /* , type*/) { if (JavaScriptCompiler.isValidJavaScriptVariableName(name)) { return [parent, '.', name]; } else { return [parent, '[', JSON.stringify(name), ']']; } }, depthedLookup: function depthedLookup(name) { return [this.aliasable('container.lookup'), '(depths, "', name, '")']; }, compilerInfo: function compilerInfo() { var revision = _base.COMPILER_REVISION, versions = _base.REVISION_CHANGES[revision]; return [revision, versions]; }, appendToBuffer: function appendToBuffer(source, location, explicit) { // Force a source as this simplifies the merge logic. if (!_utils.isArray(source)) { source = [source]; } source = this.source.wrap(source, location); if (this.environment.isSimple) { return ['return ', source, ';']; } else if (explicit) { // This is a case where the buffer operation occurs as a child of another // construct, generally braces. We have to explicitly output these buffer // operations to ensure that the emitted code goes in the correct location. return ['buffer += ', source, ';']; } else { source.appendToBuffer = true; return source; } }, initializeBuffer: function initializeBuffer() { return this.quotedString(''); }, // END PUBLIC API compile: function compile(environment, options, context, asObject) { this.environment = environment; this.options = options; this.stringParams = this.options.stringParams; this.trackIds = this.options.trackIds; this.precompile = !asObject; this.name = this.environment.name; this.isChild = !!context; this.context = context || { decorators: [], programs: [], environments: [] }; this.preamble(); this.stackSlot = 0; this.stackVars = []; this.aliases = {}; this.registers = { list: [] }; this.hashes = []; this.compileStack = []; this.inlineStack = []; this.blockParams = []; this.compileChildren(environment, options); this.useDepths = this.useDepths || environment.useDepths || environment.useDecorators || this.options.compat; this.useBlockParams = this.useBlockParams || environment.useBlockParams; var opcodes = environment.opcodes, opcode = undefined, firstLoc = undefined, i = undefined, l = undefined; for (i = 0, l = opcodes.length; i < l; i++) { opcode = opcodes[i]; this.source.currentLocation = opcode.loc; firstLoc = firstLoc || opcode.loc; this[opcode.opcode].apply(this, opcode.args); } // Flush any trailing content that might be pending. this.source.currentLocation = firstLoc; this.pushSource(''); /* istanbul ignore next */ if (this.stackSlot || this.inlineStack.length || this.compileStack.length) { throw new _exception2['default']('Compile completed with content left on stack'); } if (!this.decorators.isEmpty()) { this.useDecorators = true; this.decorators.prepend('var decorators = container.decorators;\n'); this.decorators.push('return fn;'); if (asObject) { this.decorators = Function.apply(this, ['fn', 'props', 'container', 'depth0', 'data', 'blockParams', 'depths', this.decorators.merge()]); } else { this.decorators.prepend('function(fn, props, container, depth0, data, blockParams, depths) {\n'); this.decorators.push('}\n'); this.decorators = this.decorators.merge(); } } else { this.decorators = undefined; } var fn = this.createFunctionContext(asObject); if (!this.isChild) { var ret = { compiler: this.compilerInfo(), main: fn }; if (this.decorators) { ret.main_d = this.decorators; // eslint-disable-line camelcase ret.useDecorators = true; } var _context = this.context; var programs = _context.programs; var decorators = _context.decorators; for (i = 0, l = programs.length; i < l; i++) { if (programs[i]) { ret[i] = programs[i]; if (decorators[i]) { ret[i + '_d'] = decorators[i]; ret.useDecorators = true; } } } if (this.environment.usePartial) { ret.usePartial = true; } if (this.options.data) { ret.useData = true; } if (this.useDepths) { ret.useDepths = true; } if (this.useBlockParams) { ret.useBlockParams = true; } if (this.options.compat) { ret.compat = true; } if (!asObject) { ret.compiler = JSON.stringify(ret.compiler); this.source.currentLocation = { start: { line: 1, column: 0 } }; ret = this.objectLiteral(ret); if (options.srcName) { ret = ret.toStringWithSourceMap({ file: options.destName }); ret.map = ret.map && ret.map.toString(); } else { ret = ret.toString(); } } else { ret.compilerOptions = this.options; } return ret; } else { return fn; } }, preamble: function preamble() { // track the last context pushed into place to allow skipping the // getContext opcode when it would be a noop this.lastContext = 0; this.source = new _codeGen2['default'](this.options.srcName); this.decorators = new _codeGen2['default'](this.options.srcName); }, createFunctionContext: function createFunctionContext(asObject) { var varDeclarations = ''; var locals = this.stackVars.concat(this.registers.list); if (locals.length > 0) { varDeclarations += ', ' + locals.join(', '); } // Generate minimizer alias mappings // // When using true SourceNodes, this will update all references to the given alias // as the source nodes are reused in situ. For the non-source node compilation mode, // aliases will not be used, but this case is already being run on the client and // we aren't concern about minimizing the template size. var aliasCount = 0; for (var alias in this.aliases) { // eslint-disable-line guard-for-in var node = this.aliases[alias]; if (this.aliases.hasOwnProperty(alias) && node.children && node.referenceCount > 1) { varDeclarations += ', alias' + ++aliasCount + '=' + alias; node.children[0] = 'alias' + aliasCount; } } var params = ['container', 'depth0', 'helpers', 'partials', 'data']; if (this.useBlockParams || this.useDepths) { params.push('blockParams'); } if (this.useDepths) { params.push('depths'); } // Perform a second pass over the output to merge content when possible var source = this.mergeSource(varDeclarations); if (asObject) { params.push(source); return Function.apply(this, params); } else { return this.source.wrap(['function(', params.join(','), ') {\n ', source, '}']); } }, mergeSource: function mergeSource(varDeclarations) { var isSimple = this.environment.isSimple, appendOnly = !this.forceBuffer, appendFirst = undefined, sourceSeen = undefined, bufferStart = undefined, bufferEnd = undefined; this.source.each(function (line) { if (line.appendToBuffer) { if (bufferStart) { line.prepend(' + '); } else { bufferStart = line; } bufferEnd = line; } else { if (bufferStart) { if (!sourceSeen) { appendFirst = true; } else { bufferStart.prepend('buffer += '); } bufferEnd.add(';'); bufferStart = bufferEnd = undefined; } sourceSeen = true; if (!isSimple) { appendOnly = false; } } }); if (appendOnly) { if (bufferStart) { bufferStart.prepend('return '); bufferEnd.add(';'); } else if (!sourceSeen) { this.source.push('return "";'); } } else { varDeclarations += ', buffer = ' + (appendFirst ? '' : this.initializeBuffer()); if (bufferStart) { bufferStart.prepend('return buffer + '); bufferEnd.add(';'); } else { this.source.push('return buffer;'); } } if (varDeclarations) { this.source.prepend('var ' + varDeclarations.substring(2) + (appendFirst ? '' : ';\n')); } return this.source.merge(); }, // [blockValue] // // On stack, before: hash, inverse, program, value // On stack, after: return value of blockHelperMissing // // The purpose of this opcode is to take a block of the form // `{{#this.foo}}...{{/this.foo}}`, resolve the value of `foo`, and // replace it on the stack with the result of properly // invoking blockHelperMissing. blockValue: function blockValue(name) { var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'), params = [this.contextName(0)]; this.setupHelperArgs(name, 0, params); var blockName = this.popStack(); params.splice(1, 0, blockName); this.push(this.source.functionCall(blockHelperMissing, 'call', params)); }, // [ambiguousBlockValue] // // On stack, before: hash, inverse, program, value // Compiler value, before: lastHelper=value of last found helper, if any // On stack, after, if no lastHelper: same as [blockValue] // On stack, after, if lastHelper: value ambiguousBlockValue: function ambiguousBlockValue() { // We're being a bit cheeky and reusing the options value from the prior exec var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'), params = [this.contextName(0)]; this.setupHelperArgs('', 0, params, true); this.flushInline(); var current = this.topStack(); params.splice(1, 0, current); this.pushSource(['if (!', this.lastHelper, ') { ', current, ' = ', this.source.functionCall(blockHelperMissing, 'call', params), '}']); }, // [appendContent] // // On stack, before: ... // On stack, after: ... // // Appends the string value of `content` to the current buffer appendContent: function appendContent(content) { if (this.pendingContent) { content = this.pendingContent + content; } else { this.pendingLocation = this.source.currentLocation; } this.pendingContent = content; }, // [append] // // On stack, before: value, ... // On stack, after: ... // // Coerces `value` to a String and appends it to the current buffer. // // If `value` is truthy, or 0, it is coerced into a string and appended // Otherwise, the empty string is appended append: function append() { if (this.isInline()) { this.replaceStack(function (current) { return [' != null ? ', current, ' : ""']; }); this.pushSource(this.appendToBuffer(this.popStack())); } else { var local = this.popStack(); this.pushSource(['if (', local, ' != null) { ', this.appendToBuffer(local, undefined, true), ' }']); if (this.environment.isSimple) { this.pushSource(['else { ', this.appendToBuffer("''", undefined, true), ' }']); } } }, // [appendEscaped] // // On stack, before: value, ... // On stack, after: ... // // Escape `value` and append it to the buffer appendEscaped: function appendEscaped() { this.pushSource(this.appendToBuffer([this.aliasable('container.escapeExpression'), '(', this.popStack(), ')'])); }, // [getContext] // // On stack, before: ... // On stack, after: ... // Compiler value, after: lastContext=depth // // Set the value of the `lastContext` compiler value to the depth getContext: function getContext(depth) { this.lastContext = depth; }, // [pushContext] // // On stack, before: ... // On stack, after: currentContext, ... // // Pushes the value of the current context onto the stack. pushContext: function pushContext() { this.pushStackLiteral(this.contextName(this.lastContext)); }, // [lookupOnContext] // // On stack, before: ... // On stack, after: currentContext[name], ... // // Looks up the value of `name` on the current context and pushes // it onto the stack. lookupOnContext: function lookupOnContext(parts, falsy, strict, scoped) { var i = 0; if (!scoped && this.options.compat && !this.lastContext) { // The depthed query is expected to handle the undefined logic for the root level that // is implemented below, so we evaluate that directly in compat mode this.push(this.depthedLookup(parts[i++])); } else { this.pushContext(); } this.resolvePath('context', parts, i, falsy, strict); }, // [lookupBlockParam] // // On stack, before: ... // On stack, after: blockParam[name], ... // // Looks up the value of `parts` on the given block param and pushes // it onto the stack. lookupBlockParam: function lookupBlockParam(blockParamId, parts) { this.useBlockParams = true; this.push(['blockParams[', blockParamId[0], '][', blockParamId[1], ']']); this.resolvePath('context', parts, 1); }, // [lookupData] // // On stack, before: ... // On stack, after: data, ... // // Push the data lookup operator lookupData: function lookupData(depth, parts, strict) { if (!depth) { this.pushStackLiteral('data'); } else { this.pushStackLiteral('container.data(data, ' + depth + ')'); } this.resolvePath('data', parts, 0, true, strict); }, resolvePath: function resolvePath(type, parts, i, falsy, strict) { // istanbul ignore next var _this = this; if (this.options.strict || this.options.assumeObjects) { this.push(strictLookup(this.options.strict && strict, this, parts, type)); return; } var len = parts.length; for (; i < len; i++) { /* eslint-disable no-loop-func */ this.replaceStack(function (current) { var lookup = _this.nameLookup(current, parts[i], type); // We want to ensure that zero and false are handled properly if the context (falsy flag) // needs to have the special handling for these values. if (!falsy) { return [' != null ? ', lookup, ' : ', current]; } else { // Otherwise we can use generic falsy handling return [' && ', lookup]; } }); /* eslint-enable no-loop-func */ } }, // [resolvePossibleLambda] // // On stack, before: value, ... // On stack, after: resolved value, ... // // If the `value` is a lambda, replace it on the stack by // the return value of the lambda resolvePossibleLambda: function resolvePossibleLambda() { this.push([this.aliasable('container.lambda'), '(', this.popStack(), ', ', this.contextName(0), ')']); }, // [pushStringParam] // // On stack, before: ... // On stack, after: string, currentContext, ... // // This opcode is designed for use in string mode, which // provides the string value of a parameter along with its // depth rather than resolving it immediately. pushStringParam: function pushStringParam(string, type) { this.pushContext(); this.pushString(type); // If it's a subexpression, the string result // will be pushed after this opcode. if (type !== 'SubExpression') { if (typeof string === 'string') { this.pushString(string); } else { this.pushStackLiteral(string); } } }, emptyHash: function emptyHash(omitEmpty) { if (this.trackIds) { this.push('{}'); // hashIds } if (this.stringParams) { this.push('{}'); // hashContexts this.push('{}'); // hashTypes } this.pushStackLiteral(omitEmpty ? 'undefined' : '{}'); }, pushHash: function pushHash() { if (this.hash) { this.hashes.push(this.hash); } this.hash = { values: [], types: [], contexts: [], ids: [] }; }, popHash: function popHash() { var hash = this.hash; this.hash = this.hashes.pop(); if (this.trackIds) { this.push(this.objectLiteral(hash.ids)); } if (this.stringParams) { this.push(this.objectLiteral(hash.contexts)); this.push(this.objectLiteral(hash.types)); } this.push(this.objectLiteral(hash.values)); }, // [pushString] // // On stack, before: ... // On stack, after: quotedString(string), ... // // Push a quoted version of `string` onto the stack pushString: function pushString(string) { this.pushStackLiteral(this.quotedString(string)); }, // [pushLiteral] // // On stack, before: ... // On stack, after: value, ... // // Pushes a value onto the stack. This operation prevents // the compiler from creating a temporary variable to hold // it. pushLiteral: function pushLiteral(value) { this.pushStackLiteral(value); }, // [pushProgram] // // On stack, before: ... // On stack, after: program(guid), ... // // Push a program expression onto the stack. This takes // a compile-time guid and converts it into a runtime-accessible // expression. pushProgram: function pushProgram(guid) { if (guid != null) { this.pushStackLiteral(this.programExpression(guid)); } else { this.pushStackLiteral(null); } }, // [registerDecorator] // // On stack, before: hash, program, params..., ... // On stack, after: ... // // Pops off the decorator's parameters, invokes the decorator, // and inserts the decorator into the decorators list. registerDecorator: function registerDecorator(paramSize, name) { var foundDecorator = this.nameLookup('decorators', name, 'decorator'), options = this.setupHelperArgs(name, paramSize); this.decorators.push(['fn = ', this.decorators.functionCall(foundDecorator, '', ['fn', 'props', 'container', options]), ' || fn;']); }, // [invokeHelper] // // On stack, before: hash, inverse, program, params..., ... // On stack, after: result of helper invocation // // Pops off the helper's parameters, invokes the helper, // and pushes the helper's return value onto the stack. // // If the helper is not found, `helperMissing` is called. invokeHelper: function invokeHelper(paramSize, name, isSimple) { var nonHelper = this.popStack(), helper = this.setupHelper(paramSize, name), simple = isSimple ? [helper.name, ' || '] : ''; var lookup = ['('].concat(simple, nonHelper); if (!this.options.strict) { lookup.push(' || ', this.aliasable('helpers.helperMissing')); } lookup.push(')'); this.push(this.source.functionCall(lookup, 'call', helper.callParams)); }, // [invokeKnownHelper] // // On stack, before: hash, inverse, program, params..., ... // On stack, after: result of helper invocation // // This operation is used when the helper is known to exist, // so a `helperMissing` fallback is not required. invokeKnownHelper: function invokeKnownHelper(paramSize, name) { var helper = this.setupHelper(paramSize, name); this.push(this.source.functionCall(helper.name, 'call', helper.callParams)); }, // [invokeAmbiguous] // // On stack, before: hash, inverse, program, params..., ... // On stack, after: result of disambiguation // // This operation is used when an expression like `{{foo}}` // is provided, but we don't know at compile-time whether it // is a helper or a path. // // This operation emits more code than the other options, // and can be avoided by passing the `knownHelpers` and // `knownHelpersOnly` flags at compile-time. invokeAmbiguous: function invokeAmbiguous(name, helperCall) { this.useRegister('helper'); var nonHelper = this.popStack(); this.emptyHash(); var helper = this.setupHelper(0, name, helperCall); var helperName = this.lastHelper = this.nameLookup('helpers', name, 'helper'); var lookup = ['(', '(helper = ', helperName, ' || ', nonHelper, ')']; if (!this.options.strict) { lookup[0] = '(helper = '; lookup.push(' != null ? helper : ', this.aliasable('helpers.helperMissing')); } this.push(['(', lookup, helper.paramsInit ? ['),(', helper.paramsInit] : [], '),', '(typeof helper === ', this.aliasable('"function"'), ' ? ', this.source.functionCall('helper', 'call', helper.callParams), ' : helper))']); }, // [invokePartial] // // On stack, before: context, ... // On stack after: result of partial invocation // // This operation pops off a context, invokes a partial with that context, // and pushes the result of the invocation back. invokePartial: function invokePartial(isDynamic, name, indent) { var params = [], options = this.setupParams(name, 1, params); if (isDynamic) { name = this.popStack(); delete options.name; } if (indent) { options.indent = JSON.stringify(indent); } options.helpers = 'helpers'; options.partials = 'partials'; options.decorators = 'container.decorators'; if (!isDynamic) { params.unshift(this.nameLookup('partials', name, 'partial')); } else { params.unshift(name); } if (this.options.compat) { options.depths = 'depths'; } options = this.objectLiteral(options); params.push(options); this.push(this.source.functionCall('container.invokePartial', '', params)); }, // [assignToHash] // // On stack, before: value, ..., hash, ... // On stack, after: ..., hash, ... // // Pops a value off the stack and assigns it to the current hash assignToHash: function assignToHash(key) { var value = this.popStack(), context = undefined, type = undefined, id = undefined; if (this.trackIds) { id = this.popStack(); } if (this.stringParams) { type = this.popStack(); context = this.popStack(); } var hash = this.hash; if (context) { hash.contexts[key] = context; } if (type) { hash.types[key] = type; } if (id) { hash.ids[key] = id; } hash.values[key] = value; }, pushId: function pushId(type, name, child) { if (type === 'BlockParam') { this.pushStackLiteral('blockParams[' + name[0] + '].path[' + name[1] + ']' + (child ? ' + ' + JSON.stringify('.' + child) : '')); } else if (type === 'PathExpression') { this.pushString(name); } else if (type === 'SubExpression') { this.pushStackLiteral('true'); } else { this.pushStackLiteral('null'); } }, // HELPERS compiler: JavaScriptCompiler, compileChildren: function compileChildren(environment, options) { var children = environment.children, child = undefined, compiler = undefined; for (var i = 0, l = children.length; i < l; i++) { child = children[i]; compiler = new this.compiler(); // eslint-disable-line new-cap var existing = this.matchExistingProgram(child); if (existing == null) { this.context.programs.push(''); // Placeholder to prevent name conflicts for nested children var index = this.context.programs.length; child.index = index; child.name = 'program' + index; this.context.programs[index] = compiler.compile(child, options, this.context, !this.precompile); this.context.decorators[index] = compiler.decorators; this.context.environments[index] = child; this.useDepths = this.useDepths || compiler.useDepths; this.useBlockParams = this.useBlockParams || compiler.useBlockParams; child.useDepths = this.useDepths; child.useBlockParams = this.useBlockParams; } else { child.index = existing.index; child.name = 'program' + existing.index; this.useDepths = this.useDepths || existing.useDepths; this.useBlockParams = this.useBlockParams || existing.useBlockParams; } } }, matchExistingProgram: function matchExistingProgram(child) { for (var i = 0, len = this.context.environments.length; i < len; i++) { var environment = this.context.environments[i]; if (environment && environment.equals(child)) { return environment; } } }, programExpression: function programExpression(guid) { var child = this.environment.children[guid], programParams = [child.index, 'data', child.blockParams]; if (this.useBlockParams || this.useDepths) { programParams.push('blockParams'); } if (this.useDepths) { programParams.push('depths'); } return 'container.program(' + programParams.join(', ') + ')'; }, useRegister: function useRegister(name) { if (!this.registers[name]) { this.registers[name] = true; this.registers.list.push(name); } }, push: function push(expr) { if (!(expr instanceof Literal)) { expr = this.source.wrap(expr); } this.inlineStack.push(expr); return expr; }, pushStackLiteral: function pushStackLiteral(item) { this.push(new Literal(item)); }, pushSource: function pushSource(source) { if (this.pendingContent) { this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent), this.pendingLocation)); this.pendingContent = undefined; } if (source) { this.source.push(source); } }, replaceStack: function replaceStack(callback) { var prefix = ['('], stack = undefined, createdStack = undefined, usedLiteral = undefined; /* istanbul ignore next */ if (!this.isInline()) { throw new _exception2['default']('replaceStack on non-inline'); } // We want to merge the inline statement into the replacement statement via ',' var top = this.popStack(true); if (top instanceof Literal) { // Literals do not need to be inlined stack = [top.value]; prefix = ['(', stack]; usedLiteral = true; } else { // Get or create the current stack name for use by the inline createdStack = true; var _name = this.incrStack(); prefix = ['((', this.push(_name), ' = ', top, ')']; stack = this.topStack(); } var item = callback.call(this, stack); if (!usedLiteral) { this.popStack(); } if (createdStack) { this.stackSlot--; } this.push(prefix.concat(item, ')')); }, incrStack: function incrStack() { this.stackSlot++; if (this.stackSlot > this.stackVars.length) { this.stackVars.push('stack' + this.stackSlot); } return this.topStackName(); }, topStackName: function topStackName() { return 'stack' + this.stackSlot; }, flushInline: function flushInline() { var inlineStack = this.inlineStack; this.inlineStack = []; for (var i = 0, len = inlineStack.length; i < len; i++) { var entry = inlineStack[i]; /* istanbul ignore if */ if (entry instanceof Literal) { this.compileStack.push(entry); } else { var stack = this.incrStack(); this.pushSource([stack, ' = ', entry, ';']); this.compileStack.push(stack); } } }, isInline: function isInline() { return this.inlineStack.length; }, popStack: function popStack(wrapped) { var inline = this.isInline(), item = (inline ? this.inlineStack : this.compileStack).pop(); if (!wrapped && item instanceof Literal) { return item.value; } else { if (!inline) { /* istanbul ignore next */ if (!this.stackSlot) { throw new _exception2['default']('Invalid stack pop'); } this.stackSlot--; } return item; } }, topStack: function topStack() { var stack = this.isInline() ? this.inlineStack : this.compileStack, item = stack[stack.length - 1]; /* istanbul ignore if */ if (item instanceof Literal) { return item.value; } else { return item; } }, contextName: function contextName(context) { if (this.useDepths && context) { return 'depths[' + context + ']'; } else { return 'depth' + context; } }, quotedString: function quotedString(str) { return this.source.quotedString(str); }, objectLiteral: function objectLiteral(obj) { return this.source.objectLiteral(obj); }, aliasable: function aliasable(name) { var ret = this.aliases[name]; if (ret) { ret.referenceCount++; return ret; } ret = this.aliases[name] = this.source.wrap(name); ret.aliasable = true; ret.referenceCount = 1; return ret; }, setupHelper: function setupHelper(paramSize, name, blockHelper) { var params = [], paramsInit = this.setupHelperArgs(name, paramSize, params, blockHelper); var foundHelper = this.nameLookup('helpers', name, 'helper'), callContext = this.aliasable(this.contextName(0) + ' != null ? ' + this.contextName(0) + ' : (container.nullContext || {})'); return { params: params, paramsInit: paramsInit, name: foundHelper, callParams: [callContext].concat(params) }; }, setupParams: function setupParams(helper, paramSize, params) { var options = {}, contexts = [], types = [], ids = [], objectArgs = !params, param = undefined; if (objectArgs) { params = []; } options.name = this.quotedString(helper); options.hash = this.popStack(); if (this.trackIds) { options.hashIds = this.popStack(); } if (this.stringParams) { options.hashTypes = this.popStack(); options.hashContexts = this.popStack(); } var inverse = this.popStack(), program = this.popStack(); // Avoid setting fn and inverse if neither are set. This allows // helpers to do a check for `if (options.fn)` if (program || inverse) { options.fn = program || 'container.noop'; options.inverse = inverse || 'container.noop'; } // The parameters go on to the stack in order (making sure that they are evaluated in order) // so we need to pop them off the stack in reverse order var i = paramSize; while (i--) { param = this.popStack(); params[i] = param; if (this.trackIds) { ids[i] = this.popStack(); } if (this.stringParams) { types[i] = this.popStack(); contexts[i] = this.popStack(); } } if (objectArgs) { options.args = this.source.generateArray(params); } if (this.trackIds) { options.ids = this.source.generateArray(ids); } if (this.stringParams) { options.types = this.source.generateArray(types); options.contexts = this.source.generateArray(contexts); } if (this.options.data) { options.data = 'data'; } if (this.useBlockParams) { options.blockParams = 'blockParams'; } return options; }, setupHelperArgs: function setupHelperArgs(helper, paramSize, params, useRegister) { var options = this.setupParams(helper, paramSize, params); options = this.objectLiteral(options); if (useRegister) { this.useRegister('options'); params.push('options'); return ['options=', options]; } else if (params) { params.push(options); return ''; } else { return options; } } }; (function () { var reservedWords = ('break else new var' + ' case finally return void' + ' catch for switch while' + ' continue function this with' + ' default if throw' + ' delete in try' + ' do instanceof typeof' + ' abstract enum int short' + ' boolean export interface static' + ' byte extends long super' + ' char final native synchronized' + ' class float package throws' + ' const goto private transient' + ' debugger implements protected volatile' + ' double import public let yield await' + ' null true false').split(' '); var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {}; for (var i = 0, l = reservedWords.length; i < l; i++) { compilerWords[reservedWords[i]] = true; } })(); JavaScriptCompiler.isValidJavaScriptVariableName = function (name) { return !JavaScriptCompiler.RESERVED_WORDS[name] && /^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name); }; function strictLookup(requireTerminal, compiler, parts, type) { var stack = compiler.popStack(), i = 0, len = parts.length; if (requireTerminal) { len--; } for (; i < len; i++) { stack = compiler.nameLookup(stack, parts[i], type); } if (requireTerminal) { return [compiler.aliasable('container.strict'), '(', stack, ', ', compiler.quotedString(parts[i]), ')']; } else { return stack; } } exports['default'] = JavaScriptCompiler; module.exports = exports['default']; /***/ }), /* 43 */ /***/ (function(module, exports, __webpack_require__) { /* global define */ 'use strict'; exports.__esModule = true; var _utils = __webpack_require__(5); var SourceNode = undefined; try { /* istanbul ignore next */ if (false) { // We don't support this in AMD environments. For these environments, we asusme that // they are running on the browser and thus have no need for the source-map library. var SourceMap = require('source-map'); SourceNode = SourceMap.SourceNode; } } catch (err) {} /* NOP */ /* istanbul ignore if: tested but not covered in istanbul due to dist build */ if (!SourceNode) { SourceNode = function (line, column, srcFile, chunks) { this.src = ''; if (chunks) { this.add(chunks); } }; /* istanbul ignore next */ SourceNode.prototype = { add: function add(chunks) { if (_utils.isArray(chunks)) { chunks = chunks.join(''); } this.src += chunks; }, prepend: function prepend(chunks) { if (_utils.isArray(chunks)) { chunks = chunks.join(''); } this.src = chunks + this.src; }, toStringWithSourceMap: function toStringWithSourceMap() { return { code: this.toString() }; }, toString: function toString() { return this.src; } }; } function castChunk(chunk, codeGen, loc) { if (_utils.isArray(chunk)) { var ret = []; for (var i = 0, len = chunk.length; i < len; i++) { ret.push(codeGen.wrap(chunk[i], loc)); } return ret; } else if (typeof chunk === 'boolean' || typeof chunk === 'number') { // Handle primitives that the SourceNode will throw up on return chunk + ''; } return chunk; } function CodeGen(srcFile) { this.srcFile = srcFile; this.source = []; } CodeGen.prototype = { isEmpty: function isEmpty() { return !this.source.length; }, prepend: function prepend(source, loc) { this.source.unshift(this.wrap(source, loc)); }, push: function push(source, loc) { this.source.push(this.wrap(source, loc)); }, merge: function merge() { var source = this.empty(); this.each(function (line) { source.add([' ', line, '\n']); }); return source; }, each: function each(iter) { for (var i = 0, len = this.source.length; i < len; i++) { iter(this.source[i]); } }, empty: function empty() { var loc = this.currentLocation || { start: {} }; return new SourceNode(loc.start.line, loc.start.column, this.srcFile); }, wrap: function wrap(chunk) { var loc = arguments.length <= 1 || arguments[1] === undefined ? this.currentLocation || { start: {} } : arguments[1]; if (chunk instanceof SourceNode) { return chunk; } chunk = castChunk(chunk, this, loc); return new SourceNode(loc.start.line, loc.start.column, this.srcFile, chunk); }, functionCall: function functionCall(fn, type, params) { params = this.generateList(params); return this.wrap([fn, type ? '.' + type + '(' : '(', params, ')']); }, quotedString: function quotedString(str) { return '"' + (str + '').replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\u2028/g, '\\u2028') // Per Ecma-262 7.3 + 7.8.4 .replace(/\u2029/g, '\\u2029') + '"'; }, objectLiteral: function objectLiteral(obj) { var pairs = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { var value = castChunk(obj[key], this); if (value !== 'undefined') { pairs.push([this.quotedString(key), ':', value]); } } } var ret = this.generateList(pairs); ret.prepend('{'); ret.add('}'); return ret; }, generateList: function generateList(entries) { var ret = this.empty(); for (var i = 0, len = entries.length; i < len; i++) { if (i) { ret.add(','); } ret.add(castChunk(entries[i], this)); } return ret; }, generateArray: function generateArray(entries) { var ret = this.generateList(entries); ret.prepend('['); ret.add(']'); return ret; } }; exports['default'] = CodeGen; module.exports = exports['default']; /***/ }) /******/ ]) }); ; /***/ }), /* 63 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * The EventManager is in charge of registering user interctions with the viewer. * It is used in the TemplateManager */ var EventManager = /** @class */ (function () { function EventManager(_templateManager) { var _this = this; this._templateManager = _templateManager; this._callbacksContainer = {}; this._templateManager.onEventTriggered.add(function (eventData) { _this._eventTriggered(eventData); }); } /** * Register a new callback to a specific template. * The best example for the usage can be found in the DefaultViewer * * @param templateName the templateName to register the event to * @param callback The callback to be executed * @param eventType the type of event to register * @param selector an optional selector. if not defined the parent object in the template will be selected */ EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) { if (!this._callbacksContainer[templateName]) { this._callbacksContainer[templateName] = []; } this._callbacksContainer[templateName].push({ eventType: eventType, callback: callback, selector: selector }); }; /** * This will remove a registered event from the defined template. * Each one of the variables apart from the template name are optional, but one must be provided. * * @param templateName the templateName * @param callback the callback to remove (optional) * @param eventType the event type to remove (optional) * @param selector the selector from which to remove the event (optional) */ EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) { var callbackDefs = this._callbacksContainer[templateName] || []; this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }); }; EventManager.prototype._eventTriggered = function (data) { var templateName = data.template.name; var eventType = data.event.type; var selector = data.selector; var callbackDefs = this._callbacksContainer[templateName] || []; callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) { callbackDef.callback(data); }); }; /** * Dispose the event manager */ EventManager.prototype.dispose = function () { this._callbacksContainer = {}; }; return EventManager; }()); exports.EventManager = EventManager; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXZlbnRNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3RlbXBsYXRpbmcvZXZlbnRNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBR0E7OztHQUdHO0FBQ0g7SUFJSSxzQkFBb0IsZ0JB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***/ }), /* 64 */ /***/ (function(module, exports, __webpack_require__) { /*! * PEP v0.4.3 | https://github.com/jquery/PEP * Copyright jQuery Foundation and other contributors | http://jquery.org/license */ (function (global, factory) { true ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.PointerEventsPolyfill = factory()); }(this, function () { 'use strict'; /** * This is the constructor for new PointerEvents. * * New Pointer Events must be given a type, and an optional dictionary of * initialization properties. * * Due to certain platform requirements, events returned from the constructor * identify as MouseEvents. * * @constructor * @param {String} inType The type of the event to create. * @param {Object} [inDict] An optional dictionary of initial event properties. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`. */ var MOUSE_PROPS = [ 'bubbles', 'cancelable', 'view', 'detail', 'screenX', 'screenY', 'clientX', 'clientY', 'ctrlKey', 'altKey', 'shiftKey', 'metaKey', 'button', 'relatedTarget', 'pageX', 'pageY' ]; var MOUSE_DEFAULTS = [ false, false, null, null, 0, 0, 0, 0, false, false, false, false, 0, null, 0, 0 ]; function PointerEvent(inType, inDict) { inDict = inDict || Object.create(null); var e = document.createEvent('Event'); e.initEvent(inType, inDict.bubbles || false, inDict.cancelable || false); // define inherited MouseEvent properties // skip bubbles and cancelable since they're set above in initEvent() for (var i = 2, p; i < MOUSE_PROPS.length; i++) { p = MOUSE_PROPS[i]; e[p] = inDict[p] || MOUSE_DEFAULTS[i]; } e.buttons = inDict.buttons || 0; // Spec requires that pointers without pressure specified use 0.5 for down // state and 0 for up state. var pressure = 0; if (inDict.pressure && e.buttons) { pressure = inDict.pressure; } else { pressure = e.buttons ? 0.5 : 0; } // add x/y properties aliased to clientX/Y e.x = e.clientX; e.y = e.clientY; // define the properties of the PointerEvent interface e.pointerId = inDict.pointerId || 0; e.width = inDict.width || 0; e.height = inDict.height || 0; e.pressure = pressure; e.tiltX = inDict.tiltX || 0; e.tiltY = inDict.tiltY || 0; e.twist = inDict.twist || 0; e.tangentialPressure = inDict.tangentialPressure || 0; e.pointerType = inDict.pointerType || ''; e.hwTimestamp = inDict.hwTimestamp || 0; e.isPrimary = inDict.isPrimary || false; return e; } /** * This module implements a map of pointer states */ var USE_MAP = window.Map && window.Map.prototype.forEach; var PointerMap = USE_MAP ? Map : SparseArrayMap; function SparseArrayMap() { this.array = []; this.size = 0; } SparseArrayMap.prototype = { set: function(k, v) { if (v === undefined) { return this.delete(k); } if (!this.has(k)) { this.size++; } this.array[k] = v; }, has: function(k) { return this.array[k] !== undefined; }, delete: function(k) { if (this.has(k)) { delete this.array[k]; this.size--; } }, get: function(k) { return this.array[k]; }, clear: function() { this.array.length = 0; this.size = 0; }, // return value, key, map forEach: function(callback, thisArg) { return this.array.forEach(function(v, k) { callback.call(thisArg, v, k, this); }, this); } }; var CLONE_PROPS = [ // MouseEvent 'bubbles', 'cancelable', 'view', 'detail', 'screenX', 'screenY', 'clientX', 'clientY', 'ctrlKey', 'altKey', 'shiftKey', 'metaKey', 'button', 'relatedTarget', // DOM Level 3 'buttons', // PointerEvent 'pointerId', 'width', 'height', 'pressure', 'tiltX', 'tiltY', 'pointerType', 'hwTimestamp', 'isPrimary', // event instance 'type', 'target', 'currentTarget', 'which', 'pageX', 'pageY', 'timeStamp' ]; var CLONE_DEFAULTS = [ // MouseEvent false, false, null, null, 0, 0, 0, 0, false, false, false, false, 0, null, // DOM Level 3 0, // PointerEvent 0, 0, 0, 0, 0, 0, '', 0, false, // event instance '', null, null, 0, 0, 0, 0 ]; var BOUNDARY_EVENTS = { 'pointerover': 1, 'pointerout': 1, 'pointerenter': 1, 'pointerleave': 1 }; var HAS_SVG_INSTANCE = (typeof SVGElementInstance !== 'undefined'); /** * This module is for normalizing events. Mouse and Touch events will be * collected here, and fire PointerEvents that have the same semantics, no * matter the source. * Events fired: * - pointerdown: a pointing is added * - pointerup: a pointer is removed * - pointermove: a pointer is moved * - pointerover: a pointer crosses into an element * - pointerout: a pointer leaves an element * - pointercancel: a pointer will no longer generate events */ var dispatcher = { pointermap: new PointerMap(), eventMap: Object.create(null), captureInfo: Object.create(null), // Scope objects for native events. // This exists for ease of testing. eventSources: Object.create(null), eventSourceList: [], /** * Add a new event source that will generate pointer events. * * `inSource` must contain an array of event names named `events`, and * functions with the names specified in the `events` array. * @param {string} name A name for the event source * @param {Object} source A new source of platform events. */ registerSource: function(name, source) { var s = source; var newEvents = s.events; if (newEvents) { newEvents.forEach(function(e) { if (s[e]) { this.eventMap[e] = s[e].bind(s); } }, this); this.eventSources[name] = s; this.eventSourceList.push(s); } }, register: function(element) { var l = this.eventSourceList.length; for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) { // call eventsource register es.register.call(es, element); } }, unregister: function(element) { var l = this.eventSourceList.length; for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) { // call eventsource register es.unregister.call(es, element); } }, contains: /*scope.external.contains || */function(container, contained) { try { return container.contains(contained); } catch (ex) { // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427 return false; } }, // EVENTS down: function(inEvent) { inEvent.bubbles = true; this.fireEvent('pointerdown', inEvent); }, move: function(inEvent) { inEvent.bubbles = true; this.fireEvent('pointermove', inEvent); }, up: function(inEvent) { inEvent.bubbles = true; this.fireEvent('pointerup', inEvent); }, enter: function(inEvent) { inEvent.bubbles = false; this.fireEvent('pointerenter', inEvent); }, leave: function(inEvent) { inEvent.bubbles = false; this.fireEvent('pointerleave', inEvent); }, over: function(inEvent) { inEvent.bubbles = true; this.fireEvent('pointerover', inEvent); }, out: function(inEvent) { inEvent.bubbles = true; this.fireEvent('pointerout', inEvent); }, cancel: function(inEvent) { inEvent.bubbles = true; this.fireEvent('pointercancel', inEvent); }, leaveOut: function(event) { this.out(event); this.propagate(event, this.leave, false); }, enterOver: function(event) { this.over(event); this.propagate(event, this.enter, true); }, // LISTENER LOGIC eventHandler: function(inEvent) { // This is used to prevent multiple dispatch of pointerevents from // platform events. This can happen when two elements in different scopes // are set up to create pointer events, which is relevant to Shadow DOM. if (inEvent._handledByPE) { return; } var type = inEvent.type; var fn = this.eventMap && this.eventMap[type]; if (fn) { fn(inEvent); } inEvent._handledByPE = true; }, // set up event listeners listen: function(target, events) { events.forEach(function(e) { this.addEvent(target, e); }, this); }, // remove event listeners unlisten: function(target, events) { events.forEach(function(e) { this.removeEvent(target, e); }, this); }, addEvent: /*scope.external.addEvent || */function(target, eventName) { target.addEventListener(eventName, this.boundHandler); }, removeEvent: /*scope.external.removeEvent || */function(target, eventName) { target.removeEventListener(eventName, this.boundHandler); }, // EVENT CREATION AND TRACKING /** * Creates a new Event of type `inType`, based on the information in * `inEvent`. * * @param {string} inType A string representing the type of event to create * @param {Event} inEvent A platform event with a target * @return {Event} A PointerEvent of type `inType` */ makeEvent: function(inType, inEvent) { // relatedTarget must be null if pointer is captured if (this.captureInfo[inEvent.pointerId]) { inEvent.relatedTarget = null; } var e = new PointerEvent(inType, inEvent); if (inEvent.preventDefault) { e.preventDefault = inEvent.preventDefault; } e._target = e._target || inEvent.target; return e; }, // make and dispatch an event in one call fireEvent: function(inType, inEvent) { var e = this.makeEvent(inType, inEvent); return this.dispatchEvent(e); }, /** * Returns a snapshot of inEvent, with writable properties. * * @param {Event} inEvent An event that contains properties to copy. * @return {Object} An object containing shallow copies of `inEvent`'s * properties. */ cloneEvent: function(inEvent) { var eventCopy = Object.create(null); var p; for (var i = 0; i < CLONE_PROPS.length; i++) { p = CLONE_PROPS[i]; eventCopy[p] = inEvent[p] || CLONE_DEFAULTS[i]; // Work around SVGInstanceElement shadow tree // Return the element that is represented by the instance for Safari, Chrome, IE. // This is the behavior implemented by Firefox. if (HAS_SVG_INSTANCE && (p === 'target' || p === 'relatedTarget')) { if (eventCopy[p] instanceof SVGElementInstance) { eventCopy[p] = eventCopy[p].correspondingUseElement; } } } // keep the semantics of preventDefault if (inEvent.preventDefault) { eventCopy.preventDefault = function() { inEvent.preventDefault(); }; } return eventCopy; }, getTarget: function(inEvent) { var capture = this.captureInfo[inEvent.pointerId]; if (!capture) { return inEvent._target; } if (inEvent._target === capture || !(inEvent.type in BOUNDARY_EVENTS)) { return capture; } }, propagate: function(event, fn, propagateDown) { var target = event.target; var targets = []; // Order of conditions due to document.contains() missing in IE. while (target !== document && !target.contains(event.relatedTarget)) { targets.push(target); target = target.parentNode; // Touch: Do not propagate if node is detached. if (!target) { return; } } if (propagateDown) { targets.reverse(); } targets.forEach(function(target) { event.target = target; fn.call(this, event); }, this); }, setCapture: function(inPointerId, inTarget, skipDispatch) { if (this.captureInfo[inPointerId]) { this.releaseCapture(inPointerId, skipDispatch); } this.captureInfo[inPointerId] = inTarget; this.implicitRelease = this.releaseCapture.bind(this, inPointerId, skipDispatch); document.addEventListener('pointerup', this.implicitRelease); document.addEventListener('pointercancel', this.implicitRelease); var e = new PointerEvent('gotpointercapture'); e.pointerId = inPointerId; e._target = inTarget; if (!skipDispatch) { this.asyncDispatchEvent(e); } }, releaseCapture: function(inPointerId, skipDispatch) { var t = this.captureInfo[inPointerId]; if (!t) { return; } this.captureInfo[inPointerId] = undefined; document.removeEventListener('pointerup', this.implicitRelease); document.removeEventListener('pointercancel', this.implicitRelease); var e = new PointerEvent('lostpointercapture'); e.pointerId = inPointerId; e._target = t; if (!skipDispatch) { this.asyncDispatchEvent(e); } }, /** * Dispatches the event to its target. * * @param {Event} inEvent The event to be dispatched. * @return {Boolean} True if an event handler returns true, false otherwise. */ dispatchEvent: /*scope.external.dispatchEvent || */function(inEvent) { var t = this.getTarget(inEvent); if (t) { return t.dispatchEvent(inEvent); } }, asyncDispatchEvent: function(inEvent) { requestAnimationFrame(this.dispatchEvent.bind(this, inEvent)); } }; dispatcher.boundHandler = dispatcher.eventHandler.bind(dispatcher); var targeting = { shadow: function(inEl) { if (inEl) { return inEl.shadowRoot || inEl.webkitShadowRoot; } }, canTarget: function(shadow) { return shadow && Boolean(shadow.elementFromPoint); }, targetingShadow: function(inEl) { var s = this.shadow(inEl); if (this.canTarget(s)) { return s; } }, olderShadow: function(shadow) { var os = shadow.olderShadowRoot; if (!os) { var se = shadow.querySelector('shadow'); if (se) { os = se.olderShadowRoot; } } return os; }, allShadows: function(element) { var shadows = []; var s = this.shadow(element); while (s) { shadows.push(s); s = this.olderShadow(s); } return shadows; }, searchRoot: function(inRoot, x, y) { if (inRoot) { var t = inRoot.elementFromPoint(x, y); var st, sr; // is element a shadow host? sr = this.targetingShadow(t); while (sr) { // find the the element inside the shadow root st = sr.elementFromPoint(x, y); if (!st) { // check for older shadows sr = this.olderShadow(sr); } else { // shadowed element may contain a shadow root var ssr = this.targetingShadow(st); return this.searchRoot(ssr, x, y) || st; } } // light dom element is the target return t; } }, owner: function(element) { var s = element; // walk up until you hit the shadow root or document while (s.parentNode) { s = s.parentNode; } // the owner element is expected to be a Document or ShadowRoot if (s.nodeType !== Node.DOCUMENT_NODE && s.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) { s = document; } return s; }, findTarget: function(inEvent) { var x = inEvent.clientX; var y = inEvent.clientY; // if the listener is in the shadow root, it is much faster to start there var s = this.owner(inEvent.target); // if x, y is not in this root, fall back to document search if (!s.elementFromPoint(x, y)) { s = document; } return this.searchRoot(s, x, y); } }; var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach); var map = Array.prototype.map.call.bind(Array.prototype.map); var toArray = Array.prototype.slice.call.bind(Array.prototype.slice); var filter = Array.prototype.filter.call.bind(Array.prototype.filter); var MO = window.MutationObserver || window.WebKitMutationObserver; var SELECTOR = '[touch-action]'; var OBSERVER_INIT = { subtree: true, childList: true, attributes: true, attributeOldValue: true, attributeFilter: ['touch-action'] }; function Installer(add, remove, changed, binder) { this.addCallback = add.bind(binder); this.removeCallback = remove.bind(binder); this.changedCallback = changed.bind(binder); if (MO) { this.observer = new MO(this.mutationWatcher.bind(this)); } } Installer.prototype = { watchSubtree: function(target) { // Only watch scopes that can target find, as these are top-level. // Otherwise we can see duplicate additions and removals that add noise. // // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see // a removal without an insertion when a node is redistributed among // shadows. Since it all ends up correct in the document, watching only // the document will yield the correct mutations to watch. if (this.observer && targeting.canTarget(target)) { this.observer.observe(target, OBSERVER_INIT); } }, enableOnSubtree: function(target) { this.watchSubtree(target); if (target === document && document.readyState !== 'complete') { this.installOnLoad(); } else { this.installNewSubtree(target); } }, installNewSubtree: function(target) { forEach(this.findElements(target), this.addElement, this); }, findElements: function(target) { if (target.querySelectorAll) { return target.querySelectorAll(SELECTOR); } return []; }, removeElement: function(el) { this.removeCallback(el); }, addElement: function(el) { this.addCallback(el); }, elementChanged: function(el, oldValue) { this.changedCallback(el, oldValue); }, concatLists: function(accum, list) { return accum.concat(toArray(list)); }, // register all touch-action = none nodes on document load installOnLoad: function() { document.addEventListener('readystatechange', function() { if (document.readyState === 'complete') { this.installNewSubtree(document); } }.bind(this)); }, isElement: function(n) { return n.nodeType === Node.ELEMENT_NODE; }, flattenMutationTree: function(inNodes) { // find children with touch-action var tree = map(inNodes, this.findElements, this); // make sure the added nodes are accounted for tree.push(filter(inNodes, this.isElement)); // flatten the list return tree.reduce(this.concatLists, []); }, mutationWatcher: function(mutations) { mutations.forEach(this.mutationHandler, this); }, mutationHandler: function(m) { if (m.type === 'childList') { var added = this.flattenMutationTree(m.addedNodes); added.forEach(this.addElement, this); var removed = this.flattenMutationTree(m.removedNodes); removed.forEach(this.removeElement, this); } else if (m.type === 'attributes') { this.elementChanged(m.target, m.oldValue); } } }; function shadowSelector(v) { return 'body /shadow-deep/ ' + selector(v); } function selector(v) { return '[touch-action="' + v + '"]'; } function rule(v) { return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + '; }'; } var attrib2css = [ 'none', 'auto', 'pan-x', 'pan-y', { rule: 'pan-x pan-y', selectors: [ 'pan-x pan-y', 'pan-y pan-x' ] } ]; var styles = ''; // only install stylesheet if the browser has touch action support var hasNativePE = window.PointerEvent || window.MSPointerEvent; // only add shadow selectors if shadowdom is supported var hasShadowRoot = !window.ShadowDOMPolyfill && document.head.createShadowRoot; function applyAttributeStyles() { if (hasNativePE) { attrib2css.forEach(function(r) { if (String(r) === r) { styles += selector(r) + rule(r) + '\n'; if (hasShadowRoot) { styles += shadowSelector(r) + rule(r) + '\n'; } } else { styles += r.selectors.map(selector) + rule(r.rule) + '\n'; if (hasShadowRoot) { styles += r.selectors.map(shadowSelector) + rule(r.rule) + '\n'; } } }); var el = document.createElement('style'); el.textContent = styles; document.head.appendChild(el); } } var pointermap = dispatcher.pointermap; // radius around touchend that swallows mouse events var DEDUP_DIST = 25; // left, middle, right, back, forward var BUTTON_TO_BUTTONS = [1, 4, 2, 8, 16]; var HAS_BUTTONS = false; try { HAS_BUTTONS = new MouseEvent('test', { buttons: 1 }).buttons === 1; } catch (e) {} // handler block for native mouse events var mouseEvents = { POINTER_ID: 1, POINTER_TYPE: 'mouse', events: [ 'mousedown', 'mousemove', 'mouseup', 'mouseover', 'mouseout' ], register: function(target) { dispatcher.listen(target, this.events); }, unregister: function(target) { dispatcher.unlisten(target, this.events); }, lastTouches: [], // collide with the global mouse listener isEventSimulatedFromTouch: function(inEvent) { var lts = this.lastTouches; var x = inEvent.clientX; var y = inEvent.clientY; for (var i = 0, l = lts.length, t; i < l && (t = lts[i]); i++) { // simulated mouse events will be swallowed near a primary touchend var dx = Math.abs(x - t.x); var dy = Math.abs(y - t.y); if (dx <= DEDUP_DIST && dy <= DEDUP_DIST) { return true; } } }, prepareEvent: function(inEvent) { var e = dispatcher.cloneEvent(inEvent); // forward mouse preventDefault var pd = e.preventDefault; e.preventDefault = function() { inEvent.preventDefault(); pd(); }; e.pointerId = this.POINTER_ID; e.isPrimary = true; e.pointerType = this.POINTER_TYPE; return e; }, prepareButtonsForMove: function(e, inEvent) { var p = pointermap.get(this.POINTER_ID); // Update buttons state after possible out-of-document mouseup. if (inEvent.which === 0 || !p) { e.buttons = 0; } else { e.buttons = p.buttons; } inEvent.buttons = e.buttons; }, mousedown: function(inEvent) { if (!this.isEventSimulatedFromTouch(inEvent)) { var p = pointermap.get(this.POINTER_ID); var e = this.prepareEvent(inEvent); if (!HAS_BUTTONS) { e.buttons = BUTTON_TO_BUTTONS[e.button]; if (p) { e.buttons |= p.buttons; } inEvent.buttons = e.buttons; } pointermap.set(this.POINTER_ID, inEvent); if (!p || p.buttons === 0) { dispatcher.down(e); } else { dispatcher.move(e); } } }, mousemove: function(inEvent) { if (!this.isEventSimulatedFromTouch(inEvent)) { var e = this.prepareEvent(inEvent); if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); } e.button = -1; pointermap.set(this.POINTER_ID, inEvent); dispatcher.move(e); } }, mouseup: function(inEvent) { if (!this.isEventSimulatedFromTouch(inEvent)) { var p = pointermap.get(this.POINTER_ID); var e = this.prepareEvent(inEvent); if (!HAS_BUTTONS) { var up = BUTTON_TO_BUTTONS[e.button]; // Produces wrong state of buttons in Browsers without `buttons` support // when a mouse button that was pressed outside the document is released // inside and other buttons are still pressed down. e.buttons = p ? p.buttons & ~up : 0; inEvent.buttons = e.buttons; } pointermap.set(this.POINTER_ID, inEvent); // Support: Firefox <=44 only // FF Ubuntu includes the lifted button in the `buttons` property on // mouseup. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366 e.buttons &= ~BUTTON_TO_BUTTONS[e.button]; if (e.buttons === 0) { dispatcher.up(e); } else { dispatcher.move(e); } } }, mouseover: function(inEvent) { if (!this.isEventSimulatedFromTouch(inEvent)) { var e = this.prepareEvent(inEvent); if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); } e.button = -1; pointermap.set(this.POINTER_ID, inEvent); dispatcher.enterOver(e); } }, mouseout: function(inEvent) { if (!this.isEventSimulatedFromTouch(inEvent)) { var e = this.prepareEvent(inEvent); if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); } e.button = -1; dispatcher.leaveOut(e); } }, cancel: function(inEvent) { var e = this.prepareEvent(inEvent); dispatcher.cancel(e); this.deactivateMouse(); }, deactivateMouse: function() { pointermap.delete(this.POINTER_ID); } }; var captureInfo = dispatcher.captureInfo; var findTarget = targeting.findTarget.bind(targeting); var allShadows = targeting.allShadows.bind(targeting); var pointermap$1 = dispatcher.pointermap; // This should be long enough to ignore compat mouse events made by touch var DEDUP_TIMEOUT = 2500; var CLICK_COUNT_TIMEOUT = 200; var ATTRIB = 'touch-action'; var INSTALLER; // handler block for native touch events var touchEvents = { events: [ 'touchstart', 'touchmove', 'touchend', 'touchcancel' ], register: function(target) { INSTALLER.enableOnSubtree(target); }, unregister: function() { // TODO(dfreedman): is it worth it to disconnect the MO? }, elementAdded: function(el) { var a = el.getAttribute(ATTRIB); var st = this.touchActionToScrollType(a); if (st) { el._scrollType = st; dispatcher.listen(el, this.events); // set touch-action on shadows as well allShadows(el).forEach(function(s) { s._scrollType = st; dispatcher.listen(s, this.events); }, this); } }, elementRemoved: function(el) { el._scrollType = undefined; dispatcher.unlisten(el, this.events); // remove touch-action from shadow allShadows(el).forEach(function(s) { s._scrollType = undefined; dispatcher.unlisten(s, this.events); }, this); }, elementChanged: function(el, oldValue) { var a = el.getAttribute(ATTRIB); var st = this.touchActionToScrollType(a); var oldSt = this.touchActionToScrollType(oldValue); // simply update scrollType if listeners are already established if (st && oldSt) { el._scrollType = st; allShadows(el).forEach(function(s) { s._scrollType = st; }, this); } else if (oldSt) { this.elementRemoved(el); } else if (st) { this.elementAdded(el); } }, scrollTypes: { EMITTER: 'none', XSCROLLER: 'pan-x', YSCROLLER: 'pan-y', SCROLLER: /^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/ }, touchActionToScrollType: function(touchAction) { var t = touchAction; var st = this.scrollTypes; if (t === 'none') { return 'none'; } else if (t === st.XSCROLLER) { return 'X'; } else if (t === st.YSCROLLER) { return 'Y'; } else if (st.SCROLLER.exec(t)) { return 'XY'; } }, POINTER_TYPE: 'touch', firstTouch: null, isPrimaryTouch: function(inTouch) { return this.firstTouch === inTouch.identifier; }, setPrimaryTouch: function(inTouch) { // set primary touch if there no pointers, or the only pointer is the mouse if (pointermap$1.size === 0 || (pointermap$1.size === 1 && pointermap$1.has(1))) { this.firstTouch = inTouch.identifier; this.firstXY = { X: inTouch.clientX, Y: inTouch.clientY }; this.scrolling = false; this.cancelResetClickCount(); } }, removePrimaryPointer: function(inPointer) { if (inPointer.isPrimary) { this.firstTouch = null; this.firstXY = null; this.resetClickCount(); } }, clickCount: 0, resetId: null, resetClickCount: function() { var fn = function() { this.clickCount = 0; this.resetId = null; }.bind(this); this.resetId = setTimeout(fn, CLICK_COUNT_TIMEOUT); }, cancelResetClickCount: function() { if (this.resetId) { clearTimeout(this.resetId); } }, typeToButtons: function(type) { var ret = 0; if (type === 'touchstart' || type === 'touchmove') { ret = 1; } return ret; }, touchToPointer: function(inTouch) { var cte = this.currentTouchEvent; var e = dispatcher.cloneEvent(inTouch); // We reserve pointerId 1 for Mouse. // Touch identifiers can start at 0. // Add 2 to the touch identifier for compatibility. var id = e.pointerId = inTouch.identifier + 2; e.target = captureInfo[id] || findTarget(e); e.bubbles = true; e.cancelable = true; e.detail = this.clickCount; e.button = 0; e.buttons = this.typeToButtons(cte.type); e.width = (inTouch.radiusX || inTouch.webkitRadiusX || 0) * 2; e.height = (inTouch.radiusY || inTouch.webkitRadiusY || 0) * 2; e.pressure = inTouch.force || inTouch.webkitForce || 0.5; e.isPrimary = this.isPrimaryTouch(inTouch); e.pointerType = this.POINTER_TYPE; // forward modifier keys e.altKey = cte.altKey; e.ctrlKey = cte.ctrlKey; e.metaKey = cte.metaKey; e.shiftKey = cte.shiftKey; // forward touch preventDefaults var self = this; e.preventDefault = function() { self.scrolling = false; self.firstXY = null; cte.preventDefault(); }; return e; }, processTouches: function(inEvent, inFunction) { var tl = inEvent.changedTouches; this.currentTouchEvent = inEvent; for (var i = 0, t; i < tl.length; i++) { t = tl[i]; inFunction.call(this, this.touchToPointer(t)); } }, // For single axis scrollers, determines whether the element should emit // pointer events or behave as a scroller shouldScroll: function(inEvent) { if (this.firstXY) { var ret; var scrollAxis = inEvent.currentTarget._scrollType; if (scrollAxis === 'none') { // this element is a touch-action: none, should never scroll ret = false; } else if (scrollAxis === 'XY') { // this element should always scroll ret = true; } else { var t = inEvent.changedTouches[0]; // check the intended scroll axis, and other axis var a = scrollAxis; var oa = scrollAxis === 'Y' ? 'X' : 'Y'; var da = Math.abs(t['client' + a] - this.firstXY[a]); var doa = Math.abs(t['client' + oa] - this.firstXY[oa]); // if delta in the scroll axis > delta other axis, scroll instead of // making events ret = da >= doa; } this.firstXY = null; return ret; } }, findTouch: function(inTL, inId) { for (var i = 0, l = inTL.length, t; i < l && (t = inTL[i]); i++) { if (t.identifier === inId) { return true; } } }, // In some instances, a touchstart can happen without a touchend. This // leaves the pointermap in a broken state. // Therefore, on every touchstart, we remove the touches that did not fire a // touchend event. // To keep state globally consistent, we fire a // pointercancel for this "abandoned" touch vacuumTouches: function(inEvent) { var tl = inEvent.touches; // pointermap.size should be < tl.length here, as the touchstart has not // been processed yet. if (pointermap$1.size >= tl.length) { var d = []; pointermap$1.forEach(function(value, key) { // Never remove pointerId == 1, which is mouse. // Touch identifiers are 2 smaller than their pointerId, which is the // index in pointermap. if (key !== 1 && !this.findTouch(tl, key - 2)) { var p = value.out; d.push(p); } }, this); d.forEach(this.cancelOut, this); } }, touchstart: function(inEvent) { this.vacuumTouches(inEvent); this.setPrimaryTouch(inEvent.changedTouches[0]); this.dedupSynthMouse(inEvent); if (!this.scrolling) { this.clickCount++; this.processTouches(inEvent, this.overDown); } }, overDown: function(inPointer) { pointermap$1.set(inPointer.pointerId, { target: inPointer.target, out: inPointer, outTarget: inPointer.target }); dispatcher.enterOver(inPointer); dispatcher.down(inPointer); }, touchmove: function(inEvent) { if (!this.scrolling) { if (this.shouldScroll(inEvent)) { this.scrolling = true; this.touchcancel(inEvent); } else { inEvent.preventDefault(); this.processTouches(inEvent, this.moveOverOut); } } }, moveOverOut: function(inPointer) { var event = inPointer; var pointer = pointermap$1.get(event.pointerId); // a finger drifted off the screen, ignore it if (!pointer) { return; } var outEvent = pointer.out; var outTarget = pointer.outTarget; dispatcher.move(event); if (outEvent && outTarget !== event.target) { outEvent.relatedTarget = event.target; event.relatedTarget = outTarget; // recover from retargeting by shadow outEvent.target = outTarget; if (event.target) { dispatcher.leaveOut(outEvent); dispatcher.enterOver(event); } else { // clean up case when finger leaves the screen event.target = outTarget; event.relatedTarget = null; this.cancelOut(event); } } pointer.out = event; pointer.outTarget = event.target; }, touchend: function(inEvent) { this.dedupSynthMouse(inEvent); this.processTouches(inEvent, this.upOut); }, upOut: function(inPointer) { if (!this.scrolling) { dispatcher.up(inPointer); dispatcher.leaveOut(inPointer); } this.cleanUpPointer(inPointer); }, touchcancel: function(inEvent) { this.processTouches(inEvent, this.cancelOut); }, cancelOut: function(inPointer) { dispatcher.cancel(inPointer); dispatcher.leaveOut(inPointer); this.cleanUpPointer(inPointer); }, cleanUpPointer: function(inPointer) { pointermap$1.delete(inPointer.pointerId); this.removePrimaryPointer(inPointer); }, // prevent synth mouse events from creating pointer events dedupSynthMouse: function(inEvent) { var lts = mouseEvents.lastTouches; var t = inEvent.changedTouches[0]; // only the primary finger will synth mouse events if (this.isPrimaryTouch(t)) { // remember x/y of last touch var lt = { x: t.clientX, y: t.clientY }; lts.push(lt); var fn = (function(lts, lt) { var i = lts.indexOf(lt); if (i > -1) { lts.splice(i, 1); } }).bind(null, lts, lt); setTimeout(fn, DEDUP_TIMEOUT); } } }; INSTALLER = new Installer(touchEvents.elementAdded, touchEvents.elementRemoved, touchEvents.elementChanged, touchEvents); var pointermap$2 = dispatcher.pointermap; var HAS_BITMAP_TYPE = window.MSPointerEvent && typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE === 'number'; var msEvents = { events: [ 'MSPointerDown', 'MSPointerMove', 'MSPointerUp', 'MSPointerOut', 'MSPointerOver', 'MSPointerCancel', 'MSGotPointerCapture', 'MSLostPointerCapture' ], register: function(target) { dispatcher.listen(target, this.events); }, unregister: function(target) { dispatcher.unlisten(target, this.events); }, POINTER_TYPES: [ '', 'unavailable', 'touch', 'pen', 'mouse' ], prepareEvent: function(inEvent) { var e = inEvent; if (HAS_BITMAP_TYPE) { e = dispatcher.cloneEvent(inEvent); e.pointerType = this.POINTER_TYPES[inEvent.pointerType]; } return e; }, cleanup: function(id) { pointermap$2.delete(id); }, MSPointerDown: function(inEvent) { pointermap$2.set(inEvent.pointerId, inEvent); var e = this.prepareEvent(inEvent); dispatcher.down(e); }, MSPointerMove: function(inEvent) { var e = this.prepareEvent(inEvent); dispatcher.move(e); }, MSPointerUp: function(inEvent) { var e = this.prepareEvent(inEvent); dispatcher.up(e); this.cleanup(inEvent.pointerId); }, MSPointerOut: function(inEvent) { var e = this.prepareEvent(inEvent); dispatcher.leaveOut(e); }, MSPointerOver: function(inEvent) { var e = this.prepareEvent(inEvent); dispatcher.enterOver(e); }, MSPointerCancel: function(inEvent) { var e = this.prepareEvent(inEvent); dispatcher.cancel(e); this.cleanup(inEvent.pointerId); }, MSLostPointerCapture: function(inEvent) { var e = dispatcher.makeEvent('lostpointercapture', inEvent); dispatcher.dispatchEvent(e); }, MSGotPointerCapture: function(inEvent) { var e = dispatcher.makeEvent('gotpointercapture', inEvent); dispatcher.dispatchEvent(e); } }; function applyPolyfill() { // only activate if this platform does not have pointer events if (!window.PointerEvent) { window.PointerEvent = PointerEvent; if (window.navigator.msPointerEnabled) { var tp = window.navigator.msMaxTouchPoints; Object.defineProperty(window.navigator, 'maxTouchPoints', { value: tp, enumerable: true }); dispatcher.registerSource('ms', msEvents); } else { Object.defineProperty(window.navigator, 'maxTouchPoints', { value: 0, enumerable: true }); dispatcher.registerSource('mouse', mouseEvents); if (window.ontouchstart !== undefined) { dispatcher.registerSource('touch', touchEvents); } } dispatcher.register(document); } } var n = window.navigator; var s; var r; var h; function assertActive(id) { if (!dispatcher.pointermap.has(id)) { var error = new Error('InvalidPointerId'); error.name = 'InvalidPointerId'; throw error; } } function assertConnected(elem) { var parent = elem.parentNode; while (parent && parent !== elem.ownerDocument) { parent = parent.parentNode; } if (!parent) { var error = new Error('InvalidStateError'); error.name = 'InvalidStateError'; throw error; } } function inActiveButtonState(id) { var p = dispatcher.pointermap.get(id); return p.buttons !== 0; } if (n.msPointerEnabled) { s = function(pointerId) { assertActive(pointerId); assertConnected(this); if (inActiveButtonState(pointerId)) { dispatcher.setCapture(pointerId, this, true); this.msSetPointerCapture(pointerId); } }; r = function(pointerId) { assertActive(pointerId); dispatcher.releaseCapture(pointerId, true); this.msReleasePointerCapture(pointerId); }; } else { s = function setPointerCapture(pointerId) { assertActive(pointerId); assertConnected(this); if (inActiveButtonState(pointerId)) { dispatcher.setCapture(pointerId, this); } }; r = function releasePointerCapture(pointerId) { assertActive(pointerId); dispatcher.releaseCapture(pointerId); }; } h = function hasPointerCapture(pointerId) { return !!dispatcher.captureInfo[pointerId]; }; function applyPolyfill$1() { if (window.Element && !Element.prototype.setPointerCapture) { Object.defineProperties(Element.prototype, { 'setPointerCapture': { value: s }, 'releasePointerCapture': { value: r }, 'hasPointerCapture': { value: h } }); } } applyAttributeStyles(); applyPolyfill(); applyPolyfill$1(); var pointerevents = { dispatcher: dispatcher, Installer: Installer, PointerEvent: PointerEvent, PointerMap: PointerMap, targetFinding: targeting }; return pointerevents; })); /***/ }), /* 65 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var defaultViewer_1 = __webpack_require__(8); var mappers_1 = __webpack_require__(3); var globals_1 = __webpack_require__(4); /** * Will attach an init function the the DOMContentLoaded event. * The init function will be removed automatically after the event was triggered. */ function initListeners() { document.addEventListener("DOMContentLoaded", init); function init(event) { document.removeEventListener("DOMContentLoaded", init); if (globals_1.viewerGlobals.disableInit) return; InitTags(); } } exports.initListeners = initListeners; /** * Select all HTML tags on the page that match the selector and initialize a viewer * * @param selector the selector to initialize the viewer on (default is 'babylon') */ function InitTags(selector) { if (selector === void 0) { selector = 'babylon'; } var elements = document.querySelectorAll(selector); for (var i = 0; i < elements.length; ++i) { var element = elements.item(i); // get the html configuration var configMapper = mappers_1.mapperManager.getMapper('dom'); var config = configMapper.map(element); var viewer = new defaultViewer_1.DefaultViewer(element, config); } } exports.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